Add unit test for the Settings API Bubble.
[chromium-blink-merge.git] / chrome / browser / ui / cocoa / media_picker / desktop_media_picker_controller.mm
blob25994549d7d69e37abfb05bc01da0fca6541bf14
1 // Copyright 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.
5 #import "chrome/browser/ui/cocoa/media_picker/desktop_media_picker_controller.h"
7 #include "base/bind.h"
8 #import "base/mac/bundle_locations.h"
9 #include "base/strings/sys_string_conversions.h"
10 #import "chrome/browser/ui/cocoa/media_picker/desktop_media_picker_item.h"
11 #include "content/public/browser/browser_thread.h"
12 #include "grit/generated_resources.h"
13 #import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h"
14 #import "ui/base/cocoa/flipped_view.h"
15 #import "ui/base/cocoa/window_size_constants.h"
16 #include "ui/base/l10n/l10n_util.h"
17 #include "ui/gfx/image/image_skia_util_mac.h"
19 namespace {
21 const int kInitialContentWidth = 620;
22 const int kMinimumContentWidth = 500;
23 const int kMinimumContentHeight = 390;
24 const int kThumbnailWidth = 150;
25 const int kThumbnailHeight = 150;
26 const int kFramePadding = 20;
27 const int kControlSpacing = 10;
28 const int kExcessButtonPadding = 6;
30 }  // namespace
32 @interface DesktopMediaPickerController (Private)
34 // Populate the window with controls and views.
35 - (void)initializeContentsWithAppName:(const base::string16&)appName;
37 // Create a |NSTextField| with label traits given |width|. Frame height is
38 // automatically adjusted to fit.
39 - (NSTextField*)createTextFieldWithText:(NSString*)text
40                              frameWidth:(CGFloat)width;
42 // Create a button with |title|, with size adjusted to fit.
43 - (NSButton*)createButtonWithTitle:(NSString*)title;
45 // Report result by invoking |doneCallback_|. The callback is invoked only on
46 // the first call to |reportResult:|. Subsequent calls will be no-ops.
47 - (void)reportResult:(content::DesktopMediaID)sourceID;
49 // Action handlers.
50 - (void)sharePressed:(id)sender;
51 - (void)cancelPressed:(id)sender;
53 @end
55 @implementation DesktopMediaPickerController
57 - (id)initWithMediaList:(scoped_ptr<DesktopMediaList>)media_list
58                  parent:(NSWindow*)parent
59                callback:(const DesktopMediaPicker::DoneCallback&)callback
60                 appName:(const base::string16&)appName
61              targetName:(const base::string16&)targetName {
62   const NSUInteger kStyleMask =
63       NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask;
64   base::scoped_nsobject<NSWindow> window(
65       [[NSWindow alloc] initWithContentRect:ui::kWindowSizeDeterminedLater
66                                   styleMask:kStyleMask
67                                     backing:NSBackingStoreBuffered
68                                       defer:NO]);
70   if ((self = [super initWithWindow:window])) {
71     [parent addChildWindow:window ordered:NSWindowAbove];
72     [window setDelegate:self];
73     [self initializeContentsWithAppName:appName targetName:targetName];
74     media_list_ = media_list.Pass();
75     media_list_->SetViewDialogWindowId([window windowNumber]);
76     doneCallback_ = callback;
77     items_.reset([[NSMutableArray alloc] init]);
78     bridge_.reset(new DesktopMediaPickerBridge(self));
79   }
80   return self;
83 - (void)dealloc {
84   [sourceBrowser_ setDelegate:nil];
85   [sourceBrowser_ setDataSource:nil];
86   [super dealloc];
89 - (void)initializeContentsWithAppName:(const base::string16&)appName
90                            targetName:(const base::string16&)targetName {
91   // Use flipped coordinates to facilitate manual layout.
92   const CGFloat kPaddedWidth = kInitialContentWidth - (kFramePadding * 2);
93   base::scoped_nsobject<FlippedView> content(
94       [[FlippedView alloc] initWithFrame:NSZeroRect]);
95   [[self window] setContentView:content];
96   NSPoint origin = NSMakePoint(kFramePadding, kFramePadding);
98   // Set the dialog's title.
99   NSString* titleText = l10n_util::GetNSStringF(
100       IDS_DESKTOP_MEDIA_PICKER_TITLE, appName);
101   [[self window] setTitle:titleText];
103   // Set the dialog's description.
104   NSString* descriptionText;
105   if (appName == targetName) {
106     descriptionText = l10n_util::GetNSStringF(
107         IDS_DESKTOP_MEDIA_PICKER_TEXT, appName);
108   } else {
109     descriptionText = l10n_util::GetNSStringF(
110         IDS_DESKTOP_MEDIA_PICKER_TEXT_DELEGATED, appName, targetName);
111   }
112   NSTextField* description = [self createTextFieldWithText:descriptionText
113                                                 frameWidth:kPaddedWidth];
114   [description setFrameOrigin:origin];
115   [content addSubview:description];
116   origin.y += NSHeight([description frame]) + kControlSpacing;
118   // Create the image browser.
119   sourceBrowser_.reset([[IKImageBrowserView alloc] initWithFrame:NSZeroRect]);
120   NSUInteger cellStyle = IKCellsStyleShadowed | IKCellsStyleTitled;
121   [sourceBrowser_ setDelegate:self];
122   [sourceBrowser_ setDataSource:self];
123   [sourceBrowser_ setCellsStyleMask:cellStyle];
124   [sourceBrowser_ setCellSize:NSMakeSize(kThumbnailWidth, kThumbnailHeight)];
126   // Create a scroll view to host the image browser.
127   NSRect imageBrowserScrollFrame = NSMakeRect(
128       origin.x, origin.y, kPaddedWidth, 350);
129   base::scoped_nsobject<NSScrollView> imageBrowserScroll(
130       [[NSScrollView alloc] initWithFrame:imageBrowserScrollFrame]);
131   [imageBrowserScroll setHasVerticalScroller:YES];
132   [imageBrowserScroll setDocumentView:sourceBrowser_];
133   [imageBrowserScroll setBorderType:NSBezelBorder];
134   [imageBrowserScroll setAutoresizingMask:
135       NSViewWidthSizable | NSViewHeightSizable];
136   [content addSubview:imageBrowserScroll];
137   origin.y += NSHeight(imageBrowserScrollFrame) + kControlSpacing;
139   // Create the share button.
140   shareButton_ = [self createButtonWithTitle:l10n_util::GetNSString(
141       IDS_DESKTOP_MEDIA_PICKER_SHARE)];
142   origin.x = kInitialContentWidth - kFramePadding -
143       (NSWidth([shareButton_ frame]) - kExcessButtonPadding);
144   [shareButton_ setEnabled:NO];
145   [shareButton_ setFrameOrigin:origin];
146   [shareButton_ setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
147   [shareButton_ setTarget:self];
148   [shareButton_ setAction:@selector(sharePressed:)];
149   [content addSubview:shareButton_];
151   // Create the cancel button.
152   cancelButton_ =
153       [self createButtonWithTitle:l10n_util::GetNSString(IDS_CANCEL)];
154   origin.x -= kControlSpacing +
155       (NSWidth([cancelButton_ frame]) - (kExcessButtonPadding * 2));
156   [cancelButton_ setFrameOrigin:origin];
157   [cancelButton_ setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
158   [cancelButton_ setTarget:self];
159   [cancelButton_ setAction:@selector(cancelPressed:)];
160   [content addSubview:cancelButton_];
161   origin.y += kFramePadding +
162       (NSHeight([cancelButton_ frame]) - kExcessButtonPadding);
164   // Resize window to fit.
165   [[[self window] contentView] setAutoresizesSubviews:NO];
166   [[self window] setContentSize:NSMakeSize(kInitialContentWidth, origin.y)];
167   [[self window] setContentMinSize:
168       NSMakeSize(kMinimumContentWidth, kMinimumContentHeight)];
169   [[[self window] contentView] setAutoresizesSubviews:YES];
172 - (void)showWindow:(id)sender {
173   // Signal the media_list to start sending thumbnails. |bridge_| is used as the
174   // observer, and will forward notifications to this object.
175   media_list_->SetThumbnailSize(gfx::Size(kThumbnailWidth, kThumbnailHeight));
176   media_list_->StartUpdating(bridge_.get());
178   [self.window center];
179   [super showWindow:sender];
182 - (void)reportResult:(content::DesktopMediaID)sourceID {
183   if (doneCallback_.is_null()) {
184     return;
185   }
187   // Notify the |callback_| asynchronously because it may release the
188   // controller.
189   content::BrowserThread::PostTask(
190       content::BrowserThread::UI, FROM_HERE,
191       base::Bind(doneCallback_, sourceID));
192   doneCallback_.Reset();
195 - (void)sharePressed:(id)sender {
196   NSIndexSet* indexes = [sourceBrowser_ selectionIndexes];
197   NSUInteger selectedIndex = [indexes firstIndex];
198   DesktopMediaPickerItem* item =
199       [items_ objectAtIndex:selectedIndex];
200   [self reportResult:[item sourceID]];
201   [self close];
204 - (void)cancelPressed:(id)sender {
205   [self reportResult:content::DesktopMediaID()];
206   [self close];
209 - (NSTextField*)createTextFieldWithText:(NSString*)text
210                              frameWidth:(CGFloat)width {
211   NSRect frame = NSMakeRect(0, 0, width, 1);
212   base::scoped_nsobject<NSTextField> textField(
213       [[NSTextField alloc] initWithFrame:frame]);
214   [textField setEditable:NO];
215   [textField setSelectable:YES];
216   [textField setDrawsBackground:NO];
217   [textField setBezeled:NO];
218   [textField setStringValue:text];
219   [textField setFont:[NSFont systemFontOfSize:13]];
220   [textField setAutoresizingMask:NSViewWidthSizable];
221   [GTMUILocalizerAndLayoutTweaker sizeToFitFixedWidthTextField:textField];
222   return textField.autorelease();
225 - (NSButton*)createButtonWithTitle:(NSString*)title {
226   base::scoped_nsobject<NSButton> button(
227       [[NSButton alloc] initWithFrame:NSZeroRect]);
228   [button setButtonType:NSMomentaryPushInButton];
229   [button setBezelStyle:NSRoundedBezelStyle];
230   [button setTitle:title];
231   [GTMUILocalizerAndLayoutTweaker sizeToFitView:button];
232   return button.autorelease();
235 #pragma mark NSWindowDelegate
237 - (void)windowWillClose:(NSNotification*)notification {
238   // Report the result if it hasn't been reported yet. |reportResult:| ensures
239   // that the result is only reported once.
240   [self reportResult:content::DesktopMediaID()];
242   // Remove self from the parent.
243   NSWindow* window = [self window];
244   [[window parentWindow] removeChildWindow:window];
247 #pragma mark IKImageBrowserDataSource
249 - (NSUInteger)numberOfItemsInImageBrowser:(IKImageBrowserView*)browser {
250   return [items_ count];
253 - (id)imageBrowser:(IKImageBrowserView *)browser
254        itemAtIndex:(NSUInteger)index {
255   return [items_ objectAtIndex:index];
258 #pragma mark IKImageBrowserDelegate
260 - (void)imageBrowser:(IKImageBrowserView *)browser
261       cellWasDoubleClickedAtIndex:(NSUInteger)index {
262   DesktopMediaPickerItem* item = [items_ objectAtIndex:index];
263   [self reportResult:[item sourceID]];
264   [self close];
267 - (void)imageBrowserSelectionDidChange:(IKImageBrowserView*) aBrowser {
268   // Enable or disable the OK button based on whether we have a selection.
269   [shareButton_ setEnabled:([[sourceBrowser_ selectionIndexes] count] > 0)];
272 #pragma mark DesktopMediaPickerObserver
274 - (void)sourceAddedAtIndex:(int)index {
275   const DesktopMediaList::Source& source = media_list_->GetSource(index);
276   NSString* imageTitle = base::SysUTF16ToNSString(source.name);
277   base::scoped_nsobject<DesktopMediaPickerItem> item(
278       [[DesktopMediaPickerItem alloc] initWithSourceId:source.id
279                                               imageUID:++lastImageUID_
280                                             imageTitle:imageTitle]);
281   [items_ insertObject:item atIndex:index];
282   [sourceBrowser_ reloadData];
285 - (void)sourceRemovedAtIndex:(int)index {
286   if ([[sourceBrowser_ selectionIndexes] containsIndex:index]) {
287     // Selected item was removed. Clear selection.
288     [sourceBrowser_ setSelectionIndexes:[NSIndexSet indexSet]
289                       byExtendingSelection:FALSE];
290   }
291   [items_ removeObjectAtIndex:index];
292   [sourceBrowser_ reloadData];
295 - (void)sourceMovedFrom:(int)oldIndex to:(int)newIndex {
296   base::scoped_nsobject<DesktopMediaPickerItem> item(
297       [[items_ objectAtIndex:oldIndex] retain]);
298   [items_ removeObjectAtIndex:oldIndex];
299   [items_ insertObject:item atIndex:newIndex];
300   [sourceBrowser_ reloadData];
303 - (void)sourceNameChangedAtIndex:(int)index {
304   DesktopMediaPickerItem* item = [items_ objectAtIndex:index];
305   const DesktopMediaList::Source& source = media_list_->GetSource(index);
306   [item setImageTitle:base::SysUTF16ToNSString(source.name)];
307   [sourceBrowser_ reloadData];
310 - (void)sourceThumbnailChangedAtIndex:(int)index {
311   const DesktopMediaList::Source& source = media_list_->GetSource(index);
312   NSImage* image = gfx::NSImageFromImageSkia(source.thumbnail);
314   DesktopMediaPickerItem* item = [items_ objectAtIndex:index];
315   [item setImageRepresentation:image];
316   [sourceBrowser_ reloadData];
319 @end  // @interface DesktopMediaPickerController