File:  [mozdev] / chimera / BookmarksService.mm
Revision 1.11: download - view: text, annotated - select for diffs - revision graph
Mon Feb 11 10:23:03 2002 UTC (17 years, 3 months ago) by macserv
Branches: MAIN
CVS tags: HEAD
Adding icons to the outlineView.  Totally wierd approach, but works great!  Will explain tomorrow.

    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:         NSLog(@"%@", item);
  237:         if ([columnName isEqualToString: @"name"]) {
  238:             nsIContent* content = [item contentNode];
  239:             nsAutoString nameAttr;
  240:             content->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr);
  241:             nsCAutoString cStr; cStr.AssignWithConversion(nameAttr);
  242:             
  243:         //set cell's textual contents
  244:             [cellValue replaceCharactersInRange:NSMakeRange(0, [cellValue length])
  245:                                      withString:[NSString stringWithCString: cStr.get()]];
  246:             
  247:         //Add image to cell's text in front of the text.
  248:             NSFileWrapper *wrapper = [[NSFileWrapper alloc] initRegularFileWithContents:nil];
  249:             NSTextAttachment *attachment = [[NSTextAttachment allocWithZone:NULL] initWithFileWrapper:wrapper];
  250:             attachmentAttrString = [[NSMutableAttributedString attributedStringWithAttachment:attachment] retain];
  251:             [attachment release];
  252:             [wrapper release];
  253: 
  254:             attachmentCell = (NSCell *)[(NSTextAttachment *)[attachmentAttrString attribute:NSAttachmentAttributeName
  255:                                                                                     atIndex:0
  256:                                                                              effectiveRange:NULL] attachmentCell];
  257: 
  258:             [attachmentCell setImage:[NSImage imageNamed:@"folder"]];
  259:             [cellValue replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attachmentAttrString];
  260:             [cellValue addAttribute:NSBaselineOffsetAttributeName
  261:                               value:[NSNumber numberWithFloat:-3.0]
  262:                               range:NSMakeRange(0, 1)];
  263:         //Done adding image. 
  264:         }
  265:         return cellValue;
  266:     } else {
  267:         return nil;
  268:     }
  269: }
  270: 
  271: - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  272: {
  273: }
  274: 
  275: - (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren
  276: {
  277:     printf("Reloading?\n");
  278:     if (!item)
  279:         [mOutlineView reloadData];
  280:     else if ([mOutlineView isItemExpanded: item])
  281:         [mOutlineView reloadItem: item reloadChildren: aReloadChildren];
  282: }
  283: 
  284: @end
  285: 
  286: @implementation BookmarkItem
  287: -(nsIContent*)contentNode
  288: {
  289:     return mContentNode;
  290: }
  291: 
  292: -(void)setContentNode: (nsIContent*)aContentNode
  293: {
  294:     mContentNode = aContentNode;
  295: }
  296: 
  297: - (id)copyWithZone:(NSZone *)aZone
  298: {
  299:     BookmarkItem* copy = [[[self class] allocWithZone: aZone] init];
  300:     [copy setContentNode: mContentNode];
  301:     return copy;
  302: }
  303: 
  304: @end
  305: 
  306: // Helper for stripping whitespace
  307: static void
  308: StripWhitespaceNodes(nsIContent* aElement)
  309: {
  310:     PRInt32 childCount;
  311:     aElement->ChildCount(childCount);
  312:     for (PRInt32 i = 0; i < childCount; i++) {
  313:         nsCOMPtr<nsIContent> child;
  314:         aElement->ChildAt(i, *getter_AddRefs(child));
  315:         nsCOMPtr<nsITextContent> text = do_QueryInterface(child);
  316:         if (text) {
  317:             PRBool isEmpty;
  318:             text->IsOnlyWhitespace(&isEmpty);
  319:             if (isEmpty) {
  320:                 // This node contained nothing but whitespace.
  321:                 // Remove it from the content model.
  322:                 aElement->RemoveChildAt(i, PR_TRUE);
  323:                 i--; // Decrement our count, since we just removed this child.
  324:                 childCount--; // Also decrement our total count.
  325:             }
  326:         }
  327:         else StripWhitespaceNodes(child);
  328:     }
  329: }
  330: 
  331: PRUint32 BookmarksService::gRefCnt = 0;
  332: nsIDocument* BookmarksService::gBookmarks = nsnull;
  333: NSMutableDictionary* BookmarksService::gDictionary = nil;
  334: MainController* BookmarksService::gMainController = nil;
  335: nsIAtom* BookmarksService::gFolderAtom = nsnull;
  336: nsIAtom* BookmarksService::gBookmarkAtom = nsnull;
  337: nsIAtom* BookmarksService::gHrefAtom = nsnull;
  338: nsIAtom* BookmarksService::gNameAtom = nsnull;
  339: nsVoidArray* BookmarksService::gInstances = nsnull;
  340: 
  341: BookmarksService::BookmarksService(BookmarksDataSource* aDataSource)
  342: {
  343:     mDataSource = aDataSource;
  344: }
  345: 
  346: BookmarksService::~BookmarksService()
  347: {
  348: }
  349: 
  350: void
  351: BookmarksService::GetRootContent(nsIContent** aResult)
  352: {
  353:     *aResult = nsnull;
  354:     if (gBookmarks) {
  355:         nsCOMPtr<nsIDOMElement> elt;
  356:         nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  357:         domDoc->GetDocumentElement(getter_AddRefs(elt));
  358:         elt->QueryInterface(NS_GET_IID(nsIContent), (void**)aResult); // Addref happens here.
  359:     }
  360: }
  361: 
  362: BookmarkItem*
  363: BookmarksService::GetWrapperFor(nsIContent* aContent)
  364: {
  365:     if (!gDictionary)
  366:         gDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
  367:     
  368:     PRUint32 contentID;
  369:     aContent->GetContentID(&contentID);
  370:     
  371:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: contentID]];
  372:     if (item)
  373:         return item;
  374:     else {
  375:         // Create an item.
  376:         item = [[[BookmarkItem alloc] init] autorelease]; // The dictionary retains us.
  377:         [item setContentNode: aContent];
  378:         [gDictionary setObject: item forKey: [NSNumber numberWithInt: contentID]];
  379:     }
  380:     return item;
  381: }
  382: 
  383: void
  384: BookmarksService::NotifyObservers(nsIContent* aContainer, PRBool aReloadChildren)
  385: {
  386:     if (!gInstances)
  387:         return;
  388:     
  389:     PRInt32 count = gInstances->Count();
  390:     for (PRInt32 i = 0; i < count; i++) {
  391:         BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
  392:         instance->NotifyObserver(aContainer, aReloadChildren);
  393:     }
  394:     
  395:     FlushBookmarks();
  396: }
  397: 
  398: 
  399: void
  400: BookmarksService::NotifyObserver(nsIContent* aContainer, PRBool aReloadChildren)
  401: {
  402:     if (!gDictionary)
  403:         return;
  404:    
  405:     nsCOMPtr<nsIContent> parent;
  406:     aContainer->GetParent(*getter_AddRefs(parent));
  407:     
  408:     BookmarkItem* item = nil;
  409:     if (parent)
  410:         // We're not the root.
  411:         item = GetWrapperFor(aContainer);
  412:     
  413:     [mDataSource reloadDataForItem: item reloadChildren: aReloadChildren];
  414: }
  415: 
  416: void
  417: BookmarksService::AddObserver()
  418: {
  419:     gRefCnt++;
  420:     if (gRefCnt == 1) {
  421:         gBookmarkAtom = NS_NewAtom("bookmark");
  422:         gFolderAtom = NS_NewAtom("folder");
  423:         gNameAtom = NS_NewAtom("name");
  424:         gHrefAtom = NS_NewAtom("href");
  425:         gInstances = new nsVoidArray();
  426:                 
  427:         nsCOMPtr<nsIFile> profileDir;
  428:         NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profileDir));
  429:         profileDir->Append("bookmarks.xml");
  430:     
  431:         nsXPIDLCString bookmarksFileURL;
  432:         NS_GetURLSpecFromFile(profileDir, getter_Copies(bookmarksFileURL));
  433:         
  434:         nsCOMPtr<nsIURI> uri;
  435:         NS_NewURI(getter_AddRefs(uri), bookmarksFileURL.get());
  436:     
  437:         nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));    
  438:         xblService->FetchSyncXMLDocument(uri, &gBookmarks); // The addref is here.
  439:         
  440:         nsCOMPtr<nsIContent> rootNode;
  441:         GetRootContent(getter_AddRefs(rootNode));
  442:         StripWhitespaceNodes(rootNode);
  443:     }
  444:     
  445:     gInstances->AppendElement(this);
  446: }
  447: 
  448: void
  449: BookmarksService::RemoveObserver()
  450: {
  451:     if (gRefCnt == 0)
  452:         return;
  453:  
  454:     gInstances->RemoveElement(this);
  455:      
  456:     gRefCnt--;
  457:     if (gRefCnt == 0) {
  458:         NS_IF_RELEASE(gBookmarks);
  459:         NS_RELEASE(gBookmarkAtom);
  460:         NS_RELEASE(gFolderAtom);
  461:         NS_RELEASE(gNameAtom);
  462:         NS_RELEASE(gHrefAtom);
  463:         [gDictionary release];
  464:     }
  465: }
  466: 
  467: void
  468: BookmarksService::FlushBookmarks()
  469: {
  470:     nsCOMPtr<nsIFile> bookmarksFile;
  471:     NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(bookmarksFile));
  472:     bookmarksFile->Append("bookmarks.xml");
  473: 
  474:     nsCOMPtr<nsIOutputStream> outputStream;
  475:     NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), bookmarksFile);
  476: 
  477:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  478:     
  479:     nsCOMPtr<nsIDOMSerializer> domSerializer(do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID));
  480:     domSerializer->SerializeToStream(domDoc, outputStream, nsnull);
  481: }
  482: 
  483: void
  484: BookmarksService::ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent)
  485: {
  486:     nsCOMPtr<nsIContent> content = aContent;
  487:     if (!content) {
  488:         GetRootContent(getter_AddRefs(content));
  489:         GetWrapperFor(content);
  490:     }
  491:     
  492:     // Now walk our children, and for folders also recur into them.
  493:     PRInt32 childCount;
  494:     content->ChildCount(childCount);
  495:     
  496:     for (PRInt32 i = 0; i < childCount; i++) {
  497:         nsCOMPtr<nsIContent> child;
  498:         content->ChildAt(i, *getter_AddRefs(child));
  499:         
  500:         // Obtain our name attribute.
  501:         nsAutoString name;
  502:         child->GetAttr(kNameSpaceID_None, gNameAtom, name);
  503:         nsCAutoString nameCStr; nameCStr.AssignWithConversion(name);
  504:         NSString* title = [NSString stringWithCString: nameCStr.get()];
  505:                 
  506:         // Create a menu or menu item for the child.
  507:         NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
  508:         GetWrapperFor(child);
  509:         [aMenu addItem: menuItem];
  510:         
  511:         nsCOMPtr<nsIAtom> tag;
  512:         child->GetTag(*getter_AddRefs(tag));
  513:         
  514:         if (tag == gFolderAtom) {
  515:             NSMenu* menu = [[[NSMenu alloc] initWithTitle: title] autorelease];
  516:             [aMenu setSubmenu: menu forItem: menuItem];
  517:             [menu setAutoenablesItems: NO];
  518:             ConstructBookmarksMenu(menu, child);
  519:         }
  520:         else {
  521:             [menuItem setTarget: gMainController];
  522:             [menuItem setAction: @selector(openMenuBookmark:)];
  523:         }
  524:         
  525:         PRUint32 contentID;
  526:         child->GetContentID(&contentID);
  527:         [menuItem setTag: contentID];
  528:     }
  529: }
  530: 
  531: void 
  532: BookmarksService::OpenMenuBookmark(BrowserWindowController* aController, id aMenuItem)
  533: {
  534:     // Get the corresponding bookmark item.
  535:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: [aMenuItem tag]]];
  536:         
  537:     // Get the content node.
  538:     nsIContent* content = [item contentNode];
  539:         
  540:     // Get the href attribute.  This is the URL we want to load.
  541:     nsAutoString href;
  542:     content->GetAttr(kNameSpaceID_None, gHrefAtom, href);
  543:     nsCAutoString cref; cref.AssignWithConversion(href);
  544:     if (cref.IsEmpty())
  545:         return;
  546:         
  547:     NSString* url = [NSString stringWithCString: cref.get()];
  548:     
  549:     // Now load the URL in the window.
  550:     [aController loadURL:[NSURL URLWithString: url]];
  551: }

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