summaryrefslogtreecommitdiffstats
path: root/chrome/browser/autofill/autofill_dialog_controller_mac.mm
blob: c867497bcb28ee677aef41f808bed76d1965097e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/autofill/autofill_dialog_controller_mac.h"
#include "app/l10n_util.h"
#include "base/mac_util.h"
#include "base/sys_string_conversions.h"
#import "chrome/browser/autofill/autofill_address_model_mac.h"
#import "chrome/browser/autofill/autofill_address_view_controller_mac.h"
#import "chrome/browser/autofill/autofill_credit_card_model_mac.h"
#import "chrome/browser/autofill/autofill_credit_card_view_controller_mac.h"
#import "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/browser_process.h"
#import "chrome/browser/cocoa/disclosure_view_controller.h"
#import "chrome/browser/cocoa/section_separator_view.h"
#import "chrome/browser/cocoa/window_size_autosaver.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"

// Private interface.
@interface AutoFillDialogController (PrivateAPI)
// Asyncronous handler for when PersonalDataManager data loads.  The
// personal data manager notifies the dialog with this method when the
// data loading is complete and ready to be used.
- (void)onPersonalDataLoaded:(const std::vector<AutoFillProfile*>&)profiles
                 creditCards:(const std::vector<CreditCard*>&)creditCards;
@end

namespace AutoFillDialogControllerInternal {

// PersonalDataManagerObserver facilitates asynchronous loading of
// PersonalDataManager data before showing the AutoFill settings data to the
// user.  It acts as a C++-based delegate for the |AutoFillDialogController|.
class PersonalDataManagerObserver : public PersonalDataManager::Observer {
 public:
  explicit PersonalDataManagerObserver(
      AutoFillDialogController* controller,
      PersonalDataManager* personal_data_manager,
      Profile* profile)
      : controller_(controller),
        personal_data_manager_(personal_data_manager),
        profile_(profile) {
  }

  virtual ~PersonalDataManagerObserver();

  // Notifies the observer that the PersonalDataManager has finished loading.
  virtual void OnPersonalDataLoaded();

 private:
  // Utility method to remove |this| from |personal_data_manager_| as an
  // observer.
  void RemoveObserver();

  // The dialog controller to be notified when the data loading completes.
  // Weak reference.
  AutoFillDialogController* controller_;

  // The object in which we are registered as an observer.  We hold on to
  // it to facilitate un-registering ourself in the destructor and in the
  // |OnPersonalDataLoaded| method.  This may be NULL.
  // Weak reference.
  PersonalDataManager* personal_data_manager_;

  // Profile of caller.  Held as weak reference.  May not be NULL.
  Profile* profile_;

 private:
  DISALLOW_COPY_AND_ASSIGN(PersonalDataManagerObserver);
};

// During destruction ensure that we are removed from the
// |personal_data_manager_| as an observer.
PersonalDataManagerObserver::~PersonalDataManagerObserver() {
  RemoveObserver();
}

void PersonalDataManagerObserver::RemoveObserver() {
  if (personal_data_manager_) {
    personal_data_manager_->RemoveObserver(this);
  }
}

// The data is ready so display our data.  Notify the dialog controller that
// the data is ready.  Once done we clear the observer.
void PersonalDataManagerObserver::OnPersonalDataLoaded() {
  RemoveObserver();
  [controller_ onPersonalDataLoaded:personal_data_manager_->web_profiles()
                        creditCards:personal_data_manager_->credit_cards()];
}

}  // namespace AutoFillDialogControllerInternal

@interface AutoFillDialogController (PrivateMethods)
- (void)runModalDialog;
- (void)installChildViews;
@end

@implementation AutoFillDialogController

@synthesize auxiliaryEnabled = auxiliaryEnabled_;

+ (void)showAutoFillDialogWithObserver:(AutoFillDialogObserver*)observer
               profile:(Profile*)profile
       importedProfile:(AutoFillProfile*) importedProfile
    importedCreditCard:(CreditCard*) importedCreditCard {
  AutoFillDialogController* controller =
      [AutoFillDialogController controllerWithObserver:observer
                                         profile:profile
                                 importedProfile:importedProfile
                              importedCreditCard:importedCreditCard];

  // Only run modal dialog if it is not already being shown.
  if (![controller isWindowLoaded]) {
    [controller runModalDialog];
  }
}

- (void)awakeFromNib {
  [addressSectionBox_ setShowTopLine:FALSE];

  PersonalDataManager* personal_data_manager =
      profile_->GetPersonalDataManager();
  DCHECK(personal_data_manager);

  if (personal_data_manager->IsDataLoaded()) {
    // |personalDataManager| data is loaded, we can proceed with the contents.
    [self onPersonalDataLoaded:personal_data_manager->web_profiles()
                   creditCards:personal_data_manager->credit_cards()];
  } else {
    // |personalDataManager| data is NOT loaded, so we load it here, installing
    // our observer.
    personalDataManagerObserver_.reset(
        new AutoFillDialogControllerInternal::PersonalDataManagerObserver(
            self, personal_data_manager, profile_));
    personal_data_manager->SetObserver(personalDataManagerObserver_.get());
  }
}

// NSWindow Delegate callback.  When the window closes the controller can
// be released.
- (void)windowWillClose:(NSNotification *)notification {
  // Force views to go away so they properly remove their observations.
  addressFormViewControllers_.reset();
  creditCardFormViewControllers_.reset();
  [self autorelease];
}

// Called when the user clicks the save button.
- (IBAction)save:(id)sender {
  // Call |makeFirstResponder:| to commit pending text field edits.
  [[self window] makeFirstResponder:[self window]];

  // If we have an |observer_| then communicate the changes back.
  if (observer_) {
    profiles_.clear();
    profiles_.resize([addressFormViewControllers_ count]);
    int i = 0;
    for (AutoFillAddressViewController* addressFormViewController in
        addressFormViewControllers_.get()) {
      // Initialize the profile here.  The default initializer does not fully
      // initialize.
      profiles_[i] = AutoFillProfile(ASCIIToUTF16(""), 0);
      [addressFormViewController copyModelToProfile:&profiles_[i]];
      i++;
    }
    creditCards_.clear();
    creditCards_.resize([creditCardFormViewControllers_ count]);
    int j = 0;
    for (AutoFillCreditCardViewController* creditCardFormViewController in
        creditCardFormViewControllers_.get()) {
      // Initialize the credit card here.  The default initializer does not
      // fully initialize.
      creditCards_[j] = CreditCard(ASCIIToUTF16(""), 0);
      [creditCardFormViewController copyModelToCreditCard:&creditCards_[j]];
      j++;
    }
    profile_->GetPrefs()->SetBoolean(prefs::kAutoFillAuxiliaryProfilesEnabled,
                                     auxiliaryEnabled_);
    observer_->OnAutoFillDialogApply(&profiles_, &creditCards_);
  }
  [self closeDialog];
}

// Called when the user clicks the cancel button. All we need to do is stop
// the modal session.
- (IBAction)cancel:(id)sender {
  [self closeDialog];
}

// Adds new address to bottom of list.  A new address controller is created
// and its view is inserted into the view hierarchy.
- (IBAction)addNewAddress:(id)sender {
  // Insert relative to top of section, or below last address.
  NSView* insertionPoint;
  NSUInteger count = [addressFormViewControllers_.get() count];
  if (count == 0) {
    insertionPoint = addressSection_;
  } else {
    insertionPoint = [[addressFormViewControllers_.get()
        objectAtIndex:[addressFormViewControllers_.get() count] - 1] view];
  }

  // Create a new default address, and add it to our array of controllers.
  string16 new_address_name = l10n_util::GetStringUTF16(
      IDS_AUTOFILL_NEW_ADDRESS);
  AutoFillProfile newProfile(new_address_name, 0);
  scoped_nsobject<AutoFillAddressViewController> addressViewController(
      [[AutoFillAddressViewController alloc]
          initWithProfile:newProfile
               disclosure:NSOnState
               controller:self]);
  [self willChangeValueForKey:@"addressLabels"];
  [addressFormViewControllers_.get() addObject:addressViewController];
  [self didChangeValueForKey:@"addressLabels"];

  // Embed the new address into our target view.
  [childView_ addSubview:[addressViewController view]
      positioned:NSWindowBelow relativeTo:insertionPoint];
  [[addressViewController view] setFrameOrigin:NSMakePoint(0, 0)];

  [self notifyAddressChange:self];

  // Recalculate key view loop to account for change in view tree.
  [[self window] recalculateKeyViewLoop];
}

// Adds new credit card to bottom of list.  A new credit card controller is
// created and its view is inserted into the view hierarchy.
- (IBAction)addNewCreditCard:(id)sender {
  // Insert relative to top of section, or below last address.
  NSView* insertionPoint;
  NSUInteger count = [creditCardFormViewControllers_.get() count];
  if (count == 0) {
    insertionPoint = creditCardSection_;
  } else {
    insertionPoint = [[creditCardFormViewControllers_.get()
        objectAtIndex:[creditCardFormViewControllers_.get() count] - 1] view];
  }

  // Create a new default credit card, and add it to our array of controllers.
  string16 new_credit_card_name = l10n_util::GetStringUTF16(
      IDS_AUTOFILL_NEW_CREDITCARD);
  CreditCard newCreditCard(new_credit_card_name, 0);
  scoped_nsobject<AutoFillCreditCardViewController> creditCardViewController(
      [[AutoFillCreditCardViewController alloc]
          initWithCreditCard:newCreditCard
                  disclosure:NSOnState
                  controller:self]);
  [self willChangeValueForKey:@"creditCardLabels"];
  [creditCardFormViewControllers_.get() addObject:creditCardViewController];
  [self didChangeValueForKey:@"creditCardLabels"];

  // Embed the new address into our target view.
  [childView_ addSubview:[creditCardViewController view]
      positioned:NSWindowBelow relativeTo:insertionPoint];
  [[creditCardViewController view] setFrameOrigin:NSMakePoint(0, 0)];

  // Recalculate key view loop to account for change in view tree.
  [[self window] recalculateKeyViewLoop];
}

- (IBAction)deleteAddress:(id)sender {
  NSUInteger i = [addressFormViewControllers_.get() indexOfObject:sender];
  DCHECK(i != NSNotFound);

  // Remove controller's view from superview and remove from list of
  // controllers.  Note on lifetime: removing view from super view decrements
  // refcount of view, removing controller from array decrements refcount of
  // controller which in-turn decrement refcount of view.  Both should dealloc
  // at this point.
  [[sender view] removeFromSuperview];
  [self willChangeValueForKey:@"addressLabels"];
  [addressFormViewControllers_.get() removeObjectAtIndex:i];
  [self didChangeValueForKey:@"addressLabels"];

  [self notifyAddressChange:self];

  // Recalculate key view loop to account for change in view tree.
  [[self window] recalculateKeyViewLoop];
}

- (IBAction)deleteCreditCard:(id)sender {
  NSUInteger i = [creditCardFormViewControllers_.get() indexOfObject:sender];
  DCHECK(i != NSNotFound);

  // Remove controller's view from superview and remove from list of
  // controllers.  Note on lifetime: removing view from super view decrements
  // refcount of view, removing controller from array decrements refcount of
  // controller which in-turn decrement refcount of view.  Both should dealloc
  // at this point.
  [[sender view] removeFromSuperview];
  [self willChangeValueForKey:@"creditCardLabels"];
  [creditCardFormViewControllers_.get() removeObjectAtIndex:i];
  [self didChangeValueForKey:@"creditCardLabels"];

  // Recalculate key view loop to account for change in view tree.
  [[self window] recalculateKeyViewLoop];
}

// Credit card controllers are dependent upon the address labels.  So we notify
// them here that something has changed.
- (IBAction)notifyAddressChange:(id)sender {
  for (AutoFillCreditCardViewController* creditCardFormViewController in
      creditCardFormViewControllers_.get()) {
      [creditCardFormViewController onAddressesChanged:self];
  }
}

- (NSArray*)addressLabels {
  NSUInteger capacity = [addressFormViewControllers_ count];
  NSMutableArray* array = [NSMutableArray arrayWithCapacity:capacity];

  for (AutoFillAddressViewController* addressFormViewController in
      addressFormViewControllers_.get()) {
    [array addObject:[[addressFormViewController addressModel] label]];
  }

  return array;
}

- (NSArray*)creditCardLabels {
  NSUInteger capacity = [creditCardFormViewControllers_ count];
  NSMutableArray* array = [NSMutableArray arrayWithCapacity:capacity];

  for (AutoFillCreditCardViewController* creditCardFormViewController in
      creditCardFormViewControllers_.get()) {
    [array addObject:[[creditCardFormViewController creditCardModel] label]];
  }

  return array;
}

@end

@implementation AutoFillDialogController (ExposedForUnitTests)

+ (AutoFillDialogController*)controllerWithObserver:
        (AutoFillDialogObserver*)observer
               profile:(Profile*)profile
       importedProfile:(AutoFillProfile*)importedProfile
    importedCreditCard:(CreditCard*)importedCreditCard {

  // Deallocation is done upon window close.  See |windowWillClose:|.
  AutoFillDialogController* controller =
      [[self alloc] initWithObserver:observer
                             profile:profile
                     importedProfile:importedProfile
                  importedCreditCard:importedCreditCard];
  return controller;
}


// This is the designated initializer for this class.
// |profiles| are non-retained immutable list of autofill profiles.
// |creditCards| are non-retained immutable list of credit card info.
- (id)initWithObserver:(AutoFillDialogObserver*)observer
               profile:(Profile*)profile
       importedProfile:(AutoFillProfile*)importedProfile
    importedCreditCard:(CreditCard*)importedCreditCard {
  CHECK(profile);
  // Use initWithWindowNibPath: instead of initWithWindowNibName: so we
  // can override it in a unit test.
  NSString* nibpath = [mac_util::MainAppBundle()
                       pathForResource:@"AutoFillDialog"
                       ofType:@"nib"];
  if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
    observer_ = observer;
    profile_ = profile;
    importedProfile_ = importedProfile;
    importedCreditCard_ = importedCreditCard;

    // Use property here to trigger KVO binding.
    [self setAuxiliaryEnabled:profile_->GetPrefs()->GetBoolean(
        prefs::kAutoFillAuxiliaryProfilesEnabled)];

    // Do not use [NSMutableArray array] here; we need predictable destruction
    // which will be prevented by having a reference held by an autorelease
    // pool.

    // Initialize array of sub-controllers.
    addressFormViewControllers_.reset(
        [[NSMutableArray alloc] initWithCapacity:0]);

    // Initialize array of sub-controllers.
    creditCardFormViewControllers_.reset(
        [[NSMutableArray alloc] initWithCapacity:0]);
  }
  return self;
}

// Close the dialog.
- (void)closeDialog {
  [[self window] close];
  [NSApp stopModal];
}

- (NSMutableArray*)addressFormViewControllers {
  return addressFormViewControllers_.get();
}

- (NSMutableArray*)creditCardFormViewControllers {
  return creditCardFormViewControllers_.get();
}

@end

@implementation AutoFillDialogController (PrivateMethods)

// Run application modal.
- (void)runModalDialog {
  // Use stored window geometry if it exists.
  if (g_browser_process && g_browser_process->local_state()) {
    sizeSaver_.reset([[WindowSizeAutosaver alloc]
        initWithWindow:[self window]
           prefService:g_browser_process->local_state()
                  path:prefs::kAutoFillDialogPlacement
                 state:kSaveWindowPos]);
  }

  [NSApp runModalForWindow:[self window]];
}

// Install controller and views for the address form and the credit card form.
// They are installed into the appropriate sibling order so that they can be
// arranged vertically by the VerticalLayoutView class.  We insert the views
// into the |childView_| but we hold onto the controllers and release them in
// our dealloc once the dialog closes.
- (void)installChildViews {
  NSView* insertionPoint;
  insertionPoint = addressSection_;
  for (size_t i = 0; i < profiles_.size(); i++) {
    // Special case for first address, we want to show full contents.
    NSCellStateValue disclosureState = (i == 0) ? NSOnState : NSOffState;
    scoped_nsobject<AutoFillAddressViewController> addressViewController(
        [[AutoFillAddressViewController alloc]
            initWithProfile:profiles_[i]
                 disclosure:disclosureState
                 controller:self]);
    [self willChangeValueForKey:@"addressLabels"];
    [addressFormViewControllers_.get() addObject:addressViewController];
    [self didChangeValueForKey:@"addressLabels"];

    // Embed the child view into our (owned by us) target view.
    [childView_ addSubview:[addressViewController view]
                positioned:NSWindowBelow relativeTo:insertionPoint];
    insertionPoint = [addressViewController view];
    [[addressViewController view] setFrameOrigin:NSMakePoint(0, 0)];
  }

  insertionPoint = creditCardSection_;
  for (size_t i = 0; i < creditCards_.size(); i++) {
    scoped_nsobject<AutoFillCreditCardViewController> creditCardViewController(
        [[AutoFillCreditCardViewController alloc]
            initWithCreditCard:creditCards_[i]
                    disclosure:NSOffState
                    controller:self]);
    [self willChangeValueForKey:@"creditCardLabels"];
    [creditCardFormViewControllers_.get() addObject:creditCardViewController];
    [self didChangeValueForKey:@"creditCardLabels"];

    // Embed the child view into our (owned by us) target view.
    [childView_ addSubview:[creditCardViewController view]
                positioned:NSWindowBelow relativeTo:insertionPoint];
    insertionPoint = [creditCardViewController view];
    [[creditCardViewController view] setFrameOrigin:NSMakePoint(0, 0)];
  }
}

- (void)onPersonalDataLoaded:(const std::vector<AutoFillProfile*>&)profiles
                 creditCards:(const std::vector<CreditCard*>&)creditCards {
  if (importedProfile_) {
      profiles_.push_back(*importedProfile_);
  }

  if (importedCreditCard_) {
      creditCards_.push_back(*importedCreditCard_);
  }

  // If we're not using imported data then use the data fetch from the web db.
  if (!importedProfile_ && !importedCreditCard_) {
    // Make local copy of |profiles|.
    for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin();
         iter != profiles.end(); ++iter)
      profiles_.push_back(**iter);

    // Make local copy of |creditCards|.
    for (std::vector<CreditCard*>::const_iterator iter = creditCards.begin();
         iter != creditCards.end(); ++iter)
      creditCards_.push_back(**iter);
  }

  [self installChildViews];
}

@end