Annotation of chimera/BookmarksService.mm, revision 1.20

1.16      hyatt       1: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
                      2: /* ***** BEGIN LICENSE BLOCK *****
                      3:  * Version: NPL 1.1/GPL 2.0/LGPL 2.1
1.1       hyatt       4:  *
1.16      hyatt       5:  * The contents of this file are subject to the Netscape Public License
                      6:  * Version 1.1 (the "License"); you may not use this file except in
                      7:  * compliance with the License. You may obtain a copy of the License at
                      8:  * http://www.mozilla.org/NPL/
1.1       hyatt       9:  *
1.16      hyatt      10:  * Software distributed under the License is distributed on an "AS IS" basis,
                     11:  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
                     12:  * for the specific language governing rights and limitations under the
                     13:  * License.
                     14:  *
                     15:  * The Original Code is mozilla.org code.
                     16:  *
                     17:  * The Initial Developer of the Original Code is 
                     18:  * Netscape Communications Corporation.
                     19:  * Portions created by the Initial Developer are Copyright (C) 2002
                     20:  * the Initial Developer. All Rights Reserved.
                     21:  *
                     22:  * Contributor(s):
                     23:  *
                     24:  * Alternatively, the contents of this file may be used under the terms of
                     25:  * either the GNU General Public License Version 2 or later (the "GPL"), or 
                     26:  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
                     27:  * in which case the provisions of the GPL or the LGPL are applicable instead
                     28:  * of those above. If you wish to allow use of your version of this file only
                     29:  * under the terms of either the GPL or the LGPL, and not to allow others to
                     30:  * use your version of this file under the terms of the NPL, indicate your
                     31:  * decision by deleting the provisions above and replace them with the notice
                     32:  * and other provisions required by the GPL or the LGPL. If you do not delete
                     33:  * the provisions above, a recipient may use your version of this file under
                     34:  * the terms of any one of the NPL, the GPL or the LGPL.
                     35:  *
                     36:  * ***** END LICENSE BLOCK ***** */
1.1       hyatt      37: 
                     38: #import "NSBrowserView.h"
                     39: #include "BookmarksService.h"
                     40: #include "nsIDocument.h"
                     41: #include "nsIContent.h"
                     42: #include "nsIAtom.h"
                     43: #include "nsITextContent.h"
1.5       hyatt      44: #include "nsIDOMWindow.h"
                     45: #include "nsIDOMHTMLDocument.h"
1.1       hyatt      46: #include "nsIDOMElement.h"
                     47: #include "nsString.h"
                     48: #include "nsIFile.h"
                     49: #include "nsAppDirectoryServiceDefs.h"
                     50: #include "nsIXMLHttpRequest.h"
1.6       hyatt      51: #include "nsIDOMSerializer.h"
1.1       hyatt      52: #include "nsNetUtil.h"
                     53: #include "nsINamespaceManager.h"
                     54: #include "nsIXBLService.h"
1.5       hyatt      55: #include "nsIWebBrowser.h"
1.1       hyatt      56: 
                     57: @implementation BookmarksDataSource
                     58: 
                     59: -(id) init
                     60: {
                     61:     [super init];
                     62:     mBookmarks = nsnull;
1.20    ! hyatt      63:     mCachedParent = nsnull;
        !            64:     mCachedHref = nil;
1.1       hyatt      65:     return self;
                     66: }
                     67: 
                     68: -(void) dealloc
                     69: {
                     70:     [super dealloc];
1.5       hyatt      71: }
                     72: 
                     73: -(void) windowClosing
                     74: {
                     75:     if (mBookmarks) {
1.4       hyatt      76:         mBookmarks->RemoveObserver();
1.5       hyatt      77:         delete mBookmarks;
                     78:     }
1.1       hyatt      79: }
                     80: 
                     81: -(void) ensureBookmarks
                     82: {
                     83:     if (mBookmarks)
                     84:         return;
                     85:     
1.5       hyatt      86:     mBookmarks = new BookmarksService(self);
1.4       hyatt      87:     mBookmarks->AddObserver();
1.1       hyatt      88:     
                     89:     [mOutlineView setTarget: self];
                     90:     [mOutlineView setDoubleAction: @selector(openBookmark:)];
                     91:     [mOutlineView reloadData];
                     92: }
                     93: 
1.2       hyatt      94: -(IBAction)addBookmark:(id)aSender
                     95: {
1.19      hyatt      96:   [self addBookmark: aSender useSelection: YES];
                     97: }
                     98: 
                     99: -(void)addBookmark:(id)aSender useSelection:(BOOL)aUseSel
                    100: {
                    101:   if (!mBookmarks)
                    102:     return;
                    103: 
                    104:   nsCOMPtr<nsIContent> content;
                    105:   if (aUseSel) {
1.2       hyatt     106:     int index = [mOutlineView selectedRow];
1.19      hyatt     107: 
1.7       hyatt     108:     if (index >= 0) {
1.19      hyatt     109:       BookmarkItem* item = [mOutlineView itemAtRow: index];
                    110:       if ([mOutlineView isExpandable: item])
                    111:         content = [item contentNode];
1.2       hyatt     112:     }
1.19      hyatt     113:   }
                    114: 
                    115:   if (!content)
                    116:     mBookmarks->GetRootContent(getter_AddRefs(content));
                    117: 
                    118:   nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mBookmarks->gBookmarks));
1.20    ! hyatt     119:   
1.19      hyatt     120:   // Fetch the title of the current page and the URL.
                    121:   nsCOMPtr<nsIWebBrowser> webBrowser = getter_AddRefs([[[mBrowserWindowController getMyBrowserView] getBrowserView] getWebBrowser]);
                    122:   nsCOMPtr<nsIDOMWindow> window;
                    123:   webBrowser->GetContentDOMWindow(getter_AddRefs(window));
                    124:   nsCOMPtr<nsIDOMDocument> htmlDoc;
                    125:   window->GetDocument(getter_AddRefs(htmlDoc));
                    126:   nsCOMPtr<nsIDocument> pageDoc(do_QueryInterface(htmlDoc));
                    127: 
                    128:   nsAutoString href;
                    129:   if (pageDoc) {
                    130:     nsCOMPtr<nsIURI> url;
                    131:     pageDoc->GetDocumentURL(getter_AddRefs(url));
                    132:     nsCAutoString spec;
                    133:     url->GetSpec(spec);
                    134:     href.AssignWithConversion(spec.get());
                    135:   }
                    136: 
1.20    ! hyatt     137:   mCachedHref = [NSString stringWithCharacters: href.get() length: nsCRT::strlen(href.get())];
        !           138:   [mCachedHref retain];
        !           139:   
        !           140:   mCachedParent = content;
        !           141:   
1.19      hyatt     142:   nsAutoString title;
                    143:   nsCOMPtr<nsIDOMHTMLDocument> htmlDocument(do_QueryInterface(htmlDoc));
                    144:   if (htmlDocument)
                    145:     htmlDocument->GetTitle(title);
                    146:   if (title.IsEmpty())
                    147:     title = href;
1.20    ! hyatt     148:   
        !           149:   NSTextField* textField = [mBrowserWindowController getAddBookmarkTitle];
        !           150:   [textField setStringValue: [NSString stringWithCharacters: title.get() length: nsCRT::strlen(title.get())]];
        !           151: 
        !           152:   [mBrowserWindowController cacheBookmarkDS: self];
        !           153:   
        !           154:   [NSApp beginSheet: [mBrowserWindowController getAddBookmarkSheetWindow]
        !           155:      modalForWindow: [mBrowserWindowController window]
        !           156:       modalDelegate: nil //self
        !           157:      didEndSelector: nil //@selector(sheetDidEnd:)
        !           158:         contextInfo: nil];
        !           159: }
        !           160: 
        !           161: -(void)endAddBookmark: (int)aCode
        !           162: {
        !           163:   if (aCode == 0)
        !           164:     return;
        !           165:   
        !           166:   const char* titleC = [[[mBrowserWindowController getAddBookmarkTitle] stringValue] cString];
        !           167:   nsAutoString title; title.AssignWithConversion(titleC);
        !           168: 
        !           169:   nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mBookmarks->gBookmarks));
        !           170:   nsCOMPtr<nsIDOMElement> elt;
        !           171:   domDoc->CreateElementNS(NS_LITERAL_STRING("http://chimera.mozdev.org/bookmarks"),
        !           172:                           NS_LITERAL_STRING("bookmark"),
        !           173:                           getter_AddRefs(elt));
1.19      hyatt     174: 
                    175:   elt->SetAttribute(NS_LITERAL_STRING("name"), title);
1.20    ! hyatt     176:   nsAutoString href; href.AssignWithConversion([mCachedHref cString]);
        !           177:   [mCachedHref release];
        !           178:   
1.19      hyatt     179:   elt->SetAttribute(NS_LITERAL_STRING("href"), href);
                    180: 
1.20    ! hyatt     181:   nsCOMPtr<nsIDOMElement> parent(do_QueryInterface(mCachedParent));
1.19      hyatt     182:   nsCOMPtr<nsIDOMNode> dummy;
                    183:   parent->AppendChild(elt, getter_AddRefs(dummy));
1.5       hyatt     184: 
1.19      hyatt     185:   nsCOMPtr<nsIContent> childContent(do_QueryInterface(elt));
1.20    ! hyatt     186:   mBookmarks->BookmarkAdded(mCachedParent, childContent);
1.2       hyatt     187: }
                    188: 
                    189: -(IBAction)deleteBookmark: (id)aSender
                    190: {
1.6       hyatt     191:     if (!mBookmarks)
                    192:         return;
                    193:     
                    194:     int index = [mOutlineView selectedRow];
                    195:     if (index == -1)
                    196:         return;
                    197:         
                    198:     BookmarkItem* item = [mOutlineView itemAtRow: index];
                    199:     nsCOMPtr<nsIContent> content = [item contentNode];
                    200:     nsCOMPtr<nsIDOMElement> child(do_QueryInterface(content));
                    201:     nsCOMPtr<nsIDOMNode> parent;
                    202:     child->GetParentNode(getter_AddRefs(parent));
1.19      hyatt     203:     nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parent));
1.6       hyatt     204:     nsCOMPtr<nsIDOMNode> dummy;
                    205:     parent->RemoveChild(child, getter_AddRefs(dummy));
1.19      hyatt     206:     mBookmarks->BookmarkRemoved(parentContent, content);
1.6       hyatt     207:     
                    208:     int total = [mOutlineView numberOfRows];
                    209:     if (index == total)
                    210:         index--;
                    211:         
                    212:     [mOutlineView selectRow: index byExtendingSelection: NO];
1.2       hyatt     213: }
                    214: 
1.1       hyatt     215: -(IBAction)openBookmark: (id)aSender
                    216: {
                    217:     int index = [mOutlineView selectedRow];
                    218:     if (index == -1)
                    219:         return;
                    220:     
                    221:     id item = [mOutlineView itemAtRow: index];
                    222:     if (!item)
                    223:         return;
                    224:         
                    225:     if ([mOutlineView isExpandable: item]) {
                    226:         if ([mOutlineView isItemExpanded: item])
                    227:             [mOutlineView collapseItem: item];
                    228:         else
                    229:             [mOutlineView expandItem: item];
                    230:     }
                    231:     else {
                    232:         nsIContent* content = [item contentNode];
                    233:         nsAutoString href;
                    234:         content->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, href);
                    235:         if (!href.IsEmpty()) {
                    236:             nsCAutoString cstr; cstr.AssignWithConversion(href);
                    237:             NSString* url = [NSString stringWithCString: cstr.get()];
1.14      hyatt     238:             [[[mBrowserWindowController getMyBrowserView] getBrowserView] loadURI:[NSURL URLWithString: url] flags:NSLoadFlagsNone];
1.18      hyatt     239:             // Focus and activate our content area.
                    240:             [[[mBrowserWindowController getMyBrowserView] getBrowserView] setActive: YES];
1.1       hyatt     241:         }
                    242:     } 
                    243: }
                    244: 
1.9       hyatt     245: - (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
                    246: {
1.10      hyatt     247:     return NO;
1.9       hyatt     248: }
                    249: 
1.1       hyatt     250: - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
                    251: {
                    252:     if (!mBookmarks)
                    253:         return nil;
                    254:        
                    255:     nsCOMPtr<nsIContent> content;
                    256:     if (!item)
                    257:         mBookmarks->GetRootContent(getter_AddRefs(content));
                    258:     else
                    259:         content = [item contentNode];
                    260:     
                    261:     nsCOMPtr<nsIContent> child;
                    262:     content->ChildAt(index, *getter_AddRefs(child));
                    263:     return mBookmarks->GetWrapperFor(child);
                    264: }
                    265: 
                    266: - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
                    267: {
                    268:     if (!mBookmarks)
                    269:         return NO;
                    270:     
                    271:     if (!item)
                    272:         return YES; // The root node is always open.
                    273:     
                    274:     nsCOMPtr<nsIAtom> tagName;
                    275:     nsIContent* content = [item contentNode];
                    276:     content->GetTag(*getter_AddRefs(tagName));
                    277:     
                    278:     return (tagName == BookmarksService::gFolderAtom);
                    279: }
                    280: 
                    281: - (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
                    282: {
                    283:     if (!mBookmarks)
                    284:         return 0;
1.2       hyatt     285:   
1.1       hyatt     286:     nsCOMPtr<nsIContent> content;
                    287:     if (!item)
                    288:         mBookmarks->GetRootContent(getter_AddRefs(content));
                    289:     else 
                    290:         content = [item contentNode];
                    291:     
                    292:     PRInt32 childCount;
                    293:     content->ChildCount(childCount);
                    294:     
                    295:     return childCount;
                    296: }
                    297: 
                    298: - (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
                    299: {
1.13      macserv   300:     NSString           *columnName = [tableColumn identifier];
1.11      macserv   301:     NSMutableAttributedString  *cellValue = [[NSMutableAttributedString alloc] init];
1.13      macserv   302:     NSFileWrapper        *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:nil];
                    303:     NSTextAttachment     *textAttachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];
1.11      macserv   304:     NSMutableAttributedString   *attachmentAttrString = nil;
1.13      macserv   305:     NSCell             *attachmentAttrStringCell;
1.11      macserv   306: 
1.13      macserv   307:     if ([columnName isEqualToString: @"name"]) {
                    308:         nsIContent* content = [item contentNode];
                    309:         nsAutoString nameAttr;
                    310:         content->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr);
                    311:         nsCAutoString cStr; cStr.AssignWithConversion(nameAttr);
                    312:         
                    313:         //Set cell's textual contents
                    314:         [cellValue replaceCharactersInRange:NSMakeRange(0, [cellValue length])
                    315:                                  withString:[NSString stringWithCString: cStr.get()]];
                    316:         
                    317:         //Create an attributed string to hold the empty attachment, then release the components.
                    318:         attachmentAttrString = [[NSMutableAttributedString attributedStringWithAttachment:textAttachment] retain];
                    319:         [textAttachment release];
                    320:         [fileWrapper release];
1.11      macserv   321: 
1.13      macserv   322:         //Get the cell of the text attachment.
                    323:         attachmentAttrStringCell = (NSCell *)[(NSTextAttachment *)[attachmentAttrString attribute:NSAttachmentAttributeName
                    324:                                                                                           atIndex:0
                    325:                                                                                    effectiveRange:nil] attachmentCell];
                    326:         //Figure out which image to add, and set the cell's image.
                    327:         if ( [self outlineView:outlineView isItemExpandable:item] ) {
                    328:             [attachmentAttrStringCell setImage:[NSImage imageNamed:@"folder"]];
                    329:         } else {
1.17      macserv   330:             [attachmentAttrStringCell setImage:[NSImage imageNamed:@"smallbookmark"]];
1.11      macserv   331:         }
1.13      macserv   332:         //Insert the image
                    333:         [cellValue replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attachmentAttrString];
                    334:         
                    335:         //Tweak the baseline to vertically center the text.
                    336:         [cellValue addAttribute:NSBaselineOffsetAttributeName
                    337:                           value:[NSNumber numberWithFloat:-3.0]
                    338:                           range:NSMakeRange(0, 1)];
1.1       hyatt     339:     }
1.13      macserv   340:     return cellValue;
1.1       hyatt     341: }
                    342: 
                    343: - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
                    344: {
                    345: }
                    346: 
1.5       hyatt     347: - (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren
                    348: {
                    349:     printf("Reloading?\n");
                    350:     if (!item)
                    351:         [mOutlineView reloadData];
                    352:     else if ([mOutlineView isItemExpanded: item])
                    353:         [mOutlineView reloadItem: item reloadChildren: aReloadChildren];
                    354: }
                    355: 
1.1       hyatt     356: @end
                    357: 
                    358: @implementation BookmarkItem
                    359: -(nsIContent*)contentNode
                    360: {
                    361:     return mContentNode;
                    362: }
                    363: 
                    364: -(void)setContentNode: (nsIContent*)aContentNode
                    365: {
                    366:     mContentNode = aContentNode;
                    367: }
1.7       hyatt     368: 
                    369: - (id)copyWithZone:(NSZone *)aZone
                    370: {
                    371:     BookmarkItem* copy = [[[self class] allocWithZone: aZone] init];
                    372:     [copy setContentNode: mContentNode];
                    373:     return copy;
                    374: }
                    375: 
1.1       hyatt     376: @end
                    377: 
                    378: // Helper for stripping whitespace
                    379: static void
                    380: StripWhitespaceNodes(nsIContent* aElement)
                    381: {
                    382:     PRInt32 childCount;
                    383:     aElement->ChildCount(childCount);
                    384:     for (PRInt32 i = 0; i < childCount; i++) {
                    385:         nsCOMPtr<nsIContent> child;
                    386:         aElement->ChildAt(i, *getter_AddRefs(child));
                    387:         nsCOMPtr<nsITextContent> text = do_QueryInterface(child);
                    388:         if (text) {
                    389:             PRBool isEmpty;
                    390:             text->IsOnlyWhitespace(&isEmpty);
                    391:             if (isEmpty) {
                    392:                 // This node contained nothing but whitespace.
                    393:                 // Remove it from the content model.
                    394:                 aElement->RemoveChildAt(i, PR_TRUE);
                    395:                 i--; // Decrement our count, since we just removed this child.
                    396:                 childCount--; // Also decrement our total count.
                    397:             }
                    398:         }
                    399:         else StripWhitespaceNodes(child);
                    400:     }
                    401: }
                    402: 
                    403: PRUint32 BookmarksService::gRefCnt = 0;
1.4       hyatt     404: nsIDocument* BookmarksService::gBookmarks = nsnull;
                    405: NSMutableDictionary* BookmarksService::gDictionary = nil;
1.8       hyatt     406: MainController* BookmarksService::gMainController = nil;
1.19      hyatt     407: NSMenu* BookmarksService::gBookmarksMenu = nil;
1.1       hyatt     408: nsIAtom* BookmarksService::gFolderAtom = nsnull;
                    409: nsIAtom* BookmarksService::gBookmarkAtom = nsnull;
                    410: nsIAtom* BookmarksService::gHrefAtom = nsnull;
                    411: nsIAtom* BookmarksService::gNameAtom = nsnull;
1.5       hyatt     412: nsVoidArray* BookmarksService::gInstances = nsnull;
1.1       hyatt     413: 
1.5       hyatt     414: BookmarksService::BookmarksService(BookmarksDataSource* aDataSource)
1.1       hyatt     415: {
1.5       hyatt     416:     mDataSource = aDataSource;
1.1       hyatt     417: }
                    418: 
                    419: BookmarksService::~BookmarksService()
                    420: {
                    421: }
                    422: 
                    423: void
                    424: BookmarksService::GetRootContent(nsIContent** aResult)
                    425: {
                    426:     *aResult = nsnull;
1.4       hyatt     427:     if (gBookmarks) {
1.1       hyatt     428:         nsCOMPtr<nsIDOMElement> elt;
1.4       hyatt     429:         nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
1.1       hyatt     430:         domDoc->GetDocumentElement(getter_AddRefs(elt));
                    431:         elt->QueryInterface(NS_GET_IID(nsIContent), (void**)aResult); // Addref happens here.
                    432:     }
                    433: }
                    434: 
                    435: BookmarkItem*
                    436: BookmarksService::GetWrapperFor(nsIContent* aContent)
                    437: {
1.4       hyatt     438:     if (!gDictionary)
                    439:         gDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
1.1       hyatt     440:     
                    441:     PRUint32 contentID;
                    442:     aContent->GetContentID(&contentID);
                    443:     
1.4       hyatt     444:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: contentID]];
1.1       hyatt     445:     if (item)
                    446:         return item;
                    447:     else {
                    448:         // Create an item.
                    449:         item = [[[BookmarkItem alloc] init] autorelease]; // The dictionary retains us.
                    450:         [item setContentNode: aContent];
1.4       hyatt     451:         [gDictionary setObject: item forKey: [NSNumber numberWithInt: contentID]];
1.1       hyatt     452:     }
                    453:     return item;
                    454: }
                    455: 
1.19      hyatt     456: NSMenu*
                    457: BookmarksService::LocateMenu(nsIContent* aContent)
                    458: {
                    459:   nsCOMPtr<nsIContent> parent;
                    460:   aContent->GetParent(*getter_AddRefs(parent));
                    461:   if (!parent)
                    462:     return BookmarksService::gBookmarksMenu;
                    463: 
                    464:   NSMenu* parentMenu = LocateMenu(parent);
                    465:   
                    466:   PRUint32 contentID;
                    467:   aContent->GetContentID(&contentID);
                    468: 
                    469:   NSMenuItem* childMenu = [parentMenu itemWithTag: contentID];
                    470:   return [childMenu menu];
                    471: }
                    472: 
1.5       hyatt     473: void
1.19      hyatt     474: BookmarksService::BookmarkAdded(nsIContent* aContainer, nsIContent* aChild)
1.4       hyatt     475: {
1.19      hyatt     476:   if (!gInstances || !gDictionary)
                    477:     return;
                    478: 
                    479:   PRInt32 count = gInstances->Count();
                    480:   for (PRInt32 i = 0; i < count; i++) {
                    481:     BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
                    482: 
                    483:     if (instance->mDataSource) {
                    484:       // We're a tree view.
                    485:       nsCOMPtr<nsIContent> parent;
                    486:       aContainer->GetParent(*getter_AddRefs(parent));
                    487: 
                    488:       BookmarkItem* item = nil;
                    489:       if (parent)
                    490:         // We're not the root.
                    491:         item = GetWrapperFor(aContainer);
                    492: 
                    493:       [(instance->mDataSource) reloadDataForItem: item reloadChildren: YES];
                    494:     }
                    495:     else {
                    496:       // We're the menu.
                    497:       PRInt32 index = -1;
                    498:       aChild->IndexOf(aContainer, index);
                    499:       NSMenu* menu = LocateMenu(aContainer);
                    500:       AddMenuBookmark(menu, aContainer, aChild, index);
1.5       hyatt     501:     }
1.19      hyatt     502:   }
                    503:   
                    504:   FlushBookmarks();  
1.4       hyatt     505: }
                    506: 
1.19      hyatt     507: void
                    508: BookmarksService::BookmarkChanged(nsIContent* aItem)
                    509: {
                    510:   if (!gInstances || !gDictionary)
                    511:     return;
                    512: 
                    513:   PRInt32 count = gInstances->Count();
                    514:   for (PRInt32 i = 0; i < count; i++) {
                    515:     BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
                    516:    
                    517:     if (instance->mDataSource) {
                    518:       BookmarkItem* item = GetWrapperFor(aItem);
                    519:       [(instance->mDataSource) reloadDataForItem: item reloadChildren: NO];
                    520:     }
                    521:   }
                    522: 
                    523:   FlushBookmarks();  
                    524: }
1.4       hyatt     525: 
1.5       hyatt     526: void
1.19      hyatt     527: BookmarksService::BookmarkRemoved(nsIContent* aContainer, nsIContent* aChild)
1.4       hyatt     528: {
1.19      hyatt     529:   if (!gInstances)
                    530:     return;
                    531: 
                    532:   PRInt32 count = gInstances->Count();
                    533:   for (PRInt32 i = 0; i < count; i++) {
                    534:     BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
                    535: 
                    536:     if (instance->mDataSource) {
                    537:       // We're a tree view.
                    538:       nsCOMPtr<nsIContent> parent;
                    539:       aContainer->GetParent(*getter_AddRefs(parent));
                    540: 
                    541:       BookmarkItem* item = nil;
                    542:       if (parent)
1.5       hyatt     543:         // We're not the root.
                    544:         item = GetWrapperFor(aContainer);
1.19      hyatt     545: 
                    546:       [(instance->mDataSource) reloadDataForItem: item reloadChildren: YES];
                    547:     }
                    548:     else {
                    549:       // We're the menu.
                    550:       NSMenu* menu = LocateMenu(aContainer);
                    551:       PRUint32 contentID;
                    552:       aChild->GetContentID(&contentID);
                    553:       NSMenuItem* childItem = [menu itemWithTag: contentID];
                    554:       [menu removeItem: childItem];
                    555:     }
                    556:   }
                    557: 
                    558:   FlushBookmarks(); 
1.4       hyatt     559: }
                    560: 
                    561: void
                    562: BookmarksService::AddObserver()
1.1       hyatt     563: {
                    564:     gRefCnt++;
                    565:     if (gRefCnt == 1) {
                    566:         gBookmarkAtom = NS_NewAtom("bookmark");
                    567:         gFolderAtom = NS_NewAtom("folder");
                    568:         gNameAtom = NS_NewAtom("name");
                    569:         gHrefAtom = NS_NewAtom("href");
1.5       hyatt     570:         gInstances = new nsVoidArray();
1.8       hyatt     571:                 
1.4       hyatt     572:         nsCOMPtr<nsIFile> profileDir;
                    573:         NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profileDir));
                    574:         profileDir->Append("bookmarks.xml");
                    575:     
1.15      hyatt     576:         nsCAutoString bookmarksFileURL;
                    577:         NS_GetURLSpecFromFile(profileDir, bookmarksFileURL);
1.4       hyatt     578:         
                    579:         nsCOMPtr<nsIURI> uri;
                    580:         NS_NewURI(getter_AddRefs(uri), bookmarksFileURL.get());
                    581:     
                    582:         nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));    
                    583:         xblService->FetchSyncXMLDocument(uri, &gBookmarks); // The addref is here.
                    584:         
                    585:         nsCOMPtr<nsIContent> rootNode;
                    586:         GetRootContent(getter_AddRefs(rootNode));
                    587:         StripWhitespaceNodes(rootNode);
1.1       hyatt     588:     }
                    589:     
1.5       hyatt     590:     gInstances->AppendElement(this);
1.1       hyatt     591: }
                    592: 
                    593: void
1.4       hyatt     594: BookmarksService::RemoveObserver()
1.1       hyatt     595: {
                    596:     if (gRefCnt == 0)
                    597:         return;
1.4       hyatt     598:  
1.5       hyatt     599:     gInstances->RemoveElement(this);
                    600:      
1.1       hyatt     601:     gRefCnt--;
                    602:     if (gRefCnt == 0) {
1.4       hyatt     603:         NS_IF_RELEASE(gBookmarks);
1.1       hyatt     604:         NS_RELEASE(gBookmarkAtom);
                    605:         NS_RELEASE(gFolderAtom);
                    606:         NS_RELEASE(gNameAtom);
                    607:         NS_RELEASE(gHrefAtom);
1.4       hyatt     608:         [gDictionary release];
1.1       hyatt     609:     }
                    610: }
                    611: 
1.6       hyatt     612: void
                    613: BookmarksService::FlushBookmarks()
                    614: {
                    615:     nsCOMPtr<nsIFile> bookmarksFile;
                    616:     NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(bookmarksFile));
                    617:     bookmarksFile->Append("bookmarks.xml");
                    618: 
                    619:     nsCOMPtr<nsIOutputStream> outputStream;
                    620:     NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), bookmarksFile);
                    621: 
                    622:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
                    623:     
                    624:     nsCOMPtr<nsIDOMSerializer> domSerializer(do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID));
                    625:     domSerializer->SerializeToStream(domDoc, outputStream, nsnull);
1.7       hyatt     626: }
                    627: 
                    628: void
                    629: BookmarksService::ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent)
                    630: {
                    631:     nsCOMPtr<nsIContent> content = aContent;
                    632:     if (!content) {
                    633:         GetRootContent(getter_AddRefs(content));
1.8       hyatt     634:         GetWrapperFor(content);
1.19      hyatt     635:         gBookmarksMenu = aMenu;
1.7       hyatt     636:     }
                    637:     
                    638:     // Now walk our children, and for folders also recur into them.
                    639:     PRInt32 childCount;
                    640:     content->ChildCount(childCount);
                    641:     
                    642:     for (PRInt32 i = 0; i < childCount; i++) {
1.19      hyatt     643:       nsCOMPtr<nsIContent> child;
                    644:       content->ChildAt(i, *getter_AddRefs(child));
                    645:       AddMenuBookmark(aMenu, content, child, -1);
1.7       hyatt     646:     }
1.19      hyatt     647: }
                    648: 
                    649: void
                    650: BookmarksService::AddMenuBookmark(NSMenu* aMenu, nsIContent* aParent, nsIContent* aChild, PRInt32 aIndex)
                    651: {
                    652:   nsAutoString name;
                    653:   aChild->GetAttr(kNameSpaceID_None, gNameAtom, name);
                    654:   nsCAutoString nameCStr; nameCStr.AssignWithConversion(name);
                    655:   NSString* title = [NSString stringWithCString: nameCStr.get()];
                    656: 
                    657:   // Create a menu or menu item for the child.
                    658:   NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
                    659:   GetWrapperFor(aChild);
                    660: 
                    661:   if (aIndex == -1)
                    662:     [aMenu addItem: menuItem];
                    663:   else
                    664:     [aMenu insertItem: menuItem atIndex: aIndex];
                    665:   
                    666:   nsCOMPtr<nsIAtom> tagName;
                    667:   aChild->GetTag(*getter_AddRefs(tagName));
                    668: 
                    669:   if (tagName == gFolderAtom) {
                    670:     NSMenu* menu = [[[NSMenu alloc] initWithTitle: title] autorelease];
                    671:     [aMenu setSubmenu: menu forItem: menuItem];
                    672:     [menu setAutoenablesItems: NO];
                    673:     ConstructBookmarksMenu(menu, aChild);
                    674:   }
                    675:   else {
                    676:     [menuItem setTarget: gMainController];
                    677:     [menuItem setAction: @selector(openMenuBookmark:)];
                    678:   }
                    679: 
                    680:   PRUint32 contentID;
                    681:   aChild->GetContentID(&contentID);
                    682:   [menuItem setTag: contentID];
1.6       hyatt     683: }
1.8       hyatt     684: 
                    685: void 
                    686: BookmarksService::OpenMenuBookmark(BrowserWindowController* aController, id aMenuItem)
                    687: {
                    688:     // Get the corresponding bookmark item.
                    689:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: [aMenuItem tag]]];
                    690:         
                    691:     // Get the content node.
                    692:     nsIContent* content = [item contentNode];
                    693:         
                    694:     // Get the href attribute.  This is the URL we want to load.
                    695:     nsAutoString href;
                    696:     content->GetAttr(kNameSpaceID_None, gHrefAtom, href);
                    697:     nsCAutoString cref; cref.AssignWithConversion(href);
                    698:     if (cref.IsEmpty())
                    699:         return;
                    700:         
                    701:     NSString* url = [NSString stringWithCString: cref.get()];
                    702:     
                    703:     // Now load the URL in the window.
                    704:     [aController loadURL:[NSURL URLWithString: url]];
1.18      hyatt     705:     
                    706:     // Focus and activate our content area.
                    707:     [[[aController getMyBrowserView] getBrowserView] setActive: YES];
1.8       hyatt     708: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>