create_application_shortcut_view.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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/create_application_shortcut_view.h"
6
7#include <algorithm>
8
9#include "base/bind.h"
10#include "base/bind_helpers.h"
11#include "base/prefs/pref_service.h"
12#include "base/strings/utf_string_conversions.h"
13#include "base/win/windows_version.h"
14#include "chrome/browser/extensions/tab_helper.h"
15#include "chrome/browser/favicon/favicon_util.h"
16#include "chrome/browser/history/select_favicon_frames.h"
17#include "chrome/browser/profiles/profile.h"
18#include "chrome/browser/ui/browser.h"
19#include "chrome/browser/ui/browser_commands.h"
20#include "chrome/browser/ui/browser_finder.h"
21#include "chrome/browser/ui/views/constrained_window_views.h"
22#include "chrome/browser/ui/web_applications/web_app_ui.h"
23#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
24#include "chrome/common/chrome_constants.h"
25#include "chrome/common/extensions/extension.h"
26#include "chrome/common/pref_names.h"
27#include "content/public/browser/render_view_host.h"
28#include "content/public/browser/render_widget_host_view.h"
29#include "content/public/browser/web_contents.h"
30#include "googleurl/src/gurl.h"
31#include "grit/chromium_strings.h"
32#include "grit/generated_resources.h"
33#include "grit/locale_settings.h"
34#include "grit/theme_resources.h"
35#include "net/base/load_flags.h"
36#include "net/url_request/url_request.h"
37#include "skia/ext/image_operations.h"
38#include "third_party/skia/include/core/SkBitmap.h"
39#include "third_party/skia/include/core/SkPaint.h"
40#include "third_party/skia/include/core/SkRect.h"
41#include "ui/base/l10n/l10n_util.h"
42#include "ui/base/layout.h"
43#include "ui/base/resource/resource_bundle.h"
44#include "ui/gfx/canvas.h"
45#include "ui/gfx/codec/png_codec.h"
46#include "ui/gfx/image/image_family.h"
47#include "ui/gfx/image/image_skia.h"
48#include "ui/views/controls/button/checkbox.h"
49#include "ui/views/controls/image_view.h"
50#include "ui/views/controls/label.h"
51#include "ui/views/layout/grid_layout.h"
52#include "ui/views/layout/layout_constants.h"
53#include "ui/views/widget/widget.h"
54#include "ui/views/window/dialog_client_view.h"
55
56namespace {
57
58const int kIconPreviewSizePixels = 32;
59
60// AppInfoView shows the application icon and title.
61class AppInfoView : public views::View {
62 public:
63  AppInfoView(const string16& title,
64              const string16& description,
65              const gfx::ImageFamily& icon);
66
67  // Updates the title/description of the web app.
68  void UpdateText(const string16& title, const string16& description);
69
70  // Updates the icon of the web app.
71  void UpdateIcon(const gfx::ImageFamily& image);
72
73  // Overridden from views::View:
74  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
75
76 private:
77  // Initializes the controls
78  void Init(const string16& title,
79            const string16& description, const gfx::ImageFamily& icon);
80
81  // Creates or updates description label.
82  void PrepareDescriptionLabel(const string16& description);
83
84  // Sets up layout manager.
85  void SetupLayout();
86
87  views::ImageView* icon_;
88  views::Label* title_;
89  views::Label* description_;
90};
91
92AppInfoView::AppInfoView(const string16& title,
93                         const string16& description,
94                         const gfx::ImageFamily& icon)
95    : icon_(NULL),
96      title_(NULL),
97      description_(NULL) {
98  Init(title, description, icon);
99}
100
101void AppInfoView::Init(const string16& title_text,
102                       const string16& description_text,
103                       const gfx::ImageFamily& icon) {
104  icon_ = new views::ImageView();
105  UpdateIcon(icon);
106  icon_->SetImageSize(gfx::Size(kIconPreviewSizePixels,
107                                kIconPreviewSizePixels));
108
109  title_ = new views::Label(title_text);
110  title_->SetMultiLine(true);
111  title_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
112  title_->SetFont(ui::ResourceBundle::GetSharedInstance().GetFont(
113      ui::ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
114
115  PrepareDescriptionLabel(description_text);
116
117  SetupLayout();
118}
119
120void AppInfoView::PrepareDescriptionLabel(const string16& description) {
121  // Do not make space for the description if it is empty.
122  if (description.empty())
123    return;
124
125  const size_t kMaxLength = 200;
126  const string16 kEllipsis(ASCIIToUTF16(" ... "));
127
128  string16 text = description;
129  if (text.length() > kMaxLength) {
130    text = text.substr(0, kMaxLength);
131    text += kEllipsis;
132  }
133
134  if (description_) {
135    description_->SetText(text);
136  } else {
137    description_ = new views::Label(text);
138    description_->SetMultiLine(true);
139    description_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
140  }
141}
142
143void AppInfoView::SetupLayout() {
144  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
145  SetLayoutManager(layout);
146
147  static const int kColumnSetId = 0;
148  views::ColumnSet* column_set = layout->AddColumnSet(kColumnSetId);
149  column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::LEADING,
150                        20.0f, views::GridLayout::FIXED,
151                        kIconPreviewSizePixels, kIconPreviewSizePixels);
152  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER,
153                        80.0f, views::GridLayout::USE_PREF, 0, 0);
154
155  layout->StartRow(0, kColumnSetId);
156  layout->AddView(icon_, 1, description_ ? 2 : 1);
157  layout->AddView(title_);
158
159  if (description_) {
160    layout->StartRow(0, kColumnSetId);
161    layout->SkipColumns(1);
162    layout->AddView(description_);
163  }
164}
165
166void AppInfoView::UpdateText(const string16& title,
167                             const string16& description) {
168  title_->SetText(title);
169  PrepareDescriptionLabel(description);
170
171  SetupLayout();
172}
173
174void AppInfoView::UpdateIcon(const gfx::ImageFamily& image) {
175  // Get the icon closest to the desired preview size.
176  const gfx::Image* icon = image.GetBest(kIconPreviewSizePixels,
177                                         kIconPreviewSizePixels);
178  if (!icon || icon->IsEmpty())
179    // The family has no icons. Leave the image blank.
180    return;
181  const SkBitmap& bitmap = *icon->ToSkBitmap();
182  if (bitmap.width() == kIconPreviewSizePixels &&
183      bitmap.height() == kIconPreviewSizePixels) {
184    icon_->SetImage(gfx::ImageSkia::CreateFrom1xBitmap(bitmap));
185  } else {
186    // Resize the image to the desired size.
187    SkBitmap resized_bitmap = skia::ImageOperations::Resize(
188        bitmap, skia::ImageOperations::RESIZE_LANCZOS3,
189        kIconPreviewSizePixels, kIconPreviewSizePixels);
190
191    icon_->SetImage(gfx::ImageSkia::CreateFrom1xBitmap(resized_bitmap));
192  }
193}
194
195void AppInfoView::OnPaint(gfx::Canvas* canvas) {
196  gfx::Rect bounds = GetLocalBounds();
197
198  SkRect border_rect = {
199    SkIntToScalar(bounds.x()),
200    SkIntToScalar(bounds.y()),
201    SkIntToScalar(bounds.right()),
202    SkIntToScalar(bounds.bottom())
203  };
204
205  SkPaint border_paint;
206  border_paint.setAntiAlias(true);
207  border_paint.setARGB(0xFF, 0xC8, 0xC8, 0xC8);
208
209  canvas->sk_canvas()->drawRoundRect(border_rect, SkIntToScalar(2),
210                                     SkIntToScalar(2), border_paint);
211
212  SkRect inner_rect = {
213    border_rect.fLeft + SkDoubleToScalar(0.5),
214    border_rect.fTop + SkDoubleToScalar(0.5),
215    border_rect.fRight - SkDoubleToScalar(0.5),
216    border_rect.fBottom - SkDoubleToScalar(0.5),
217  };
218
219  SkPaint inner_paint;
220  inner_paint.setAntiAlias(true);
221  inner_paint.setARGB(0xFF, 0xF8, 0xF8, 0xF8);
222  canvas->sk_canvas()->drawRoundRect(inner_rect, SkDoubleToScalar(1.5),
223                                     SkDoubleToScalar(1.5), inner_paint);
224}
225
226}  // namespace
227
228namespace chrome {
229
230void ShowCreateWebAppShortcutsDialog(gfx::NativeWindow parent_window,
231                                     content::WebContents* web_contents) {
232  CreateBrowserModalDialogViews(
233      new CreateUrlApplicationShortcutView(web_contents),
234      parent_window)->Show();
235}
236
237void ShowCreateChromeAppShortcutsDialog(gfx::NativeWindow parent_window,
238                                        Profile* profile,
239                                        const extensions::Extension* app) {
240  CreateBrowserModalDialogViews(
241      new CreateChromeApplicationShortcutView(profile, app),
242      parent_window)->Show();
243}
244
245}  // namespace chrome
246
247CreateApplicationShortcutView::CreateApplicationShortcutView(Profile* profile)
248    : profile_(profile),
249      app_info_(NULL),
250      create_shortcuts_label_(NULL),
251      desktop_check_box_(NULL),
252      menu_check_box_(NULL),
253      quick_launch_check_box_(NULL) {}
254
255CreateApplicationShortcutView::~CreateApplicationShortcutView() {}
256
257void CreateApplicationShortcutView::InitControls() {
258  // Create controls
259  app_info_ = new AppInfoView(shortcut_info_.title, shortcut_info_.description,
260                              shortcut_info_.favicon);
261  create_shortcuts_label_ = new views::Label(
262      l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_LABEL));
263  create_shortcuts_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
264
265  desktop_check_box_ = AddCheckbox(
266      l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_DESKTOP_CHKBOX),
267      profile_->GetPrefs()->GetBoolean(prefs::kWebAppCreateOnDesktop));
268
269  menu_check_box_ = NULL;
270  quick_launch_check_box_ = NULL;
271
272#if defined(OS_WIN)
273  // Do not allow creating shortcuts on the Start Screen for Windows 8.
274  if (base::win::GetVersion() < base::win::VERSION_WIN8) {
275    menu_check_box_ = AddCheckbox(
276        l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_START_MENU_CHKBOX),
277        profile_->GetPrefs()->GetBoolean(prefs::kWebAppCreateInAppsMenu));
278  }
279
280  quick_launch_check_box_ = AddCheckbox(
281      (base::win::GetVersion() >= base::win::VERSION_WIN7) ?
282        l10n_util::GetStringUTF16(IDS_PIN_TO_TASKBAR_CHKBOX) :
283        l10n_util::GetStringUTF16(
284            IDS_CREATE_SHORTCUTS_QUICK_LAUNCH_BAR_CHKBOX),
285      profile_->GetPrefs()->GetBoolean(prefs::kWebAppCreateInQuickLaunchBar));
286#elif defined(OS_POSIX)
287  menu_check_box_ = AddCheckbox(
288      l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_MENU_CHKBOX),
289      profile_->GetPrefs()->GetBoolean(prefs::kWebAppCreateInAppsMenu));
290#endif
291
292  // Layout controls
293  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
294  SetLayoutManager(layout);
295
296  static const int kHeaderColumnSetId = 0;
297  views::ColumnSet* column_set = layout->AddColumnSet(kHeaderColumnSetId);
298  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER,
299                        100.0f, views::GridLayout::FIXED, 0, 0);
300
301  static const int kTableColumnSetId = 1;
302  column_set = layout->AddColumnSet(kTableColumnSetId);
303  column_set->AddPaddingColumn(0, views::kPanelHorizIndentation);
304  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
305                        100.0f, views::GridLayout::USE_PREF, 0, 0);
306
307  layout->StartRow(0, kHeaderColumnSetId);
308  layout->AddView(app_info_);
309
310  layout->AddPaddingRow(0, views::kPanelSubVerticalSpacing);
311  layout->StartRow(0, kHeaderColumnSetId);
312  layout->AddView(create_shortcuts_label_);
313
314  layout->AddPaddingRow(0, views::kLabelToControlVerticalSpacing);
315  layout->StartRow(0, kTableColumnSetId);
316  layout->AddView(desktop_check_box_);
317
318  if (menu_check_box_ != NULL) {
319    layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
320    layout->StartRow(0, kTableColumnSetId);
321    layout->AddView(menu_check_box_);
322  }
323
324  if (quick_launch_check_box_ != NULL) {
325    layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
326    layout->StartRow(0, kTableColumnSetId);
327    layout->AddView(quick_launch_check_box_);
328  }
329}
330
331gfx::Size CreateApplicationShortcutView::GetPreferredSize() {
332  // TODO(evanm): should this use IDS_CREATE_SHORTCUTS_DIALOG_WIDTH_CHARS?
333  static const int kDialogWidth = 360;
334  int height = GetLayoutManager()->GetPreferredHeightForWidth(this,
335      kDialogWidth);
336  return gfx::Size(kDialogWidth, height);
337}
338
339string16 CreateApplicationShortcutView::GetDialogButtonLabel(
340    ui::DialogButton button) const {
341  if (button == ui::DIALOG_BUTTON_OK)
342    return l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_COMMIT);
343  return views::DialogDelegateView::GetDialogButtonLabel(button);
344}
345
346bool CreateApplicationShortcutView::IsDialogButtonEnabled(
347    ui::DialogButton button) const {
348  if (button == ui::DIALOG_BUTTON_OK)
349    return desktop_check_box_->checked() ||
350           ((menu_check_box_ != NULL) &&
351            menu_check_box_->checked()) ||
352           ((quick_launch_check_box_ != NULL) &&
353            quick_launch_check_box_->checked());
354
355  return true;
356}
357
358ui::ModalType CreateApplicationShortcutView::GetModalType() const {
359  return ui::MODAL_TYPE_WINDOW;
360}
361
362string16 CreateApplicationShortcutView::GetWindowTitle() const {
363  return l10n_util::GetStringUTF16(IDS_CREATE_SHORTCUTS_TITLE);
364}
365
366bool CreateApplicationShortcutView::Accept() {
367  if (!IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK))
368    return false;
369
370  ShellIntegration::ShortcutLocations creation_locations;
371  creation_locations.on_desktop = desktop_check_box_->checked();
372  creation_locations.in_applications_menu = menu_check_box_ == NULL ? false :
373      menu_check_box_->checked();
374  creation_locations.applications_menu_subdir = shortcut_menu_subdir_;
375
376#if defined(OS_WIN)
377  creation_locations.in_quick_launch_bar = quick_launch_check_box_ == NULL ?
378      NULL : quick_launch_check_box_->checked();
379#elif defined(OS_POSIX)
380  // Create shortcut in Mac dock or as Linux (gnome/kde) application launcher
381  // are not implemented yet.
382  creation_locations.in_quick_launch_bar = false;
383#endif
384
385  web_app::CreateShortcuts(shortcut_info_, creation_locations,
386                           web_app::ALLOW_DUPLICATE_SHORTCUTS);
387  return true;
388}
389
390views::Checkbox* CreateApplicationShortcutView::AddCheckbox(
391    const string16& text, bool checked) {
392  views::Checkbox* checkbox = new views::Checkbox(text);
393  checkbox->SetChecked(checked);
394  checkbox->set_listener(this);
395  return checkbox;
396}
397
398void CreateApplicationShortcutView::ButtonPressed(views::Button* sender,
399                                                  const ui::Event& event) {
400  if (sender == desktop_check_box_) {
401    profile_->GetPrefs()->SetBoolean(prefs::kWebAppCreateOnDesktop,
402                                     desktop_check_box_->checked());
403  } else if (sender == menu_check_box_) {
404    profile_->GetPrefs()->SetBoolean(prefs::kWebAppCreateInAppsMenu,
405                                     menu_check_box_->checked());
406  } else if (sender == quick_launch_check_box_) {
407    profile_->GetPrefs()->SetBoolean(prefs::kWebAppCreateInQuickLaunchBar,
408                                     quick_launch_check_box_->checked());
409  }
410
411  // When no checkbox is checked we should not have the action button enabled.
412  GetDialogClientView()->UpdateDialogButtons();
413}
414
415CreateUrlApplicationShortcutView::CreateUrlApplicationShortcutView(
416    content::WebContents* web_contents)
417    : CreateApplicationShortcutView(
418          Profile::FromBrowserContext(web_contents->GetBrowserContext())),
419      web_contents_(web_contents),
420      pending_download_id_(-1)  {
421
422  web_app::GetShortcutInfoForTab(web_contents_, &shortcut_info_);
423  const WebApplicationInfo& app_info =
424      extensions::TabHelper::FromWebContents(web_contents_)->web_app_info();
425  if (!app_info.icons.empty()) {
426    web_app::GetIconsInfo(app_info, &unprocessed_icons_);
427    FetchIcon();
428  }
429
430  // NOTE: Leave shortcut_menu_subdir_ blank to create URL app shortcuts in the
431  // top-level menu.
432
433  InitControls();
434}
435
436CreateUrlApplicationShortcutView::~CreateUrlApplicationShortcutView() {
437}
438
439bool CreateUrlApplicationShortcutView::Accept() {
440  if (!CreateApplicationShortcutView::Accept())
441    return false;
442
443  // Get the smallest icon in the icon family (should have only 1).
444  const gfx::Image* icon = shortcut_info_.favicon.GetBest(0, 0);
445  SkBitmap bitmap = icon ? icon->AsBitmap() : SkBitmap();
446  extensions::TabHelper::FromWebContents(web_contents_)->SetAppIcon(bitmap);
447  Browser* browser = chrome::FindBrowserWithWebContents(web_contents_);
448  if (browser)
449    chrome::ConvertTabToAppWindow(browser, web_contents_);
450  return true;
451}
452
453void CreateUrlApplicationShortcutView::FetchIcon() {
454  // There should only be fetch job at a time.
455  DCHECK_EQ(-1, pending_download_id_);
456
457  if (unprocessed_icons_.empty())  // No icons to fetch.
458    return;
459
460  int preferred_size = std::max(unprocessed_icons_.back().width,
461                                unprocessed_icons_.back().height);
462  pending_download_id_ = web_contents_->DownloadImage(
463      unprocessed_icons_.back().url,
464      true,  // is a favicon
465      preferred_size,
466      0,  // no maximum size
467      base::Bind(&CreateUrlApplicationShortcutView::DidDownloadFavicon,
468                 base::Unretained(this)));
469
470  unprocessed_icons_.pop_back();
471}
472
473void CreateUrlApplicationShortcutView::DidDownloadFavicon(
474    int id,
475    int http_status_code,
476    const GURL& image_url,
477    int requested_size,
478    const std::vector<SkBitmap>& bitmaps) {
479  if (id != pending_download_id_)
480    return;
481  pending_download_id_ = -1;
482
483  SkBitmap image;
484
485  if (!bitmaps.empty()) {
486    std::vector<ui::ScaleFactor> scale_factors;
487    ui::ScaleFactor scale_factor = ui::GetScaleFactorForNativeView(
488        web_contents_->GetRenderViewHost()->GetView()->GetNativeView());
489    scale_factors.push_back(scale_factor);
490    size_t closest_index = FaviconUtil::SelectBestFaviconFromBitmaps(
491        bitmaps,
492        scale_factors,
493        requested_size);
494    image = bitmaps[closest_index];
495  }
496
497  if (!image.isNull()) {
498    shortcut_info_.favicon.Add(gfx::ImageSkia::CreateFrom1xBitmap(image));
499    static_cast<AppInfoView*>(app_info_)->UpdateIcon(shortcut_info_.favicon);
500  } else {
501    FetchIcon();
502  }
503}
504
505CreateChromeApplicationShortcutView::CreateChromeApplicationShortcutView(
506    Profile* profile,
507    const extensions::Extension* app) :
508      CreateApplicationShortcutView(profile),
509      app_(app),
510      weak_ptr_factory_(this) {
511  // Required by InitControls().
512  shortcut_info_.title = UTF8ToUTF16(app->name());
513  shortcut_info_.description = UTF8ToUTF16(app->description());
514
515  // Place Chrome app shortcuts in the "Chrome Apps" submenu.
516  shortcut_menu_subdir_ = web_app::GetAppShortcutsSubdirName();
517
518  InitControls();
519
520  // Get shortcut information and icon now; they are needed for our UI.
521  web_app::UpdateShortcutInfoAndIconForApp(
522      *app, profile,
523      base::Bind(&CreateChromeApplicationShortcutView::OnShortcutInfoLoaded,
524                 weak_ptr_factory_.GetWeakPtr()));
525}
526
527CreateChromeApplicationShortcutView::~CreateChromeApplicationShortcutView() {}
528
529// Called when the app's ShortcutInfo (with icon) is loaded.
530void CreateChromeApplicationShortcutView::OnShortcutInfoLoaded(
531    const ShellIntegration::ShortcutInfo& shortcut_info) {
532  shortcut_info_ = shortcut_info;
533
534  CHECK(app_info_);
535  static_cast<AppInfoView*>(app_info_)->UpdateIcon(shortcut_info_.favicon);
536}
537