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.
5 #import "chrome/browser/ui/cocoa/download/download_item_controller.h"
7 #include "base/mac/bundle_locations.h"
8 #include "base/mac/mac_util.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string16.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/sys_string_conversions.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/download/chrome_download_manager_delegate.h"
15 #include "chrome/browser/download/download_item_model.h"
16 #include "chrome/browser/download/download_shelf_context_menu.h"
17 #import "chrome/browser/themes/theme_properties.h"
18 #import "chrome/browser/themes/theme_service.h"
19 #import "chrome/browser/ui/cocoa/download/download_item_button.h"
20 #import "chrome/browser/ui/cocoa/download/download_item_cell.h"
21 #include "chrome/browser/ui/cocoa/download/download_item_mac.h"
22 #import "chrome/browser/ui/cocoa/download/download_shelf_context_menu_controller.h"
23 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
24 #import "chrome/browser/ui/cocoa/themed_window.h"
25 #import "chrome/browser/ui/cocoa/ui_localizer.h"
26 #include "content/public/browser/download_item.h"
27 #include "content/public/browser/page_navigator.h"
28 #include "grit/generated_resources.h"
29 #include "grit/theme_resources.h"
30 #include "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h"
31 #include "ui/base/l10n/l10n_util_mac.h"
32 #include "ui/base/resource/resource_bundle.h"
33 #include "ui/gfx/text_elider.h"
34 #include "ui/gfx/font.h"
35 #include "ui/gfx/image/image.h"
37 using content::DownloadItem;
41 // NOTE: Mac currently doesn't use this like Windows does. Mac uses this to
42 // control the min size on the dangerous download text. TVL sent a query off to
43 // UX to fully spec all the the behaviors of download items and truncations
44 // rules so all platforms can get inline in the future.
45 const int kTextWidth = 140; // Pixels
47 // The maximum width in pixels for the file name tooltip.
48 const int kToolTipMaxWidth = 900;
51 // Helper to widen a view.
52 void WidenView(NSView* view, CGFloat widthChange) {
53 // If it is an NSBox, the autoresize of the contentView is the issue.
54 NSView* contentView = view;
55 if ([view isKindOfClass:[NSBox class]]) {
56 contentView = [(NSBox*)view contentView];
58 BOOL autoresizesSubviews = [contentView autoresizesSubviews];
59 if (autoresizesSubviews) {
60 [contentView setAutoresizesSubviews:NO];
63 NSRect frame = [view frame];
64 frame.size.width += widthChange;
65 [view setFrame:frame];
67 if (autoresizesSubviews) {
68 [contentView setAutoresizesSubviews:YES];
74 class DownloadShelfContextMenuMac : public DownloadShelfContextMenu {
76 DownloadShelfContextMenuMac(DownloadItem* downloadItem,
77 content::PageNavigator* navigator)
78 : DownloadShelfContextMenu(downloadItem, navigator) { }
80 // DownloadShelfContextMenu::GetMenuModel is protected.
81 using DownloadShelfContextMenu::GetMenuModel;
84 @interface DownloadItemController (Private)
85 - (void)themeDidChangeNotification:(NSNotification*)aNotification;
86 - (void)updateTheme:(ui::ThemeProvider*)themeProvider;
87 - (void)setState:(DownoadItemState)state;
90 // Implementation of DownloadItemController
92 @implementation DownloadItemController
94 - (id)initWithDownload:(DownloadItem*)downloadItem
95 shelf:(DownloadShelfController*)shelf
96 navigator:(content::PageNavigator*)navigator {
97 if ((self = [super initWithNibName:@"DownloadItem"
98 bundle:base::mac::FrameworkBundle()])) {
99 // Must be called before [self view], so that bridge_ is set in awakeFromNib
100 bridge_.reset(new DownloadItemMac(downloadItem, self));
101 menuBridge_.reset(new DownloadShelfContextMenuMac(downloadItem, navigator));
103 NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
104 [defaultCenter addObserver:self
105 selector:@selector(themeDidChangeNotification:)
106 name:kBrowserThemeDidChangeNotification
111 creationTime_ = base::Time::Now();
112 font_list_.reset(new gfx::FontList(
113 ui::ResourceBundle::GetSharedInstance().GetFontList(
114 ui::ResourceBundle::BaseFont)));
120 [[NSNotificationCenter defaultCenter] removeObserver:self];
121 [progressView_ setController:nil];
122 [[self view] removeFromSuperview];
126 - (void)awakeFromNib {
127 [progressView_ setController:self];
129 GTMUILocalizerAndLayoutTweaker* localizerAndLayoutTweaker =
130 [[[GTMUILocalizerAndLayoutTweaker alloc] init] autorelease];
131 [localizerAndLayoutTweaker applyLocalizer:localizer_ tweakingUI:[self view]];
133 [self setStateFromDownload:bridge_->download_model()];
136 [self updateToolTip];
139 - (void)showDangerousWarning:(DownloadItemModel*)downloadModel {
140 // The transition from safe -> dangerous should only happen once. The code
141 // assumes that the danger type of the download doesn't change once it's set.
142 if ([self isDangerousMode])
145 [self setState:kDangerous];
147 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
150 NSString* dangerousWarning = base::SysUTF16ToNSString(
151 downloadModel->GetWarningText(*font_list_, kTextWidth));
152 DCHECK(dangerousWarning);
153 [dangerousDownloadLabel_ setStringValue:dangerousWarning];
154 CGFloat labelWidthChange =
155 [GTMUILocalizerAndLayoutTweaker
156 sizeToFitFixedHeightTextField:dangerousDownloadLabel_
157 minWidth:kTextWidth];
158 CGFloat buttonWidthChange = 0.0;
160 if (downloadModel->MightBeMalicious()) {
161 alertIcon = rb.GetNativeImageNamed(IDR_SAFEBROWSING_WARNING).ToNSImage();
162 buttonWidthChange = [maliciousButtonTweaker_ changedWidth];
164 // Move the buttons to account for the change in label size.
165 NSPoint frameOrigin = [maliciousButtonTweaker_ frame].origin;
166 frameOrigin.x += labelWidthChange;
167 [maliciousButtonTweaker_ setFrameOrigin:frameOrigin];
169 [dangerousButtonTweaker_ setHidden:YES];
170 [maliciousButtonTweaker_ setHidden:NO];
172 alertIcon = rb.GetNativeImageNamed(IDR_WARNING).ToNSImage();
173 buttonWidthChange = [dangerousButtonTweaker_ changedWidth];
175 // The text on the confirm button can change depending on the type of the
177 NSString* confirmButtonTitle =
178 base::SysUTF16ToNSString(downloadModel->GetWarningConfirmButtonText());
179 DCHECK(confirmButtonTitle);
180 [dangerousDownloadConfirmButton_ setTitle:confirmButtonTitle];
182 // Move the button to account for the change in label size.
183 NSPoint frameOrigin = [dangerousButtonTweaker_ frame].origin;
184 frameOrigin.x += labelWidthChange;
185 [dangerousButtonTweaker_ setFrameOrigin:frameOrigin];
187 [dangerousButtonTweaker_ setHidden:NO];
188 [maliciousButtonTweaker_ setHidden:YES];
191 [image_ setImage:alertIcon];
193 // Grow the parent views
194 WidenView([self view], labelWidthChange + buttonWidthChange);
195 WidenView(dangerousDownloadView_, labelWidthChange + buttonWidthChange);
198 - (void)setStateFromDownload:(DownloadItemModel*)downloadModel {
199 DCHECK_EQ([self download], downloadModel->download());
201 // Handle dangerous downloads.
202 if (downloadModel->IsDangerous()) {
203 [self showDangerousWarning:downloadModel];
207 // Set path to draggable download on completion.
208 if (downloadModel->download()->GetState() == DownloadItem::COMPLETE)
209 [progressView_ setDownload:downloadModel->download()->GetTargetFilePath()];
211 [cell_ setStateFromDownload:downloadModel];
214 - (void)setIcon:(NSImage*)icon {
215 [cell_ setImage:icon];
219 // We are deleted after this!
220 [shelf_ remove:self];
223 - (void)updateVisibility:(id)sender {
224 if ([[self view] window])
225 [self updateTheme:[[[self view] window] themeProvider]];
227 NSView* view = [self view];
228 NSRect containerFrame = [[view superview] frame];
229 [view setHidden:(NSMaxX([view frame]) > NSWidth(containerFrame))];
232 - (void)downloadWasOpened {
233 [shelf_ downloadWasOpened:self];
236 - (IBAction)handleButtonClick:(id)sender {
237 NSEvent* event = [NSApp currentEvent];
238 DownloadItem* download = [self download];
239 if ([event modifierFlags] & NSCommandKeyMask) {
240 // Let cmd-click show the file in Finder, like e.g. in Safari and Spotlight.
241 download->ShowDownloadInShell();
243 download->OpenDownload();
247 - (NSSize)preferredSize {
248 if (state_ == kNormal)
249 return [progressView_ frame].size;
250 DCHECK_EQ(kDangerous, state_);
251 return [dangerousDownloadView_ frame].size;
254 - (DownloadItem*)download {
255 return bridge_->download_model()->download();
258 - (ui::MenuModel*)contextMenuModel {
259 return menuBridge_->GetMenuModel();
262 - (void)updateToolTip {
263 base::string16 tooltip_text =
264 bridge_->download_model()->GetTooltipText(*font_list_, kToolTipMaxWidth);
265 [progressView_ setToolTip:base::SysUTF16ToNSString(tooltip_text)];
268 - (void)clearDangerousMode {
269 [self setState:kNormal];
270 // The state change hide the dangerouse download view and is now showing the
271 // download progress view. This means the view is likely to be a different
272 // size, so trigger a shelf layout to fix up spacing.
273 [shelf_ layoutItems];
276 - (BOOL)isDangerousMode {
277 return state_ == kDangerous;
280 - (void)setState:(DownoadItemState)state {
284 if (state_ == kNormal) {
285 [progressView_ setHidden:NO];
286 [dangerousDownloadView_ setHidden:YES];
288 DCHECK_EQ(kDangerous, state_);
289 [progressView_ setHidden:YES];
290 [dangerousDownloadView_ setHidden:NO];
292 // NOTE: Do not relayout the shelf, as this could get called during initial
293 // setup of the the item, so the localized text and sizing might not have
297 // Called after a theme change took place, possibly for a different profile.
298 - (void)themeDidChangeNotification:(NSNotification*)notification {
299 [self updateTheme:[[[self view] window] themeProvider]];
302 // Adapt appearance to the current theme. Called after theme changes and before
303 // this is shown for the first time.
304 - (void)updateTheme:(ui::ThemeProvider*)themeProvider {
308 NSColor* color = themeProvider->GetNSColor(ThemeProperties::COLOR_TAB_TEXT);
309 [dangerousDownloadLabel_ setTextColor:color];
312 - (IBAction)saveDownload:(id)sender {
313 // The user has confirmed a dangerous download. We record how quickly the
314 // user did this to detect whether we're being clickjacked.
315 UMA_HISTOGRAM_LONG_TIMES("clickjacking.save_download",
316 base::Time::Now() - creationTime_);
317 // This will change the state and notify us.
318 bridge_->download_model()->download()->ValidateDangerousDownload();
321 - (IBAction)discardDownload:(id)sender {
322 UMA_HISTOGRAM_LONG_TIMES("clickjacking.discard_download",
323 base::Time::Now() - creationTime_);
324 DownloadItem* download = bridge_->download_model()->download();
326 // WARNING: we are deleted at this point. Don't access 'this'.
329 - (IBAction)dismissMaliciousDownload:(id)sender {
331 // WARNING: we are deleted at this point.
334 - (IBAction)showContextMenu:(id)sender {
335 base::scoped_nsobject<DownloadShelfContextMenuController> menuController(
336 [[DownloadShelfContextMenuController alloc]
337 initWithItemController:self
339 [NSMenu popUpContextMenu:[menuController menu]
340 withEvent:[NSApp currentEvent]
341 forView:[self view]];