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.
7 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_editor_base_controller.h"
9 #include "base/auto_reset.h"
10 #include "base/logging.h"
11 #include "base/mac/bundle_locations.h"
12 #include "base/mac/mac_util.h"
13 #include "base/strings/sys_string_conversions.h"
14 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
15 #include "chrome/browser/profiles/profile.h"
16 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_all_tabs_controller.h"
17 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.h"
18 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_name_folder_controller.h"
19 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_tree_browser_cell.h"
20 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
21 #include "components/bookmarks/browser/bookmark_model.h"
22 #include "grit/generated_resources.h"
23 #include "ui/base/l10n/l10n_util.h"
24 #include "ui/base/l10n/l10n_util_mac.h"
26 @interface BookmarkEditorBaseController ()
28 // Return the folder tree object for the given path.
29 - (BookmarkFolderInfo*)folderForIndexPath:(NSIndexPath*)path;
31 // (Re)build the folder tree from the BookmarkModel's current state.
32 - (void)buildFolderTree;
34 // Notifies the controller that the bookmark model has changed.
35 // |selection| specifies if the current selection should be
36 // maintained (usually YES).
37 - (void)modelChangedPreserveSelection:(BOOL)preserve;
39 // Notifies the controller that a node has been removed.
40 - (void)nodeRemoved:(const BookmarkNode*)node
41 fromParent:(const BookmarkNode*)parent;
43 // Given a folder node, collect an array containing BookmarkFolderInfos
44 // describing its subchildren which are also folders.
45 - (NSMutableArray*)addChildFoldersFromNode:(const BookmarkNode*)node;
47 // Scan the folder tree stemming from the given tree folder and create
48 // any newly added folders. Pass down info for the folder which was
49 // selected before we began creating folders.
50 - (void)createNewFoldersForFolder:(BookmarkFolderInfo*)treeFolder
51 selectedFolderInfo:(BookmarkFolderInfo*)selectedFolderInfo;
53 // Scan the folder tree looking for the given bookmark node and return
54 // the selection path thereto.
55 - (NSIndexPath*)selectionPathForNode:(const BookmarkNode*)node;
57 // Implementation of getExpandedNodes. See description in header for details.
58 - (void)getExpandedNodes:(BookmarkExpandedStateTracker::Nodes*)nodes
59 folder:(BookmarkFolderInfo*)info
60 path:(std::vector<NSUInteger>*)path
64 // static; implemented for each platform. Update this function for new
65 // classes derived from BookmarkEditorBaseController.
66 void BookmarkEditor::Show(gfx::NativeWindow parent_window,
68 const EditDetails& details,
69 Configuration configuration) {
70 if (details.type == EditDetails::EXISTING_NODE &&
71 details.existing_node->is_folder()) {
72 BookmarkNameFolderController* controller =
73 [[BookmarkNameFolderController alloc]
74 initWithParentWindow:parent_window
76 node:details.existing_node];
77 [controller runAsModalSheet];
81 if (details.type == EditDetails::NEW_FOLDER && details.urls.empty()) {
82 BookmarkNameFolderController* controller =
83 [[BookmarkNameFolderController alloc]
84 initWithParentWindow:parent_window
86 parent:details.parent_node
87 newIndex:details.index];
88 [controller runAsModalSheet];
92 BookmarkEditorBaseController* controller = nil;
93 if (details.type == EditDetails::NEW_FOLDER) {
94 controller = [[BookmarkAllTabsController alloc]
95 initWithParentWindow:parent_window
97 parent:details.parent_node
100 configuration:configuration];
102 controller = [[BookmarkEditorController alloc]
103 initWithParentWindow:parent_window
105 parent:details.parent_node
106 node:details.existing_node
109 configuration:configuration];
111 [controller runAsModalSheet];
114 // Adapter to tell BookmarkEditorBaseController when bookmarks change.
115 class BookmarkEditorBaseControllerBridge : public BookmarkModelObserver {
117 BookmarkEditorBaseControllerBridge(BookmarkEditorBaseController* controller)
118 : controller_(controller),
122 virtual void BookmarkModelLoaded(BookmarkModel* model,
123 bool ids_reassigned) OVERRIDE {
124 [controller_ modelChangedPreserveSelection:YES];
127 virtual void BookmarkNodeMoved(BookmarkModel* model,
128 const BookmarkNode* old_parent,
130 const BookmarkNode* new_parent,
131 int new_index) OVERRIDE {
132 if (!importing_ && new_parent->GetChild(new_index)->is_folder())
133 [controller_ modelChangedPreserveSelection:YES];
136 virtual void BookmarkNodeAdded(BookmarkModel* model,
137 const BookmarkNode* parent,
138 int index) OVERRIDE {
139 if (!importing_ && parent->GetChild(index)->is_folder())
140 [controller_ modelChangedPreserveSelection:YES];
143 virtual void BookmarkNodeRemoved(
144 BookmarkModel* model,
145 const BookmarkNode* parent,
147 const BookmarkNode* node,
148 const std::set<GURL>& removed_urls) OVERRIDE {
149 [controller_ nodeRemoved:node fromParent:parent];
150 if (node->is_folder())
151 [controller_ modelChangedPreserveSelection:NO];
154 virtual void BookmarkAllNodesRemoved(
155 BookmarkModel* model,
156 const std::set<GURL>& removed_urls) OVERRIDE {
157 [controller_ modelChangedPreserveSelection:NO];
160 virtual void BookmarkNodeChanged(BookmarkModel* model,
161 const BookmarkNode* node) OVERRIDE {
162 if (!importing_ && node->is_folder())
163 [controller_ modelChangedPreserveSelection:YES];
166 virtual void BookmarkNodeChildrenReordered(
167 BookmarkModel* model,
168 const BookmarkNode* node) OVERRIDE {
170 [controller_ modelChangedPreserveSelection:YES];
173 virtual void BookmarkNodeFaviconChanged(BookmarkModel* model,
174 const BookmarkNode* node) OVERRIDE {
175 // I care nothing for these 'favicons': I only show folders.
178 virtual void ExtensiveBookmarkChangesBeginning(
179 BookmarkModel* model) OVERRIDE {
183 // Invoked after a batch import finishes. This tells observers to update
184 // themselves if they were waiting for the update to finish.
185 virtual void ExtensiveBookmarkChangesEnded(BookmarkModel* model) OVERRIDE {
187 [controller_ modelChangedPreserveSelection:YES];
191 BookmarkEditorBaseController* controller_; // weak
198 @implementation BookmarkEditorBaseController
200 @synthesize initialName = initialName_;
201 @synthesize displayName = displayName_;
203 - (id)initWithParentWindow:(NSWindow*)parentWindow
204 nibName:(NSString*)nibName
205 profile:(Profile*)profile
206 parent:(const BookmarkNode*)parent
208 title:(const base::string16&)title
209 configuration:(BookmarkEditor::Configuration)configuration {
210 NSString* nibpath = [base::mac::FrameworkBundle()
211 pathForResource:nibName
213 if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
214 parentWindow_ = parentWindow;
216 parentNode_ = parent;
219 configuration_ = configuration;
220 initialName_ = [@"" retain];
221 observer_.reset(new BookmarkEditorBaseControllerBridge(self));
222 [self bookmarkModel]->AddObserver(observer_.get());
228 [self bookmarkModel]->RemoveObserver(observer_.get());
229 [initialName_ release];
230 [displayName_ release];
234 - (void)awakeFromNib {
235 [self setDisplayName:[self initialName]];
237 if (configuration_ != BookmarkEditor::SHOW_TREE) {
238 // Remember the tree view's height; we will shrink our frame by that much.
239 NSRect frame = [[self window] frame];
240 CGFloat browserHeight = [folderTreeView_ frame].size.height;
241 frame.size.height -= browserHeight;
242 frame.origin.y += browserHeight;
243 // Remove the folder tree and "new folder" button.
244 [folderTreeView_ removeFromSuperview];
245 [newFolderButton_ removeFromSuperview];
246 // Finally, commit the size change.
247 [[self window] setFrame:frame display:YES];
250 // Build up a tree of the current folder configuration.
251 [self buildFolderTree];
254 - (void)windowDidLoad {
255 if (configuration_ == BookmarkEditor::SHOW_TREE) {
256 [self selectNodeInBrowser:parentNode_];
261 // Implementing this informal protocol allows us to open the sheet
262 // somewhere other than at the top of the window. NOTE: this means
263 // that I, the controller, am also the window's delegate.
264 - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet
265 usingRect:(NSRect)rect {
266 // adjust rect.origin.y to be the bottom of the toolbar
271 // TODO(jrg): consider NSModalSession.
272 - (void)runAsModalSheet {
273 // Lock down floating bar when in full-screen mode. Don't animate
274 // otherwise the pane will be misplaced.
275 [[BrowserWindowController browserWindowControllerForWindow:parentWindow_]
276 lockBarVisibilityForOwner:self withAnimation:NO delay:NO];
277 [NSApp beginSheet:[self window]
278 modalForWindow:parentWindow_
280 didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
284 // This constant has to match the name of the method after it.
285 NSString* const kOkEnabledName = @"okEnabled";
290 - (IBAction)ok:(id)sender {
291 NSWindow* window = [self window];
292 [window makeFirstResponder:window];
293 // At least one of these two functions should be provided by derived classes.
294 BOOL hasWillCommit = [self respondsToSelector:@selector(willCommit)];
295 BOOL hasDidCommit = [self respondsToSelector:@selector(didCommit)];
296 DCHECK(hasWillCommit || hasDidCommit);
297 BOOL shouldContinue = YES;
299 NSNumber* hasWillContinue = [self performSelector:@selector(willCommit)];
300 if (hasWillContinue && [hasWillContinue isKindOfClass:[NSNumber class]])
301 shouldContinue = [hasWillContinue boolValue];
304 [self createNewFolders];
306 NSNumber* hasDidContinue = [self performSelector:@selector(didCommit)];
307 if (hasDidContinue && [hasDidContinue isKindOfClass:[NSNumber class]])
308 shouldContinue = [hasDidContinue boolValue];
311 [NSApp endSheet:window];
314 - (IBAction)cancel:(id)sender {
315 [NSApp endSheet:[self window]];
318 - (void)didEndSheet:(NSWindow*)sheet
319 returnCode:(int)returnCode
320 contextInfo:(void*)contextInfo {
322 [[BrowserWindowController browserWindowControllerForWindow:parentWindow_]
323 releaseBarVisibilityForOwner:self withAnimation:YES delay:NO];
326 - (void)windowWillClose:(NSNotification*)notification {
330 #pragma mark Folder Tree Management
332 - (BookmarkModel*)bookmarkModel {
333 return BookmarkModelFactory::GetForProfile(profile_);
336 - (Profile*)profile {
340 - (const BookmarkNode*)parentNode {
348 - (const base::string16&)title{
352 - (BookmarkFolderInfo*)folderForIndexPath:(NSIndexPath*)indexPath {
353 NSUInteger pathCount = [indexPath length];
354 BookmarkFolderInfo* item = nil;
355 NSArray* treeNode = [self folderTreeArray];
356 for (NSUInteger i = 0; i < pathCount; ++i) {
357 item = [treeNode objectAtIndex:[indexPath indexAtPosition:i]];
358 treeNode = [item children];
363 - (NSIndexPath*)selectedIndexPath {
364 NSIndexPath* selectedIndexPath = nil;
365 NSArray* selections = [self tableSelectionPaths];
366 if ([selections count]) {
367 DCHECK([selections count] == 1); // Should be exactly one selection.
368 selectedIndexPath = [selections objectAtIndex:0];
370 return selectedIndexPath;
373 - (BookmarkFolderInfo*)selectedFolder {
374 BookmarkFolderInfo* item = nil;
375 NSIndexPath* selectedIndexPath = [self selectedIndexPath];
376 if (selectedIndexPath) {
377 item = [self folderForIndexPath:selectedIndexPath];
382 - (const BookmarkNode*)selectedNode {
383 const BookmarkNode* selectedNode = NULL;
384 // Determine a new parent node only if the browser is showing.
385 if (configuration_ == BookmarkEditor::SHOW_TREE) {
386 BookmarkFolderInfo* folderInfo = [self selectedFolder];
388 selectedNode = [folderInfo folderNode];
390 // If the tree is not showing then we use the original parent.
391 selectedNode = parentNode_;
396 - (void)expandNodes:(const BookmarkExpandedStateTracker::Nodes&)nodes {
397 id treeControllerRoot = [folderTreeController_ arrangedObjects];
398 for (BookmarkExpandedStateTracker::Nodes::const_iterator i = nodes.begin();
399 i != nodes.end(); ++i) {
400 NSIndexPath* path = [self selectionPathForNode:*i];
401 id folderNode = [treeControllerRoot descendantNodeAtIndexPath:path];
402 [folderTreeView_ expandItem:folderNode];
406 - (BookmarkExpandedStateTracker::Nodes)getExpandedNodes {
407 BookmarkExpandedStateTracker::Nodes nodes;
408 std::vector<NSUInteger> path;
409 NSArray* folderNodes = [self folderTreeArray];
411 for (BookmarkFolderInfo* folder in folderNodes) {
413 [self getExpandedNodes:&nodes
416 root:[folderTreeController_ arrangedObjects]];
423 - (void)getExpandedNodes:(BookmarkExpandedStateTracker::Nodes*)nodes
424 folder:(BookmarkFolderInfo*)folder
425 path:(std::vector<NSUInteger>*)path
427 NSIndexPath* indexPath = [NSIndexPath indexPathWithIndexes:&(path->front())
428 length:path->size()];
429 id node = [root descendantNodeAtIndexPath:indexPath];
430 if (![folderTreeView_ isItemExpanded:node])
432 nodes->insert([folder folderNode]);
433 NSArray* children = [folder children];
435 for (BookmarkFolderInfo* childFolder in children) {
437 [self getExpandedNodes:nodes folder:childFolder path:path root:root];
443 - (NSArray*)folderTreeArray {
444 return folderTreeArray_.get();
447 - (NSArray*)tableSelectionPaths {
448 return tableSelectionPaths_.get();
451 - (void)setTableSelectionPath:(NSIndexPath*)tableSelectionPath {
452 [self setTableSelectionPaths:[NSArray arrayWithObject:tableSelectionPath]];
455 - (void)setTableSelectionPaths:(NSArray*)tableSelectionPaths {
456 tableSelectionPaths_.reset([tableSelectionPaths retain]);
459 - (void)selectNodeInBrowser:(const BookmarkNode*)node {
460 DCHECK(configuration_ == BookmarkEditor::SHOW_TREE);
461 NSIndexPath* selectionPath = [self selectionPathForNode:node];
462 [self willChangeValueForKey:kOkEnabledName];
463 [self setTableSelectionPath:selectionPath];
464 [self didChangeValueForKey:kOkEnabledName];
467 - (NSIndexPath*)selectionPathForNode:(const BookmarkNode*)desiredNode {
468 // Back up the parent chaing for desiredNode, building up a stack
469 // of ancestor nodes. Then crawl down the folderTreeArray looking
470 // for each ancestor in order while building up the selectionPath.
471 std::stack<const BookmarkNode*> nodeStack;
472 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
473 const BookmarkNode* rootNode = model->root_node();
474 const BookmarkNode* node = desiredNode;
475 while (node != rootNode) {
477 nodeStack.push(node);
478 node = node->parent();
480 NSUInteger stackSize = nodeStack.size();
482 NSIndexPath* path = nil;
483 NSArray* folders = [self folderTreeArray];
484 while (!nodeStack.empty()) {
485 node = nodeStack.top();
487 // Find node in the current folders array.
489 for (BookmarkFolderInfo *folderInfo in folders) {
490 const BookmarkNode* testNode = [folderInfo folderNode];
491 if (testNode == node) {
492 path = path ? [path indexPathByAddingIndex:i] :
493 [NSIndexPath indexPathWithIndex:i];
494 folders = [folderInfo children];
500 DCHECK([path length] == stackSize);
504 - (NSMutableArray*)addChildFoldersFromNode:(const BookmarkNode*)node {
505 NSMutableArray* childFolders = nil;
506 int childCount = node->child_count();
507 for (int i = 0; i < childCount; ++i) {
508 const BookmarkNode* childNode = node->GetChild(i);
509 if (childNode->is_folder() && childNode->IsVisible()) {
510 NSString* childName = base::SysUTF16ToNSString(childNode->GetTitle());
511 NSMutableArray* children = [self addChildFoldersFromNode:childNode];
512 BookmarkFolderInfo* folderInfo =
513 [BookmarkFolderInfo bookmarkFolderInfoWithFolderName:childName
517 childFolders = [NSMutableArray arrayWithObject:folderInfo];
519 [childFolders addObject:folderInfo];
525 - (void)buildFolderTree {
526 // Build up a tree of the current folder configuration.
527 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
528 const BookmarkNode* rootNode = model->root_node();
529 NSMutableArray* baseArray = [self addChildFoldersFromNode:rootNode];
531 [self willChangeValueForKey:@"folderTreeArray"];
532 folderTreeArray_.reset([baseArray retain]);
533 [self didChangeValueForKey:@"folderTreeArray"];
536 - (void)modelChangedPreserveSelection:(BOOL)preserve {
537 if (creatingNewFolders_)
539 const BookmarkNode* selectedNode = [self selectedNode];
540 [self buildFolderTree];
543 configuration_ == BookmarkEditor::SHOW_TREE)
544 [self selectNodeInBrowser:selectedNode];
547 - (void)nodeRemoved:(const BookmarkNode*)node
548 fromParent:(const BookmarkNode*)parent {
549 if (node->is_folder()) {
550 if (parentNode_ == node || parentNode_->HasAncestor(node)) {
551 parentNode_ = [self bookmarkModel]->bookmark_bar_node();
552 if (configuration_ != BookmarkEditor::SHOW_TREE) {
553 // The user can't select a different folder, so just close up shop.
559 if (configuration_ == BookmarkEditor::SHOW_TREE) {
560 // For safety's sake, in case deleted node was an ancestor of selection,
561 // go back to a known safe place.
562 [self selectNodeInBrowser:parentNode_];
567 #pragma mark New Folder Handler
569 - (void)createNewFoldersForFolder:(BookmarkFolderInfo*)folderInfo
570 selectedFolderInfo:(BookmarkFolderInfo*)selectedFolderInfo {
571 NSArray* subfolders = [folderInfo children];
572 const BookmarkNode* parentNode = [folderInfo folderNode];
575 for (BookmarkFolderInfo* subFolderInfo in subfolders) {
576 if ([subFolderInfo newFolder]) {
577 BookmarkModel* model = [self bookmarkModel];
578 const BookmarkNode* newFolder =
579 model->AddFolder(parentNode, i,
580 base::SysNSStringToUTF16([subFolderInfo folderName]));
581 // Update our dictionary with the actual folder node just created.
582 [subFolderInfo setFolderNode:newFolder];
583 [subFolderInfo setNewFolder:NO];
585 [self createNewFoldersForFolder:subFolderInfo
586 selectedFolderInfo:selectedFolderInfo];
591 - (IBAction)newFolder:(id)sender {
592 // Create a new folder off of the selected folder node.
593 BookmarkFolderInfo* parentInfo = [self selectedFolder];
595 NSIndexPath* selection = [self selectedIndexPath];
596 NSString* newFolderName =
597 l10n_util::GetNSStringWithFixup(IDS_BOOKMARK_EDITOR_NEW_FOLDER_NAME);
598 BookmarkFolderInfo* folderInfo =
599 [BookmarkFolderInfo bookmarkFolderInfoWithFolderName:newFolderName];
600 [self willChangeValueForKey:@"folderTreeArray"];
601 NSMutableArray* children = [parentInfo children];
603 [children addObject:folderInfo];
605 children = [NSMutableArray arrayWithObject:folderInfo];
606 [parentInfo setChildren:children];
608 [self didChangeValueForKey:@"folderTreeArray"];
610 // Expose the parent folder children.
611 [folderTreeView_ expandItem:parentInfo];
613 // Select the new folder node and put the folder name into edit mode.
614 selection = [selection indexPathByAddingIndex:[children count] - 1];
615 [self setTableSelectionPath:selection];
616 NSInteger row = [folderTreeView_ selectedRow];
619 // Put the cell into single-line mode before putting it into edit mode.
620 // TODO(kushi.p): Remove this when the project hits a 10.6+ only state.
621 NSCell* folderCell = [folderTreeView_ preparedCellAtColumn:0 row:row];
623 respondsToSelector:@selector(setUsesSingleLineMode:)]) {
624 [folderCell setUsesSingleLineMode:YES];
627 [folderTreeView_ editColumn:0 row:row withEvent:nil select:YES];
631 - (void)createNewFolders {
632 base::AutoReset<BOOL> creatingNewFoldersSetter(&creatingNewFolders_, YES);
633 // Scan the tree looking for nodes marked 'newFolder' and create those nodes.
634 NSArray* folderTreeArray = [self folderTreeArray];
635 for (BookmarkFolderInfo *folderInfo in folderTreeArray) {
636 [self createNewFoldersForFolder:folderInfo
637 selectedFolderInfo:[self selectedFolder]];
641 #pragma mark For Unit Test Use Only
643 - (BOOL)okButtonEnabled {
644 return [okButton_ isEnabled];
647 - (void)selectTestNodeInBrowser:(const BookmarkNode*)node {
648 [self selectNodeInBrowser:node];
651 @end // BookmarkEditorBaseController
653 @implementation BookmarkFolderInfo
655 @synthesize folderName = folderName_;
656 @synthesize folderNode = folderNode_;
657 @synthesize children = children_;
658 @synthesize newFolder = newFolder_;
660 + (id)bookmarkFolderInfoWithFolderName:(NSString*)folderName
661 folderNode:(const BookmarkNode*)folderNode
662 children:(NSMutableArray*)children {
663 return [[[BookmarkFolderInfo alloc] initWithFolderName:folderName
664 folderNode:folderNode
670 + (id)bookmarkFolderInfoWithFolderName:(NSString*)folderName {
671 return [[[BookmarkFolderInfo alloc] initWithFolderName:folderName
678 - (id)initWithFolderName:(NSString*)folderName
679 folderNode:(const BookmarkNode*)folderNode
680 children:(NSMutableArray*)children
681 newFolder:(BOOL)newFolder {
682 if ((self = [super init])) {
683 // A folderName is always required, and if newFolder is NO then there
684 // should be a folderNode. Children is optional.
685 DCHECK(folderName && (newFolder || folderNode));
686 if (folderName && (newFolder || folderNode)) {
687 folderName_ = [folderName copy];
688 folderNode_ = folderNode;
689 children_ = [children retain];
690 newFolder_ = newFolder;
692 NOTREACHED(); // Invalid init.
701 NOTREACHED(); // Should never be called.
702 return [self initWithFolderName:nil folderNode:nil children:nil newFolder:NO];
706 [folderName_ release];
711 // Implementing isEqual: allows the NSTreeController to preserve the selection
712 // and open/shut state of outline items when the data changes.
713 - (BOOL)isEqual:(id)other {
714 return [other isKindOfClass:[BookmarkFolderInfo class]] &&
715 folderNode_ == [(BookmarkFolderInfo*)other folderNode];