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 #include "content/shell/shell_login_dialog.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/logging.h"
10 #include "base/mac/bundle_locations.h"
11 #import "base/mac/cocoa_protocols.h"
12 #import "base/memory/scoped_nsobject.h"
13 #include "base/sys_string_conversions.h"
14 #include "content/public/browser/browser_thread.h"
15 #import "ui/base/cocoa/nib_loading.h"
19 const int kUsernameFieldTag = 1;
20 const int kPasswordFieldTag = 2;
24 // Helper object that receives the notification that the dialog/sheet is
26 @interface ShellLoginDialogHelper : NSObject<NSAlertDelegate> {
28 scoped_nsobject<NSAlert> alert_;
29 NSTextField* usernameField_; // WEAK; owned by alert_
30 NSSecureTextField* passwordField_; // WEAK; owned by alert_
34 - (NSView*)accessoryView;
36 - (void)alertDidEnd:(NSAlert*)alert
37 returnCode:(int)returnCode
38 contextInfo:(void*)contextInfo;
43 @implementation ShellLoginDialogHelper
46 alert_.reset([[NSAlert alloc] init]);
47 [alert_ setAccessoryView:[self accessoryView]];
51 - (NSView*)accessoryView {
52 NSView* accessory_view = ui::GetViewFromNib(@"HttpAuth");
56 usernameField_ = [accessory_view viewWithTag:kUsernameFieldTag];
57 passwordField_ = [accessory_view viewWithTag:kPasswordFieldTag];
58 return accessory_view;
62 [[alert_ window] makeFirstResponder:usernameField_];
65 - (void)alertDidEnd:(NSAlert*)alert
66 returnCode:(int)returnCode
67 contextInfo:(void*)contextInfo {
68 if (returnCode == NSRunStoppedResponse)
71 content::ShellLoginDialog* this_dialog =
72 reinterpret_cast<content::ShellLoginDialog*>(contextInfo);
73 if (returnCode == NSAlertFirstButtonReturn) {
74 this_dialog->UserAcceptedAuth(
75 base::SysNSStringToUTF16([usernameField_ stringValue]),
76 base::SysNSStringToUTF16([passwordField_ stringValue]));
78 this_dialog->UserCancelledAuth();
83 [NSApp endSheet:[alert_ window]];
91 void ShellLoginDialog::PlatformCreateDialog(const string16& message) {
92 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
93 helper_ = [[ShellLoginDialogHelper alloc] init];
95 // Show the modal dialog.
96 NSAlert* alert = [helper_ alert];
97 [alert setDelegate:helper_];
98 [alert setInformativeText:base::SysUTF16ToNSString(message)];
99 [alert setMessageText:@"Please log in."];
100 [alert addButtonWithTitle:@"OK"];
101 NSButton* other = [alert addButtonWithTitle:@"Cancel"];
102 [other setKeyEquivalent:@"\e"];
104 beginSheetModalForWindow:nil // nil here makes it app-modal
105 modalDelegate:helper_
106 didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
112 void ShellLoginDialog::PlatformCleanUp() {
113 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
118 void ShellLoginDialog::PlatformRequestCancelled() {
119 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
123 } // namespace content