File:  [mozdev] / chimera / BookmarksService.mm
Revision 1.12: download - view: text, annotated - select for diffs - revision graph
Mon Feb 11 10:28:30 2002 UTC (17 years, 3 months ago) by macserv
Branches: MAIN
CVS tags: HEAD
/me removes an NSLog.

    1: /*
    2:  *  BookmarksService.cpp
    3:  *  Chimera
    4:  *
    5:  *  Created by David Hyatt on Thu Feb 07 2002.
    6:  *  Copyright (c) 2001 __MyCompanyName__. All rights reserved.
    7:  *
    8:  */
    9: 
   10: #import "NSBrowserView.h"
   11: #include "BookmarksService.h"
   12: #include "nsIDocument.h"
   13: #include "nsIContent.h"
   14: #include "nsIAtom.h"
   15: #include "nsITextContent.h"
   16: #include "nsIDOMWindow.h"
   17: #include "nsIDOMHTMLDocument.h"
   18: #include "nsIDOMElement.h"
   19: #include "nsString.h"
   20: #include "nsIFile.h"
   21: #include "nsAppDirectoryServiceDefs.h"
   22: #include "nsIXMLHttpRequest.h"
   23: #include "nsIDOMSerializer.h"
   24: #include "nsNetUtil.h"
   25: #include "nsINamespaceManager.h"
   26: #include "nsIXBLService.h"
   27: #include "nsIWebBrowser.h"
   28: 
   29: @implementation BookmarksDataSource
   30: 
   31: -(id) init
   32: {
   33:     [super init];
   34:     mBookmarks = nsnull;
   35:     return self;
   36: }
   37: 
   38: -(void) dealloc
   39: {
   40:     [super dealloc];
   41: }
   42: 
   43: -(void) windowClosing
   44: {
   45:     if (mBookmarks) {
   46:         mBookmarks->RemoveObserver();
   47:         delete mBookmarks;
   48:     }
   49: }
   50: 
   51: -(void) ensureBookmarks
   52: {
   53:     if (mBookmarks)
   54:         return;
   55:     
   56:     mBookmarks = new BookmarksService(self);
   57:     mBookmarks->AddObserver();
   58:     
   59:     [mOutlineView setTarget: self];
   60:     [mOutlineView setDoubleAction: @selector(openBookmark:)];
   61:     [mOutlineView reloadData];
   62: }
   63: 
   64: -(IBAction)addBookmark:(id)aSender
   65: {
   66:     if (!mBookmarks)
   67:         return;
   68:     
   69:     nsCOMPtr<nsIContent> content;
   70:     int index = [mOutlineView selectedRow];
   71:    
   72:     if (index >= 0) {
   73:         BookmarkItem* item = [mOutlineView itemAtRow: index];
   74:         if ([mOutlineView isExpandable: item]) 
   75:             content = [item contentNode];
   76:     }
   77:     
   78:     if (!content)
   79:         mBookmarks->GetRootContent(getter_AddRefs(content));
   80:         
   81:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mBookmarks->gBookmarks));
   82:     nsCOMPtr<nsIDOMElement> elt;
   83:     domDoc->CreateElementNS(NS_LITERAL_STRING("http://chimera.mozdev.org/bookmarks"), 
   84:                             NS_LITERAL_STRING("bookmark"), 
   85:                             getter_AddRefs(elt));
   86:     
   87:     // Fetch the title of the current page and the URL.
   88:     nsCOMPtr<nsIWebBrowser> webBrowser = getter_AddRefs([[mBrowserView getBrowserView] getWebBrowser]);
   89:     nsCOMPtr<nsIDOMWindow> window;
   90:     webBrowser->GetContentDOMWindow(getter_AddRefs(window));
   91:     nsCOMPtr<nsIDOMDocument> htmlDoc;
   92:     window->GetDocument(getter_AddRefs(htmlDoc));
   93:     nsCOMPtr<nsIDocument> pageDoc(do_QueryInterface(htmlDoc));
   94:     
   95:     nsAutoString href; 
   96:     if (pageDoc) {
   97:         nsCOMPtr<nsIURI> url;
   98:         pageDoc->GetDocumentURL(getter_AddRefs(url));
   99:         nsXPIDLCString spec;
  100:         url->GetSpec(getter_Copies(spec));
  101:         href.AssignWithConversion(spec.get());
  102:     }
  103:     
  104:     nsAutoString title;
  105:     nsCOMPtr<nsIDOMHTMLDocument> htmlDocument(do_QueryInterface(htmlDoc));
  106:     if (htmlDocument)
  107:         htmlDocument->GetTitle(title);
  108:     if (title.IsEmpty())
  109:         title = href;
  110:         
  111:     elt->SetAttribute(NS_LITERAL_STRING("name"), title);
  112:     elt->SetAttribute(NS_LITERAL_STRING("href"), href);    
  113:     
  114:     nsCOMPtr<nsIDOMElement> parent(do_QueryInterface(content));
  115:     nsCOMPtr<nsIDOMNode> dummy;
  116:     parent->AppendChild(elt, getter_AddRefs(dummy));
  117: 
  118:     mBookmarks->NotifyObservers(content, PR_TRUE);
  119: }
  120: 
  121: -(IBAction)deleteBookmark: (id)aSender
  122: {
  123:     if (!mBookmarks)
  124:         return;
  125:     
  126:     int index = [mOutlineView selectedRow];
  127:     if (index == -1)
  128:         return;
  129:         
  130:     BookmarkItem* item = [mOutlineView itemAtRow: index];
  131:     nsCOMPtr<nsIContent> content = [item contentNode];
  132:     nsCOMPtr<nsIDOMElement> child(do_QueryInterface(content));
  133:     nsCOMPtr<nsIDOMNode> parent;
  134:     child->GetParentNode(getter_AddRefs(parent));
  135:     nsCOMPtr<nsIDOMNode> dummy;
  136:     parent->RemoveChild(child, getter_AddRefs(dummy));
  137:     nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parent));
  138:     mBookmarks->NotifyObservers(parentContent, PR_TRUE);
  139:     
  140:     int total = [mOutlineView numberOfRows];
  141:     if (index == total)
  142:         index--;
  143:         
  144:     [mOutlineView selectRow: index byExtendingSelection: NO];
  145: }
  146: 
  147: -(IBAction)openBookmark: (id)aSender
  148: {
  149:     int index = [mOutlineView selectedRow];
  150:     if (index == -1)
  151:         return;
  152:     
  153:     id item = [mOutlineView itemAtRow: index];
  154:     if (!item)
  155:         return;
  156:         
  157:     if ([mOutlineView isExpandable: item]) {
  158:         if ([mOutlineView isItemExpanded: item])
  159:             [mOutlineView collapseItem: item];
  160:         else
  161:             [mOutlineView expandItem: item];
  162:     }
  163:     else {
  164:         nsIContent* content = [item contentNode];
  165:         nsAutoString href;
  166:         content->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, href);
  167:         if (!href.IsEmpty()) {
  168:             nsCAutoString cstr; cstr.AssignWithConversion(href);
  169:             NSString* url = [NSString stringWithCString: cstr.get()];
  170:             [[mBrowserView getBrowserView] loadURI:[NSURL URLWithString: url] flags:NSLoadFlagsNone];
  171:         }
  172:     } 
  173: }
  174: 
  175: - (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
  176: {
  177:     return NO;
  178: }
  179: 
  180: - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
  181: {
  182:     if (!mBookmarks)
  183:         return nil;
  184:        
  185:     nsCOMPtr<nsIContent> content;
  186:     if (!item)
  187:         mBookmarks->GetRootContent(getter_AddRefs(content));
  188:     else
  189:         content = [item contentNode];
  190:     
  191:     nsCOMPtr<nsIContent> child;
  192:     content->ChildAt(index, *getter_AddRefs(child));
  193:     return mBookmarks->GetWrapperFor(child);
  194: }
  195: 
  196: - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
  197: {
  198:     if (!mBookmarks)
  199:         return NO;
  200:     
  201:     if (!item)
  202:         return YES; // The root node is always open.
  203:     
  204:     nsCOMPtr<nsIAtom> tagName;
  205:     nsIContent* content = [item contentNode];
  206:     content->GetTag(*getter_AddRefs(tagName));
  207:     
  208:     return (tagName == BookmarksService::gFolderAtom);
  209: }
  210: 
  211: - (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
  212: {
  213:     if (!mBookmarks)
  214:         return 0;
  215:   
  216:     nsCOMPtr<nsIContent> content;
  217:     if (!item)
  218:         mBookmarks->GetRootContent(getter_AddRefs(content));
  219:     else 
  220:         content = [item contentNode];
  221:     
  222:     PRInt32 childCount;
  223:     content->ChildCount(childCount);
  224:     
  225:     return childCount;
  226: }
  227: 
  228: - (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  229: {
  230:     NSMutableAttributedString 	*cellValue = [[NSMutableAttributedString alloc] init];
  231:     NSMutableAttributedString   *attachmentAttrString = nil;
  232:     NSString 					*columnName = [tableColumn identifier];
  233:     NSCell 						*attachmentCell;
  234: 
  235:     if ( item ) {
  236:         if ([columnName isEqualToString: @"name"]) {
  237:             nsIContent* content = [item contentNode];
  238:             nsAutoString nameAttr;
  239:             content->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr);
  240:             nsCAutoString cStr; cStr.AssignWithConversion(nameAttr);
  241:             
  242:         //set cell's textual contents
  243:             [cellValue replaceCharactersInRange:NSMakeRange(0, [cellValue length])
  244:                                      withString:[NSString stringWithCString: cStr.get()]];
  245:             
  246:         //Add image to cell's text in front of the text.
  247:             NSFileWrapper *wrapper = [[NSFileWrapper alloc] initRegularFileWithContents:nil];
  248:             NSTextAttachment *attachment = [[NSTextAttachment allocWithZone:NULL] initWithFileWrapper:wrapper];
  249:             attachmentAttrString = [[NSMutableAttributedString attributedStringWithAttachment:attachment] retain];
  250:             [attachment release];
  251:             [wrapper release];
  252: 
  253:             attachmentCell = (NSCell *)[(NSTextAttachment *)[attachmentAttrString attribute:NSAttachmentAttributeName
  254:                                                                                     atIndex:0
  255:                                                                              effectiveRange:NULL] attachmentCell];
  256: 
  257:             [attachmentCell setImage:[NSImage imageNamed:@"folder"]];
  258:             [cellValue replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attachmentAttrString];
  259:             [cellValue addAttribute:NSBaselineOffsetAttributeName
  260:                               value:[NSNumber numberWithFloat:-3.0]
  261:                               range:NSMakeRange(0, 1)];
  262:         //Done adding image. 
  263:         }
  264:         return cellValue;
  265:     } else {
  266:         return nil;
  267:     }
  268: }
  269: 
  270: - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  271: {
  272: }
  273: 
  274: - (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren
  275: {
  276:     printf("Reloading?\n");
  277:     if (!item)
  278:         [mOutlineView reloadData];
  279:     else if ([mOutlineView isItemExpanded: item])
  280:         [mOutlineView reloadItem: item reloadChildren: aReloadChildren];
  281: }
  282: 
  283: @end
  284: 
  285: @implementation BookmarkItem
  286: -(nsIContent*)contentNode
  287: {
  288:     return mContentNode;
  289: }
  290: 
  291: -(void)setContentNode: (nsIContent*)aContentNode
  292: {
  293:     mContentNode = aContentNode;
  294: }
  295: 
  296: - (id)copyWithZone:(NSZone *)aZone
  297: {
  298:     BookmarkItem* copy = [[[self class] allocWithZone: aZone] init];
  299:     [copy setContentNode: mContentNode];
  300:     return copy;
  301: }
  302: 
  303: @end
  304: 
  305: // Helper for stripping whitespace
  306: static void
  307: StripWhitespaceNodes(nsIContent* aElement)
  308: {
  309:     PRInt32 childCount;
  310:     aElement->ChildCount(childCount);
  311:     for (PRInt32 i = 0; i < childCount; i++) {
  312:         nsCOMPtr<nsIContent> child;
  313:         aElement->ChildAt(i, *getter_AddRefs(child));
  314:         nsCOMPtr<nsITextContent> text = do_QueryInterface(child);
  315:         if (text) {
  316:             PRBool isEmpty;
  317:             text->IsOnlyWhitespace(&isEmpty);
  318:             if (isEmpty) {
  319:                 // This node contained nothing but whitespace.
  320:                 // Remove it from the content model.
  321:                 aElement->RemoveChildAt(i, PR_TRUE);
  322:                 i--; // Decrement our count, since we just removed this child.
  323:                 childCount--; // Also decrement our total count.
  324:             }
  325:         }
  326:         else StripWhitespaceNodes(child);
  327:     }
  328: }
  329: 
  330: PRUint32 BookmarksService::gRefCnt = 0;
  331: nsIDocument* BookmarksService::gBookmarks = nsnull;
  332: NSMutableDictionary* BookmarksService::gDictionary = nil;
  333: MainController* BookmarksService::gMainController = nil;
  334: nsIAtom* BookmarksService::gFolderAtom = nsnull;
  335: nsIAtom* BookmarksService::gBookmarkAtom = nsnull;
  336: nsIAtom* BookmarksService::gHrefAtom = nsnull;
  337: nsIAtom* BookmarksService::gNameAtom = nsnull;
  338: nsVoidArray* BookmarksService::gInstances = nsnull;
  339: 
  340: BookmarksService::BookmarksService(BookmarksDataSource* aDataSource)
  341: {
  342:     mDataSource = aDataSource;
  343: }
  344: 
  345: BookmarksService::~BookmarksService()
  346: {
  347: }
  348: 
  349: void
  350: BookmarksService::GetRootContent(nsIContent** aResult)
  351: {
  352:     *aResult = nsnull;
  353:     if (gBookmarks) {
  354:         nsCOMPtr<nsIDOMElement> elt;
  355:         nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  356:         domDoc->GetDocumentElement(getter_AddRefs(elt));
  357:         elt->QueryInterface(NS_GET_IID(nsIContent), (void**)aResult); // Addref happens here.
  358:     }
  359: }
  360: 
  361: BookmarkItem*
  362: BookmarksService::GetWrapperFor(nsIContent* aContent)
  363: {
  364:     if (!gDictionary)
  365:         gDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
  366:     
  367:     PRUint32 contentID;
  368:     aContent->GetContentID(&contentID);
  369:     
  370:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: contentID]];
  371:     if (item)
  372:         return item;
  373:     else {
  374:         // Create an item.
  375:         item = [[[BookmarkItem alloc] init] autorelease]; // The dictionary retains us.
  376:         [item setContentNode: aContent];
  377:         [gDictionary setObject: item forKey: [NSNumber numberWithInt: contentID]];
  378:     }
  379:     return item;
  380: }
  381: 
  382: void
  383: BookmarksService::NotifyObservers(nsIContent* aContainer, PRBool aReloadChildren)
  384: {
  385:     if (!gInstances)
  386:         return;
  387:     
  388:     PRInt32 count = gInstances->Count();
  389:     for (PRInt32 i = 0; i < count; i++) {
  390:         BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
  391:         instance->NotifyObserver(aContainer, aReloadChildren);
  392:     }
  393:     
  394:     FlushBookmarks();
  395: }
  396: 
  397: 
  398: void
  399: BookmarksService::NotifyObserver(nsIContent* aContainer, PRBool aReloadChildren)
  400: {
  401:     if (!gDictionary)
  402:         return;
  403:    
  404:     nsCOMPtr<nsIContent> parent;
  405:     aContainer->GetParent(*getter_AddRefs(parent));
  406:     
  407:     BookmarkItem* item = nil;
  408:     if (parent)
  409:         // We're not the root.
  410:         item = GetWrapperFor(aContainer);
  411:     
  412:     [mDataSource reloadDataForItem: item reloadChildren: aReloadChildren];
  413: }
  414: 
  415: void
  416: BookmarksService::AddObserver()
  417: {
  418:     gRefCnt++;
  419:     if (gRefCnt == 1) {
  420:         gBookmarkAtom = NS_NewAtom("bookmark");
  421:         gFolderAtom = NS_NewAtom("folder");
  422:         gNameAtom = NS_NewAtom("name");
  423:         gHrefAtom = NS_NewAtom("href");
  424:         gInstances = new nsVoidArray();
  425:                 
  426:         nsCOMPtr<nsIFile> profileDir;
  427:         NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profileDir));
  428:         profileDir->Append("bookmarks.xml");
  429:     
  430:         nsXPIDLCString bookmarksFileURL;
  431:         NS_GetURLSpecFromFile(profileDir, getter_Copies(bookmarksFileURL));
  432:         
  433:         nsCOMPtr<nsIURI> uri;
  434:         NS_NewURI(getter_AddRefs(uri), bookmarksFileURL.get());
  435:     
  436:         nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));    
  437:         xblService->FetchSyncXMLDocument(uri, &gBookmarks); // The addref is here.
  438:         
  439:         nsCOMPtr<nsIContent> rootNode;
  440:         GetRootContent(getter_AddRefs(rootNode));
  441:         StripWhitespaceNodes(rootNode);
  442:     }
  443:     
  444:     gInstances->AppendElement(this);
  445: }
  446: 
  447: void
  448: BookmarksService::RemoveObserver()
  449: {
  450:     if (gRefCnt == 0)
  451:         return;
  452:  
  453:     gInstances->RemoveElement(this);
  454:      
  455:     gRefCnt--;
  456:     if (gRefCnt == 0) {
  457:         NS_IF_RELEASE(gBookmarks);
  458:         NS_RELEASE(gBookmarkAtom);
  459:         NS_RELEASE(gFolderAtom);
  460:         NS_RELEASE(gNameAtom);
  461:         NS_RELEASE(gHrefAtom);
  462:         [gDictionary release];
  463:     }
  464: }
  465: 
  466: void
  467: BookmarksService::FlushBookmarks()
  468: {
  469:     nsCOMPtr<nsIFile> bookmarksFile;
  470:     NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(bookmarksFile));
  471:     bookmarksFile->Append("bookmarks.xml");
  472: 
  473:     nsCOMPtr<nsIOutputStream> outputStream;
  474:     NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), bookmarksFile);
  475: 
  476:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  477:     
  478:     nsCOMPtr<nsIDOMSerializer> domSerializer(do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID));
  479:     domSerializer->SerializeToStream(domDoc, outputStream, nsnull);
  480: }
  481: 
  482: void
  483: BookmarksService::ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent)
  484: {
  485:     nsCOMPtr<nsIContent> content = aContent;
  486:     if (!content) {
  487:         GetRootContent(getter_AddRefs(content));
  488:         GetWrapperFor(content);
  489:     }
  490:     
  491:     // Now walk our children, and for folders also recur into them.
  492:     PRInt32 childCount;
  493:     content->ChildCount(childCount);
  494:     
  495:     for (PRInt32 i = 0; i < childCount; i++) {
  496:         nsCOMPtr<nsIContent> child;
  497:         content->ChildAt(i, *getter_AddRefs(child));
  498:         
  499:         // Obtain our name attribute.
  500:         nsAutoString name;
  501:         child->GetAttr(kNameSpaceID_None, gNameAtom, name);
  502:         nsCAutoString nameCStr; nameCStr.AssignWithConversion(name);
  503:         NSString* title = [NSString stringWithCString: nameCStr.get()];
  504:                 
  505:         // Create a menu or menu item for the child.
  506:         NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
  507:         GetWrapperFor(child);
  508:         [aMenu addItem: menuItem];
  509:         
  510:         nsCOMPtr<nsIAtom> tag;
  511:         child->GetTag(*getter_AddRefs(tag));
  512:         
  513:         if (tag == gFolderAtom) {
  514:             NSMenu* menu = [[[NSMenu alloc] initWithTitle: title] autorelease];
  515:             [aMenu setSubmenu: menu forItem: menuItem];
  516:             [menu setAutoenablesItems: NO];
  517:             ConstructBookmarksMenu(menu, child);
  518:         }
  519:         else {
  520:             [menuItem setTarget: gMainController];
  521:             [menuItem setAction: @selector(openMenuBookmark:)];
  522:         }
  523:         
  524:         PRUint32 contentID;
  525:         child->GetContentID(&contentID);
  526:         [menuItem setTag: contentID];
  527:     }
  528: }
  529: 
  530: void 
  531: BookmarksService::OpenMenuBookmark(BrowserWindowController* aController, id aMenuItem)
  532: {
  533:     // Get the corresponding bookmark item.
  534:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: [aMenuItem tag]]];
  535:         
  536:     // Get the content node.
  537:     nsIContent* content = [item contentNode];
  538:         
  539:     // Get the href attribute.  This is the URL we want to load.
  540:     nsAutoString href;
  541:     content->GetAttr(kNameSpaceID_None, gHrefAtom, href);
  542:     nsCAutoString cref; cref.AssignWithConversion(href);
  543:     if (cref.IsEmpty())
  544:         return;
  545:         
  546:     NSString* url = [NSString stringWithCString: cref.get()];
  547:     
  548:     // Now load the URL in the window.
  549:     [aController loadURL:[NSURL URLWithString: url]];
  550: }

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