summaryrefslogtreecommitdiffstats
path: root/chrome/browser/cocoa/bookmark_bar_controller.mm
blob: e30a1a2e5fe7d5ba401538f09fd00493060b6ea1 (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
// Copyright (c) 2009 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.

#include "base/sys_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#import "chrome/browser/cocoa/bookmark_bar_bridge.h"
#import "chrome/browser/cocoa/bookmark_bar_controller.h"
#import "chrome/browser/cocoa/bookmark_bar_view.h"
#import "chrome/browser/cocoa/bookmark_button_cell.h"
#import "chrome/browser/cocoa/cocoa_utils.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"

using namespace CocoaUtils;

@interface BookmarkBarController(Private)
- (void)applyContentAreaOffset:(BOOL)apply;
- (void)positionBar;
- (void)showBookmarkBar:(BOOL)enable;
@end

namespace {
const int kBookmarkBarHeight = 30;
// Magic numbers from Cole
const CGFloat kDefaultBookmarkWidth = 150.0;
const CGFloat kBookmarkVerticalPadding = 2.0;
const CGFloat kBookmarkHorizontalPadding = 8.0;
};

@implementation BookmarkBarController

- (id)initWithProfile:(Profile*)profile
          contentView:(NSView*)content
             delegate:(id<BookmarkURLOpener>)delegate {
  if ((self = [super init])) {
    bookmarkModel_ = profile->GetBookmarkModel();
    contentView_ = content;
    delegate_ = delegate;
    // Create and initialize the view's position. Show it if appropriate.
    // TODO(jrg): put it in a nib if necessary.
    NSRect frame = NSMakeRect(0, 0, 0, 30);
    bookmarkBarView_ = [[BookmarkBarView alloc] initWithFrame:frame];
    [self positionBar];
    if (profile->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar))
      [self showBookmarkBar:YES];
    [[[contentView_ window] contentView] addSubview:bookmarkBarView_];
  }
  // Don't pass ourself along until our init is done.
  // Thus, this call is (almost) last.
  bridge_.reset(new BookmarkBarBridge(self, bookmarkModel_));
  return self;
}

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

// Initializes the bookmark bar at the top edge of |contentArea_| and the
// view's visibility to match the pref. This doesn't move the content view at
// all, you need to call |-showBookmarkBar:| to do that.
- (void)positionBar {
  // Hide or show bar based on initial visibility and set the resize flags.
  [bookmarkBarView_ setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];
  [bookmarkBarView_ setHidden:!barIsVisible_];

  // Set the bar's height to zero and position it at the top of the
  // content area, within the window's content view (as opposed to the
  // tab strip, which is a sibling). We'll enlarge it and slide the
  // content area down when we need to show this strip.
  NSRect contentFrame = [contentView_ frame];
  NSRect barFrame = NSMakeRect(0, NSMaxY(contentFrame),
                               contentFrame.size.width, 0);
  [bookmarkBarView_ setFrame:barFrame];
}

// Called when the contentView's frame changes.  Enlarge the view to
// stay with the top of the contentView.
- (void)resizeBookmarkBar {
  NSRect barFrame = [bookmarkBarView_ frame];
  const int maxY = NSMaxY(barFrame);
  barFrame.origin.y = NSMaxY([contentView_ frame]);
  barFrame.size.height = maxY - barFrame.origin.y;
  [bookmarkBarView_ setFrame:barFrame];
}

// Show or hide the bar based on the value of |enable|. Handles animating the
// resize of the content view.
- (void)showBookmarkBar:(BOOL)enable {
  contentViewHasOffset_ = enable;
  [bookmarkBarView_ setHidden:enable ? NO : YES];
  [self applyContentAreaOffset:enable];

  barIsVisible_ = enable;
  if (enable) {
    [self loaded:bookmarkModel_];
  }
}

// Apply a contents box offset to make (or remove) room for the
// bookmark bar.  If apply==YES, always make room (the contentView_ is
// "full size").  If apply==NO we are trying to undo an offset.  If no
// offset there is nothing to undo.
- (void)applyContentAreaOffset:(BOOL)apply {
  if (bookmarkBarView_ == nil) {
    // We're too early, but awakeFromNib will call me again.
    return;
  }
  if (!contentViewHasOffset_ && apply) {
    // There is no offset to unconditionally apply.
    return;
  }

  NSRect frame = [contentView_ frame];
  if (apply)
    frame.size.height -= kBookmarkBarHeight;
  else
    frame.size.height += kBookmarkBarHeight;

  [[contentView_ animator] setFrame:frame];
  [bookmarkBarView_ setNeedsDisplay:YES];
  [contentView_ setNeedsDisplay:YES];
}

- (BOOL)isBookmarkBarVisible {
  return barIsVisible_;
}

// We don't change a preference; we only change visibility.
// Preference changing (global state) is handled in
// BrowserWindowCocoa::ToggleBookmarkBar().
- (void)toggleBookmarkBar {
  [self showBookmarkBar:!barIsVisible_];
}

// Delete all items from the bookmark bar.
- (void)clearBookmarkBar {
  [bookmarkBarView_ setSubviews:[NSArray array]];
}

// TODO(jrg): add an openBookmarkInBackground() for ctrl-click which
// has a different disposition.
- (void)openBookmark:(id)sender {
  BookmarkNode* node = static_cast<BookmarkNode*>([[[sender cell]
                                                     representedObject]
                                                    pointerValue]);
  DCHECK(node);
  [delegate_ openBookmarkURL:node->GetURL() disposition:CURRENT_TAB];
}

// Return an autoreleased NSCell suitable for a bookmark button.
- (NSCell *)cellForBookmarkNode:(BookmarkNode*)node frame:(NSRect)frame {
  NSString* title = base::SysWideToNSString(node->GetTitle());
  NSButtonCell *cell = [[[BookmarkButtonCell alloc] initTextCell:nil]
                         autorelease];
  DCHECK(cell);
  [cell setRepresentedObject:[NSValue valueWithPointer:node]];
  [cell setButtonType:NSMomentaryPushInButton];
  [cell setBezelStyle:NSShadowlessSquareBezelStyle];
  [cell setShowsBorderOnlyWhileMouseInside:YES];

  // The favicon may be NULL if we haven't loaded it yet.  Bookmarks
  // (and their icons) are loaded on the IO thread to speed launch.
  const SkBitmap& favicon = bookmarkModel_->GetFavIcon(node);
  if (!favicon.isNull()) {
    NSImage* image = SkBitmapToNSImage(favicon);
    if (image) {
      [cell setImage:image];
      [cell setImagePosition:NSImageLeft];
    }
  }

  [cell setTitle:title];
  [cell setControlSize:NSSmallControlSize];
  [cell setAlignment:NSLeftTextAlignment];
  [cell setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
  [cell setWraps:NO];
  [cell setLineBreakMode:NSLineBreakByTruncatingMiddle];
  [cell setBordered:NO];
  return cell;
}

// TODO(jrg): accomodation for bookmarks less than minimum width in
// size (like Windows)?
- (NSRect)frameForBookmarkAtIndex:(int)index {
  NSRect bounds = [[self view] bounds];
  // TODO: be smarter about this; the animator delays the right height
  if (bounds.size.height == 0)
    bounds.size.height = kBookmarkBarHeight;

  NSRect frame = NSInsetRect(bounds,
                             kBookmarkHorizontalPadding,
                             kBookmarkVerticalPadding);
  frame.origin.x += (kDefaultBookmarkWidth * index);
  frame.size.width = kDefaultBookmarkWidth;
  return frame;
}

// Add all items from the given model to our bookmark bar.
// TODO(jrg): lots of things!
//  - bookmark folders (e.g. menu from the button)
//  - favicos
//  - button and menu on the right for when bookmarks don't all fit on the
//    screen
//  - ...
//
// TODO(jrg): contextual menu (e.g. Open In New Tab) for each button
// in this function)
//
// TODO(jrg): write a "build bar" so there is a nice spot for things
// like the contextual menu which is invoked when not over a
// bookmark.  On Safari that menu has a "new folder" option.
- (void)addNodesToBar:(BookmarkNode*)node {
  for (int i = 0; i < node->GetChildCount(); i++) {
    BookmarkNode* child = node->GetChild(i);

    NSRect frame = [self frameForBookmarkAtIndex:i];
    NSButton* button = [[[NSButton alloc] initWithFrame:frame]
                         autorelease];
    DCHECK(button);
    // [NSButton setCell:] warns to NOT use setCell: other than in the
    // initializer of a control.  However, we are using a basic
    // NSButton whose initializer does not take an NSCell as an
    // object.  To honor the assumed semantics, we do nothing with
    // NSButton between alloc/init and setCell:.
    [button setCell:[self cellForBookmarkNode:child frame:frame]];
    // [button sizeToFit];

    if (child->is_folder()) {
      // For now just disable the button if it's a folder.
      // TODO(jrg): recurse.
      [button setEnabled:NO];
    } else {
      // Make the button do something
      [button setTarget:self];
      [button setAction:@selector(openBookmark:)];
      // Add a tooltip.
      NSString* title = base::SysWideToNSString(child->GetTitle());
      std::string url_string = child->GetURL().possibly_invalid_spec();
      NSString* tooltip = [NSString stringWithFormat:@"%@\n%s", title,
                                    url_string.c_str()];
      [button setToolTip:tooltip];
    }
    // Finally, add it to the bookmark bar.
    [bookmarkBarView_ addSubview:button];
  }
}

// TODO(jrg): for now this is brute force.
- (void)loaded:(BookmarkModel*)model {
  DCHECK(model == bookmarkModel_);
  // Do nothing if not visible or too early
  if ((barIsVisible_ == NO) || !model->IsLoaded())
    return;
  // Else brute force nuke and build.
  BookmarkNode* node = model->GetBookmarkBarNode();
  [self clearBookmarkBar];
  [self addNodesToBar:node];
}

- (void)beingDeleted:(BookmarkModel*)model {
  [self clearBookmarkBar];
}

// TODO(jrg): for now this is brute force.
- (void)nodeMoved:(BookmarkModel*)model
        oldParent:(BookmarkNode*)oldParent oldIndex:(int)oldIndex
        newParent:(BookmarkNode*)newParent newIndex:(int)newIndex {
  [self loaded:model];
}

// TODO(jrg): for now this is brute force.
- (void)nodeAdded:(BookmarkModel*)model
           parent:(BookmarkNode*)oldParent index:(int)index {
  [self loaded:model];
}

// TODO(jrg): for now this is brute force.
- (void)nodeChanged:(BookmarkModel*)model
               node:(BookmarkNode*)node {
  [self loaded:model];
}

// TODO(jrg): linear searching is bad.
// Need a BookmarkNode-->NSCell mapping.
- (void)nodeFavIconLoaded:(BookmarkModel*)model
                     node:(BookmarkNode*)node {
  NSArray* views = [bookmarkBarView_ subviews];
  for (NSButton* button in views) {
    NSButtonCell* cell = [button cell];
    void* pointer = [[cell representedObject] pointerValue];
    BookmarkNode* cellnode = static_cast<BookmarkNode*>(pointer);
    if (cellnode == node) {
      NSImage* image = SkBitmapToNSImage(bookmarkModel_->GetFavIcon(node));
      if (image) {
        [cell setImage:image];
        [cell setImagePosition:NSImageLeft];
      }
      return;
    }
  }
}

// TODO(jrg): for now this is brute force.
- (void)nodeChildrenReordered:(BookmarkModel*)model
                         node:(BookmarkNode*)node {
  [self loaded:model];
}

- (NSView*)view {
  return bookmarkBarView_;
}

@end