summaryrefslogtreecommitdiffstats
path: root/chrome/browser/cocoa/extensions/browser_actions_controller.mm
blob: 491c516686f9e55e920c365e8e5c4518aed11b53 (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
// 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 "browser_actions_controller.h"

#include <string>

#include "base/sys_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#import "chrome/browser/cocoa/extensions/browser_action_button.h"
#import "chrome/browser/cocoa/extensions/browser_actions_container_view.h"
#import "chrome/browser/cocoa/extensions/extension_popup_controller.h"
#include "chrome/browser/extensions/extension_browser_event_router.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/pref_names.h"

extern const CGFloat kBrowserActionButtonPadding = 3;

extern const NSString* kBrowserActionVisibilityChangedNotification =
    @"BrowserActionVisibilityChangedNotification";

namespace {
const CGFloat kAnimationDuration = 0.2;
const CGFloat kContainerPadding = 2.0;
const CGFloat kGrippyXOffset = 8.0;
const CGFloat kButtonOpacityLeadPadding = 5.0;
}  // namespace

@interface BrowserActionsController(Private)
- (void)createButtons;
- (void)createActionButtonForExtension:(Extension*)extension
                             withIndex:(NSUInteger)index;
- (void)removeActionButtonForExtension:(Extension*)extension;
- (CGFloat)containerWidthWithButtonCount:(NSUInteger)buttonCount;
- (NSUInteger)containerButtonCapacity;
- (void)repositionActionButtons;
- (void)updateButtonOpacityAndDragAbilities;
- (void)containerFrameChanged;
- (void)containerDragStart;
- (void)containerDragging;
- (void)containerDragFinished;
- (int)currentTabId;
- (bool)shouldDisplayBrowserAction:(Extension*)extension;
- (void)showChevronIfNecessaryWithAnimation:(BOOL)animation;
@end

// A helper class to proxy extension notifications to the view controller's
// appropriate methods.
class ExtensionsServiceObserverBridge : public NotificationObserver,
                                        public ExtensionToolbarModel::Observer {
 public:
  ExtensionsServiceObserverBridge(BrowserActionsController* owner,
                                  Profile* profile) : owner_(owner) {
    registrar_.Add(this, NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE,
                   Source<Profile>(profile));
  }

  // Overridden from NotificationObserver.
  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE: {
        ExtensionPopupController* popup = [ExtensionPopupController popup];
        if (popup && ![popup isClosing])
          [popup close];

        break;
      }
      default:
        NOTREACHED() << L"Unexpected notification";
    }
  }

  // ExtensionToolbarModel::Observer implementation.
  void BrowserActionAdded(Extension* extension, int index) {
    [owner_ createActionButtonForExtension:extension withIndex:index];
    [owner_ resizeContainerWithAnimation:NO];
  }

  void BrowserActionRemoved(Extension* extension) {
    [owner_ removeActionButtonForExtension:extension];
    [owner_ resizeContainerWithAnimation:NO];
  }

 private:
  // The object we need to inform when we get a notification. Weak. Owns us.
  BrowserActionsController* owner_;

  // Used for registering to receive notifications and automatic clean up.
  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionsServiceObserverBridge);
};

@implementation BrowserActionsController

@synthesize containerView = containerView_;

- (id)initWithBrowser:(Browser*)browser
        containerView:(BrowserActionsContainerView*)container {
  DCHECK(browser && container);

  if ((self = [super init])) {
    browser_ = browser;
    profile_ = browser->profile();

    if (!profile_->GetPrefs()->FindPreference(
        prefs::kBrowserActionContainerWidth))
      [BrowserActionsController registerUserPrefs:profile_->GetPrefs()];

    observer_.reset(new ExtensionsServiceObserverBridge(self, profile_));
    ExtensionsService* extensionsService = profile_->GetExtensionsService();
    // |extensionsService| can be NULL in Incognito.
    if (extensionsService) {
      toolbarModel_ = extensionsService->toolbar_model();
      toolbarModel_->AddObserver(observer_.get());
    }

    containerView_ = container;
    [containerView_ setHidden:YES];
    [containerView_ setCanDragLeft:YES];
    [containerView_ setCanDragRight:YES];
    [containerView_ setPostsFrameChangedNotifications:YES];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(containerFrameChanged)
               name:NSViewFrameDidChangeNotification
             object:containerView_];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(containerDragStart)
               name:kBrowserActionGrippyDragStartedNotification
             object:containerView_];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(containerDragging)
               name:kBrowserActionGrippyDraggingNotification
             object:containerView_];
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(containerDragFinished)
               name:kBrowserActionGrippyDragFinishedNotification
             object:containerView_];

    hiddenButtons_.reset([[NSMutableArray alloc] init]);
    buttons_.reset([[NSMutableDictionary alloc] init]);
    [self createButtons];
    [self showChevronIfNecessaryWithAnimation:NO];
  }

  return self;
}

- (void)dealloc {
  if (toolbarModel_)
    toolbarModel_->RemoveObserver(observer_.get());

  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}

- (void)update {
  for (BrowserActionButton* button in [buttons_ allValues]) {
    [button setTabId:[self currentTabId]];
    [button updateState];
  }
}

- (void)createButtons {
  // No extensions in incognito mode.
  if (!toolbarModel_)
    return;

  NSUInteger i = 0;
  for (ExtensionList::iterator iter = toolbarModel_->begin();
       iter != toolbarModel_->end(); ++iter) {
    if (![self shouldDisplayBrowserAction:*iter])
      continue;

    [self createActionButtonForExtension:*iter withIndex:i++];
  }

  CGFloat width = [self savedWidth];
  // The width will never be 0 (due to the container's minimum size restriction)
  // except when no width has been saved. In this case, set the width to be as
  // if all buttons are shown.
  if (width == 0)
    width = [self containerWidthWithButtonCount:[self buttonCount]];

  [containerView_ resizeToWidth:width animate:NO];
}

- (void)createActionButtonForExtension:(Extension*)extension
                             withIndex:(NSUInteger)index {
  if (!extension->browser_action())
    return;

  if (![self shouldDisplayBrowserAction:extension])
    return;

  if (profile_->IsOffTheRecord())
    index = toolbarModel_->OriginalIndexToIncognito(index);

  // Show the container if it's the first button. Otherwise it will be shown
  // already.
  if ([buttons_ count] == 0)
    [containerView_ setHidden:NO];

  BrowserActionButton* newButton = [[[BrowserActionButton alloc]
      initWithExtension:extension
                profile:profile_
                  tabId:[self currentTabId]] autorelease];
  [newButton setTarget:self];
  [newButton setAction:@selector(browserActionClicked:)];
  NSString* buttonKey = base::SysUTF8ToNSString(extension->id());
  if (!buttonKey)
    return;

  [buttons_ setObject:newButton forKey:buttonKey];
  if (index < [self containerButtonCapacity]) {
    [containerView_ addSubview:newButton];
  } else {
    [hiddenButtons_ addObject:newButton];
    [newButton setAlphaValue:0.0];
  }

  [self repositionActionButtons];
  [containerView_ setNeedsDisplay:YES];
}

- (void)removeActionButtonForExtension:(Extension*)extension {
  if (!extension->browser_action())
    return;

  NSString* buttonKey = base::SysUTF8ToNSString(extension->id());
  if (!buttonKey)
    return;

  BrowserActionButton* button = [buttons_ objectForKey:buttonKey];
  // This could be the case in incognito, where only a subset of extensions are
  // shown.
  if (!button)
    return;

  [button removeFromSuperview];
  // It may or may not be hidden, but it won't matter to NSMutableArray either
  // way.
  [hiddenButtons_ removeObject:button];

  [buttons_ removeObjectForKey:buttonKey];
  if ([buttons_ count] == 0) {
    // No more buttons? Hide the container.
    [containerView_ setHidden:YES];
  } else {
    [self repositionActionButtons];
  }
  [containerView_ setNeedsDisplay:YES];
}

- (void)repositionActionButtons {
  NSUInteger i = 0;
  for (ExtensionList::iterator iter = toolbarModel_->begin();
       iter != toolbarModel_->end(); ++iter) {
    if (![self shouldDisplayBrowserAction:*iter])
      continue;

    CGFloat xOffset = kGrippyXOffset +
        (i * (kBrowserActionWidth + kBrowserActionButtonPadding));
    NSString* extensionId = base::SysUTF8ToNSString((*iter)->id());
    DCHECK(extensionId);
    if (!extensionId)
      continue;
    BrowserActionButton* button = [buttons_ objectForKey:extensionId];
    NSRect buttonFrame = [button frame];
    buttonFrame.origin.x = xOffset;
    [button setFrame:buttonFrame];
    ++i;
  }
}

- (CGFloat)containerWidthWithButtonCount:(NSUInteger)buttonCount {
  CGFloat width = 0.0;
  if (buttonCount > 0) {
    width = kGrippyXOffset + kContainerPadding +
        (buttonCount * (kBrowserActionWidth + kBrowserActionButtonPadding));
    // Make room for the chevron if necessary.
    if ([self buttonCount] != [self visibleButtonCount])
      width += kChevronWidth + kBrowserActionButtonPadding;
  }
  return width;
}

- (NSUInteger)containerButtonCapacity {
  CGFloat containerWidth = [self savedWidth];
  if (containerWidth == 0)
    containerWidth = [self containerWidthWithButtonCount:[self buttonCount]];

  return (containerWidth - kGrippyXOffset + kContainerPadding) /
      (kBrowserActionWidth + kBrowserActionButtonPadding);
}

// Resizes the container given the number of visible buttons in the container,
// taking into account the size of the grippy. Also updates the persistent
// width preference.
- (void)resizeContainerWithAnimation:(BOOL)animate {
  CGFloat width =
      [self containerWidthWithButtonCount:[self visibleButtonCount]];
  [containerView_ resizeToWidth:width animate:animate];

  [self showChevronIfNecessaryWithAnimation:YES];

  if (!profile_->IsOffTheRecord())
    profile_->GetPrefs()->SetReal(prefs::kBrowserActionContainerWidth,
        NSWidth([containerView_ frame]));

  [[NSNotificationCenter defaultCenter]
      postNotificationName:kBrowserActionVisibilityChangedNotification
                    object:self];
}

- (void)updateButtonOpacityAndDragAbilities {
  for (BrowserActionButton* button in [buttons_ allValues]) {
    NSRect buttonFrame = [button frame];
    buttonFrame.origin.x += kButtonOpacityLeadPadding;
    if (NSContainsRect([containerView_ bounds], buttonFrame)) {
      if ([button alphaValue] != 1.0)
        [button setAlphaValue:1.0];

      continue;
    }
    CGFloat intersectionWidth =
        NSWidth(NSIntersectionRect([containerView_ bounds], buttonFrame));
    CGFloat alpha = std::max(0.0f,
        (intersectionWidth - kButtonOpacityLeadPadding) / NSWidth(buttonFrame));
    [button setAlphaValue:alpha];
    [button setNeedsDisplay:YES];
  }

  // Updates the drag direction constraint variables based on relevant metrics.
  [containerView_ setCanDragLeft:
      ([self visibleButtonCount] != [self buttonCount])];
  [[containerView_ window] invalidateCursorRectsForView:containerView_];
}

- (void)containerFrameChanged {
  [self updateButtonOpacityAndDragAbilities];
}

- (void)containerDragStart {
  while([hiddenButtons_ count] > 0) {
    [containerView_ addSubview:[hiddenButtons_ objectAtIndex:0]];
    [hiddenButtons_ removeObjectAtIndex:0];
  }
}

- (void)containerDragging {
  [[NSNotificationCenter defaultCenter]
      postNotificationName:kBrowserActionGrippyDraggingNotification
                    object:self];
}

// Handles when a user initiated drag to resize the container has finished.
- (void)containerDragFinished {
  for (BrowserActionButton* button in [buttons_ allValues]) {
    NSRect buttonFrame = [button frame];
    if (NSContainsRect([containerView_ bounds], buttonFrame))
      continue;

    CGFloat intersectionWidth =
        NSWidth(NSIntersectionRect([containerView_ bounds], buttonFrame));
    // Pad the threshold by 5 pixels in order to have the buttons hide more
    // easily.
    if (([containerView_ grippyPinned] && intersectionWidth > 0) ||
        (intersectionWidth <= (NSWidth(buttonFrame) / 2) + 5.0)) {
      [button setAlphaValue:0.0];
      [button removeFromSuperview];
      [hiddenButtons_ addObject:button];
    }
  }

  [self resizeContainerWithAnimation:NO];
}

- (NSUInteger)buttonCount {
  return [buttons_ count];
}

- (NSUInteger)visibleButtonCount {
  return [buttons_ count] - [hiddenButtons_ count];
}

- (void)browserActionClicked:(BrowserActionButton*)sender {
  int tabId = [self currentTabId];
  if (tabId < 0) {
    NOTREACHED() << "No current tab.";
    return;
  }

  ExtensionAction* action = [sender extension]->browser_action();
  if (action->HasPopup(tabId)) {
    NSString* extensionId = base::SysUTF8ToNSString([sender extension]->id());
    // If the extension ID is not valid UTF-8, then the NSString will be nil
    // and an exception will be thrown when calling objectForKey below, hosing
    // the browser. Check it.
    DCHECK(extensionId);
    if (!extensionId)
      return;
    BrowserActionButton* actionButton = [buttons_ objectForKey:extensionId];
    NSPoint arrowPoint = [actionButton frame].origin;
    // Adjust the anchor point to be at the center of the browser action button.
    arrowPoint.x += kBrowserActionWidth / 2;
    arrowPoint = [[actionButton superview] convertPoint:arrowPoint toView:nil];
    arrowPoint = [[actionButton window] convertBaseToScreen:arrowPoint];
    [ExtensionPopupController showURL:action->GetPopupUrl(tabId)
                            inBrowser:browser_
                           anchoredAt:arrowPoint
                        arrowLocation:kTopRight];
  } else {
    ExtensionBrowserEventRouter::GetInstance()->BrowserActionExecuted(
       profile_, action->extension_id(), browser_);
  }
}

- (int)currentTabId {
  TabContents* selected_tab = browser_->GetSelectedTabContents();
  if (!selected_tab)
    return -1;

  return selected_tab->controller().session_id().id();
}

- (NSView*)browserActionViewForExtension:(Extension*)extension {
  for (BrowserActionButton* button in [buttons_ allValues]) {
    if ([button extension] == extension)
      return button;
  }
  NOTREACHED();
  return nil;
}

- (NSButton*)buttonWithIndex:(NSUInteger)index {
  NSUInteger i = 0;
  for (ExtensionList::iterator iter = toolbarModel_->begin();
       iter != toolbarModel_->end(); ++iter) {
    if (i == index)
      return [buttons_ objectForKey:base::SysUTF8ToNSString((*iter)->id())];

    ++i;
  }
  return nil;
}

- (bool)shouldDisplayBrowserAction:(Extension*)extension {
  // Only display incognito-enabled extensions while in incognito mode.
  return (!profile_->IsOffTheRecord() ||
          profile_->GetExtensionsService()->IsIncognitoEnabled(extension));
}

- (CGFloat)savedWidth {
  // Don't use the standard saved width for incognito until a separate pref is
  // added.
  if (profile_->IsOffTheRecord())
    return 0.0;

  return profile_->GetPrefs()->GetReal(prefs::kBrowserActionContainerWidth);
}

- (void)showChevronIfNecessaryWithAnimation:(BOOL)animation {
  BOOL hideChevron = [self buttonCount] == [self visibleButtonCount];
  [containerView_ setChevronHidden:hideChevron animate:animation];
}

+ (void)registerUserPrefs:(PrefService*)prefs {
  prefs->RegisterRealPref(prefs::kBrowserActionContainerWidth, 0);
}

@end