summaryrefslogtreecommitdiffstats
path: root/chrome/browser/cocoa/search_engine_dialog_controller.mm
blob: 4863c0780f7cbbe1b71975e72858f07b1548dedd (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
// 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/cocoa/search_engine_dialog_controller.h"

#include <algorithm>

#include "app/l10n_util_mac.h"
#include "app/resource_bundle.h"
#include "base/mac_util.h"
#include "base/nsimage_cache_mac.h"
#include "base/sys_string_conversions.h"
#include "base/time.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/search_engines/template_url_model_observer.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#import "third_party/GTM/AppKit/GTMUILocalizerAndLayoutTweaker.h"

// Horizontal spacing between search engine choices.
const int kSearchEngineSpacing = 20;

// Vertical spacing between the search engine logo and the button underneath.
const int kLogoButtonSpacing = 10;

// Width of a label used in place of a logo.
const int kLogoLabelWidth = 170;

// Height of a label used in place of a logo.
const int kLogoLabelHeight = 25;

@interface SearchEngineDialogController (Private)
- (void)onTemplateURLModelChanged;
- (void)buildSearchEngineView;
- (NSView*)viewForSearchEngine:(const TemplateURL*)engine
                       atIndex:(size_t)index;
- (IBAction)searchEngineSelected:(id)sender;
@end

class SearchEngineDialogControllerBridge : public TemplateURLModelObserver {
 public:
  SearchEngineDialogControllerBridge(SearchEngineDialogController* controller);

  // TemplateURLModelObserver
  virtual void OnTemplateURLModelChanged();

 private:
  SearchEngineDialogController* controller_;
};

SearchEngineDialogControllerBridge::SearchEngineDialogControllerBridge(
    SearchEngineDialogController* controller) : controller_(controller) {
}

void SearchEngineDialogControllerBridge::OnTemplateURLModelChanged() {
  [controller_ onTemplateURLModelChanged];
  MessageLoop::current()->QuitNow();
}

@implementation SearchEngineDialogController

@synthesize profile = profile_;
@synthesize randomize = randomize_;

- (id)init {
  NSString* nibpath =
      [mac_util::MainAppBundle() pathForResource:@"SearchEngineDialog"
                                          ofType:@"nib"];
  self = [super initWithWindowNibPath:nibpath owner:self];
  if (self != nil) {
    bridge_.reset(new SearchEngineDialogControllerBridge(self));
  }
  return self;
}

- (void)dealloc {
  [super dealloc];
}

- (IBAction)showWindow:(id)sender {
  searchEnginesModel_ = profile_->GetTemplateURLModel();
  searchEnginesModel_->AddObserver(bridge_.get());

  if (searchEnginesModel_->loaded()) {
    [self onTemplateURLModelChanged];
  } else {
    searchEnginesModel_->Load();
    MessageLoop::current()->Run();
  }
}

- (void)onTemplateURLModelChanged {
  searchEnginesModel_->RemoveObserver(bridge_.get());

  // Add the search engines in the search_engines_model_ to the buttons list.
  // The first three will always be from prepopulated data.
  std::vector<const TemplateURL*> templateUrls =
      searchEnginesModel_->GetTemplateURLs();

  // If we have fewer than two search engines, end the search engine dialog
  // immediately, leaving the imported default search engine setting intact.
  if (templateUrls.size() < 2) {
    return;
  }

  NSWindow* win = [self window];

  [win setBackgroundColor:[NSColor whiteColor]];

  NSImage* headerImage = ResourceBundle::GetSharedInstance().
      GetNSImageNamed(IDR_SEARCH_ENGINE_DIALOG_TOP);
  [headerImageView_ setImage:headerImage];

  // Is the user's default search engine included in the first three
  // prepopulated set? If not, we need to expand the dialog to include a fourth
  // engine.
  const TemplateURL* defaultSearchEngine =
      searchEnginesModel_->GetDefaultSearchProvider();

  std::vector<const TemplateURL*>::iterator engineIter =
      templateUrls.begin();
  for (int i = 0; engineIter != templateUrls.end(); ++i, ++engineIter) {
    if (i < 3) {
      choices_.push_back(*engineIter);
    } else {
      if (*engineIter == defaultSearchEngine)
        choices_.push_back(*engineIter);
    }
  }

  // Randomize the order of the logos if the option has been set.
  if (randomize_) {
    int seed = static_cast<int>(base::Time::Now().ToInternalValue());
    srand(seed);
    std::random_shuffle(choices_.begin(), choices_.end());
  }

  [self buildSearchEngineView];

  // Display the dialog.
  NSInteger choice = [NSApp runModalForWindow:win];
  searchEnginesModel_->SetDefaultSearchProvider(choices_.at(choice));
}

- (void)buildSearchEngineView {
  scoped_nsobject<NSMutableArray> searchEngineViews
      ([[NSMutableArray alloc] init]);

  for (size_t i = 0; i < choices_.size(); ++i)
    [searchEngineViews addObject:[self viewForSearchEngine:choices_.at(i)
                                                   atIndex:i]];

  NSSize newOverallSize = NSZeroSize;
  for (NSView* view in searchEngineViews.get()) {
    NSRect engineFrame = [view frame];
    engineFrame.origin = NSMakePoint(newOverallSize.width, 0);
    [searchEngineView_ addSubview:view];
    [view setFrame:engineFrame];
    newOverallSize = NSMakeSize(
        newOverallSize.width + NSWidth(engineFrame) + kSearchEngineSpacing,
        std::max(newOverallSize.height, NSHeight(engineFrame)));
  }
  newOverallSize.width -= kSearchEngineSpacing;

  // Resize the window to fit (and because it's bound on all sides it will
  // resize the search engine view).
  NSSize currentOverallSize = [searchEngineView_ bounds].size;
  NSSize deltaSize = NSMakeSize(
      newOverallSize.width - currentOverallSize.width,
      newOverallSize.height - currentOverallSize.height);
  NSSize windowDeltaSize = [searchEngineView_ convertSize:deltaSize toView:nil];
  NSRect windowFrame = [[self window] frame];
  windowFrame.size.width += windowDeltaSize.width;
  windowFrame.size.height += windowDeltaSize.height;
  [[self window] setFrame:windowFrame display:NO];
}

- (NSView*)viewForSearchEngine:(const TemplateURL*)engine
                       atIndex:(size_t)index {
  bool useImages = false;
#if defined(GOOGLE_CHROME_BUILD)
  useImages = true;
#endif

  // Make the engine identifier.
  NSView* engineIdentifier = nil;  // either the logo or the text label

  int logoId = engine->logo_id();
  if (useImages && logoId > 0) {
    NSImage* logoImage =
        ResourceBundle::GetSharedInstance().GetNSImageNamed(logoId);
    NSRect logoBounds = NSZeroRect;
    logoBounds.size = [logoImage size];
    NSImageView* logoView =
        [[[NSImageView alloc] initWithFrame:logoBounds] autorelease];
    [logoView setImage:logoImage];
    [logoView setEditable:NO];

    // Tooltip text provides accessibility.
    [logoView setToolTip:base::SysWideToNSString(engine->short_name())];
    engineIdentifier = logoView;
  } else {
    // No logo -- we must show a text label.
    NSRect labelBounds = NSMakeRect(0, 0, kLogoLabelWidth, kLogoLabelHeight);
    NSTextField* labelField =
        [[[NSTextField alloc] initWithFrame:labelBounds] autorelease];
    [labelField setBezeled:NO];
    [labelField setEditable:NO];
    [labelField setSelectable:NO];

    scoped_nsobject<NSMutableParagraphStyle> paragraphStyle(
        [[NSMutableParagraphStyle alloc] init]);
    [paragraphStyle setAlignment:NSCenterTextAlignment];
    NSDictionary* attrs = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSFont boldSystemFontOfSize:13], NSFontAttributeName,
        paragraphStyle.get(), NSParagraphStyleAttributeName,
        nil];

    NSString* value = base::SysWideToNSString(engine->short_name());
    scoped_nsobject<NSAttributedString> attrValue(
        [[NSAttributedString alloc] initWithString:value
                                        attributes:attrs]);

    [labelField setAttributedStringValue:attrValue.get()];

    engineIdentifier = labelField;
  }

  // Make the "Choose" button.
  scoped_nsobject<NSButton> chooseButton(
      [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 100, 34)]);
  [chooseButton setBezelStyle:NSRoundedBezelStyle];
  [[chooseButton cell] setFont:[NSFont systemFontOfSize:
      [NSFont systemFontSizeForControlSize:NSRegularControlSize]]];
  [chooseButton setTitle:l10n_util::GetNSStringWithFixup(IDS_FR_SEARCH_CHOOSE)];
  [GTMUILocalizerAndLayoutTweaker sizeToFitView:chooseButton.get()];
  [chooseButton setTag:index];
  [chooseButton setTarget:self];
  [chooseButton setAction:@selector(searchEngineSelected:)];

  // Put 'em together.
  NSRect engineIdentifierFrame = [engineIdentifier frame];
  NSRect chooseButtonFrame = [chooseButton frame];

  NSRect containingViewFrame = NSZeroRect;
  containingViewFrame.size.width += engineIdentifierFrame.size.width;
  containingViewFrame.size.height += engineIdentifierFrame.size.height;
  containingViewFrame.size.height += kLogoButtonSpacing;
  containingViewFrame.size.height += chooseButtonFrame.size.height;

  NSView* containingView =
      [[[NSView alloc] initWithFrame:containingViewFrame] autorelease];

  [containingView addSubview:engineIdentifier];
  engineIdentifierFrame.origin.y =
      chooseButtonFrame.size.height + kLogoButtonSpacing;
  [engineIdentifier setFrame:engineIdentifierFrame];

  [containingView addSubview:chooseButton];
  chooseButtonFrame.origin.x =
      int((containingViewFrame.size.width - chooseButtonFrame.size.width) / 2);
  [chooseButton setFrame:chooseButtonFrame];

  return containingView;
}

- (NSFont*)mainLabelFont {
  return [NSFont boldSystemFontOfSize:13];
}

- (IBAction)searchEngineSelected:(id)sender {
  [[self window] close];
  [NSApp stopModalWithCode:[sender tag]];
}

@end