File:  [mozdev] / chimera / BookmarksService.mm
Revision 1.7: download - view: text, annotated - select for diffs - revision graph
Sat Feb 9 23:17:02 2002 UTC (17 years, 1 month ago) by hyatt
Branches: MAIN
CVS tags: HEAD
Rearranging the menus and making bookmarks show up in the menu.

    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: - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
  176: {
  177:     if (!mBookmarks)
  178:         return nil;
  179:        
  180:     nsCOMPtr<nsIContent> content;
  181:     if (!item)
  182:         mBookmarks->GetRootContent(getter_AddRefs(content));
  183:     else
  184:         content = [item contentNode];
  185:     
  186:     nsCOMPtr<nsIContent> child;
  187:     content->ChildAt(index, *getter_AddRefs(child));
  188:     return mBookmarks->GetWrapperFor(child);
  189: }
  190: 
  191: - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
  192: {
  193:     if (!mBookmarks)
  194:         return NO;
  195:     
  196:     if (!item)
  197:         return YES; // The root node is always open.
  198:     
  199:     nsCOMPtr<nsIAtom> tagName;
  200:     nsIContent* content = [item contentNode];
  201:     content->GetTag(*getter_AddRefs(tagName));
  202:     
  203:     return (tagName == BookmarksService::gFolderAtom);
  204: }
  205: 
  206: - (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
  207: {
  208:     if (!mBookmarks)
  209:         return 0;
  210:   
  211:     nsCOMPtr<nsIContent> content;
  212:     if (!item)
  213:         mBookmarks->GetRootContent(getter_AddRefs(content));
  214:     else 
  215:         content = [item contentNode];
  216:     
  217:     PRInt32 childCount;
  218:     content->ChildCount(childCount);
  219:     
  220:     return childCount;
  221: }
  222: 
  223: - (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  224: {
  225:     if (!item)
  226:         return nil;
  227:     
  228:     NSString* columnName = [tableColumn identifier];
  229:       
  230:     if ([columnName isEqualToString: @"name"]) {
  231:         nsIContent* content = [item contentNode];
  232:         nsAutoString nameAttr;
  233:         content->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr);
  234:         nsCAutoString cStr; cStr.AssignWithConversion(nameAttr);
  235:         return [NSString stringWithCString: cStr.get()];
  236:     }
  237:     
  238:     return nil;
  239: }
  240: 
  241: - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  242: {
  243: }
  244: 
  245: - (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren
  246: {
  247:     printf("Reloading?\n");
  248:     if (!item)
  249:         [mOutlineView reloadData];
  250:     else if ([mOutlineView isItemExpanded: item])
  251:         [mOutlineView reloadItem: item reloadChildren: aReloadChildren];
  252: }
  253: 
  254: @end
  255: 
  256: @implementation BookmarkItem
  257: -(nsIContent*)contentNode
  258: {
  259:     return mContentNode;
  260: }
  261: 
  262: -(void)setContentNode: (nsIContent*)aContentNode
  263: {
  264:     mContentNode = aContentNode;
  265: }
  266: 
  267: - (id)copyWithZone:(NSZone *)aZone
  268: {
  269:     BookmarkItem* copy = [[[self class] allocWithZone: aZone] init];
  270:     [copy setContentNode: mContentNode];
  271:     return copy;
  272: }
  273: 
  274: @end
  275: 
  276: // Helper for stripping whitespace
  277: static void
  278: StripWhitespaceNodes(nsIContent* aElement)
  279: {
  280:     PRInt32 childCount;
  281:     aElement->ChildCount(childCount);
  282:     for (PRInt32 i = 0; i < childCount; i++) {
  283:         nsCOMPtr<nsIContent> child;
  284:         aElement->ChildAt(i, *getter_AddRefs(child));
  285:         nsCOMPtr<nsITextContent> text = do_QueryInterface(child);
  286:         if (text) {
  287:             PRBool isEmpty;
  288:             text->IsOnlyWhitespace(&isEmpty);
  289:             if (isEmpty) {
  290:                 // This node contained nothing but whitespace.
  291:                 // Remove it from the content model.
  292:                 aElement->RemoveChildAt(i, PR_TRUE);
  293:                 i--; // Decrement our count, since we just removed this child.
  294:                 childCount--; // Also decrement our total count.
  295:             }
  296:         }
  297:         else StripWhitespaceNodes(child);
  298:     }
  299: }
  300: 
  301: PRUint32 BookmarksService::gRefCnt = 0;
  302: nsIDocument* BookmarksService::gBookmarks = nsnull;
  303: NSMutableDictionary* BookmarksService::gDictionary = nil;
  304: NSMutableDictionary* BookmarksService::gBookmarkToMenuMap = nil;
  305: NSMutableDictionary* BookmarksService::gMenuToBookmarkMap = nil;
  306: nsIAtom* BookmarksService::gFolderAtom = nsnull;
  307: nsIAtom* BookmarksService::gBookmarkAtom = nsnull;
  308: nsIAtom* BookmarksService::gHrefAtom = nsnull;
  309: nsIAtom* BookmarksService::gNameAtom = nsnull;
  310: nsVoidArray* BookmarksService::gInstances = nsnull;
  311: 
  312: BookmarksService::BookmarksService(BookmarksDataSource* aDataSource)
  313: {
  314:     mDataSource = aDataSource;
  315: }
  316: 
  317: BookmarksService::~BookmarksService()
  318: {
  319: }
  320: 
  321: void
  322: BookmarksService::GetRootContent(nsIContent** aResult)
  323: {
  324:     *aResult = nsnull;
  325:     if (gBookmarks) {
  326:         nsCOMPtr<nsIDOMElement> elt;
  327:         nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  328:         domDoc->GetDocumentElement(getter_AddRefs(elt));
  329:         elt->QueryInterface(NS_GET_IID(nsIContent), (void**)aResult); // Addref happens here.
  330:     }
  331: }
  332: 
  333: BookmarkItem*
  334: BookmarksService::GetWrapperFor(nsIContent* aContent)
  335: {
  336:     if (!gDictionary)
  337:         gDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
  338:     
  339:     PRUint32 contentID;
  340:     aContent->GetContentID(&contentID);
  341:     
  342:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: contentID]];
  343:     if (item)
  344:         return item;
  345:     else {
  346:         // Create an item.
  347:         item = [[[BookmarkItem alloc] init] autorelease]; // The dictionary retains us.
  348:         [item setContentNode: aContent];
  349:         [gDictionary setObject: item forKey: [NSNumber numberWithInt: contentID]];
  350:     }
  351:     return item;
  352: }
  353: 
  354: void
  355: BookmarksService::NotifyObservers(nsIContent* aContainer, PRBool aReloadChildren)
  356: {
  357:     if (!gInstances)
  358:         return;
  359:     
  360:     PRInt32 count = gInstances->Count();
  361:     for (PRInt32 i = 0; i < count; i++) {
  362:         BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
  363:         instance->NotifyObserver(aContainer, aReloadChildren);
  364:     }
  365:     
  366:     FlushBookmarks();
  367: }
  368: 
  369: 
  370: void
  371: BookmarksService::NotifyObserver(nsIContent* aContainer, PRBool aReloadChildren)
  372: {
  373:     if (!gDictionary)
  374:         return;
  375:    
  376:     nsCOMPtr<nsIContent> parent;
  377:     aContainer->GetParent(*getter_AddRefs(parent));
  378:     
  379:     BookmarkItem* item = nil;
  380:     if (parent)
  381:         // We're not the root.
  382:         item = GetWrapperFor(aContainer);
  383:     
  384:     [mDataSource reloadDataForItem: item reloadChildren: aReloadChildren];
  385: }
  386: 
  387: void
  388: BookmarksService::AddObserver()
  389: {
  390:     gRefCnt++;
  391:     if (gRefCnt == 1) {
  392:         gBookmarkAtom = NS_NewAtom("bookmark");
  393:         gFolderAtom = NS_NewAtom("folder");
  394:         gNameAtom = NS_NewAtom("name");
  395:         gHrefAtom = NS_NewAtom("href");
  396:         gInstances = new nsVoidArray();
  397:         
  398:         nsCOMPtr<nsIFile> profileDir;
  399:         NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profileDir));
  400:         profileDir->Append("bookmarks.xml");
  401:     
  402:         nsXPIDLCString bookmarksFileURL;
  403:         NS_GetURLSpecFromFile(profileDir, getter_Copies(bookmarksFileURL));
  404:         
  405:         nsCOMPtr<nsIURI> uri;
  406:         NS_NewURI(getter_AddRefs(uri), bookmarksFileURL.get());
  407:     
  408:         nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));    
  409:         xblService->FetchSyncXMLDocument(uri, &gBookmarks); // The addref is here.
  410:         
  411:         nsCOMPtr<nsIContent> rootNode;
  412:         GetRootContent(getter_AddRefs(rootNode));
  413:         StripWhitespaceNodes(rootNode);
  414:     }
  415:     
  416:     gInstances->AppendElement(this);
  417: }
  418: 
  419: void
  420: BookmarksService::RemoveObserver()
  421: {
  422:     if (gRefCnt == 0)
  423:         return;
  424:  
  425:     gInstances->RemoveElement(this);
  426:      
  427:     gRefCnt--;
  428:     if (gRefCnt == 0) {
  429:         NS_IF_RELEASE(gBookmarks);
  430:         NS_RELEASE(gBookmarkAtom);
  431:         NS_RELEASE(gFolderAtom);
  432:         NS_RELEASE(gNameAtom);
  433:         NS_RELEASE(gHrefAtom);
  434:         [gDictionary release];
  435:         [gBookmarkToMenuMap release];
  436:         [gMenuToBookmarkMap release];
  437:     }
  438: }
  439: 
  440: void
  441: BookmarksService::FlushBookmarks()
  442: {
  443:     nsCOMPtr<nsIFile> bookmarksFile;
  444:     NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(bookmarksFile));
  445:     bookmarksFile->Append("bookmarks.xml");
  446: 
  447:     nsCOMPtr<nsIOutputStream> outputStream;
  448:     NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), bookmarksFile);
  449: 
  450:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  451:     
  452:     nsCOMPtr<nsIDOMSerializer> domSerializer(do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID));
  453:     domSerializer->SerializeToStream(domDoc, outputStream, nsnull);
  454: }
  455: 
  456: void
  457: BookmarksService::ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent)
  458: {
  459:     // Create our menu maps.
  460:     if (!gMenuToBookmarkMap)
  461:         gMenuToBookmarkMap = [[NSMutableDictionary alloc] initWithCapacity: 30];
  462:     if (!gBookmarkToMenuMap)
  463:         gBookmarkToMenuMap = [[NSMutableDictionary alloc] initWithCapacity: 30];
  464:     
  465:     nsCOMPtr<nsIContent> content = aContent;
  466:     if (!content) {
  467:         GetRootContent(getter_AddRefs(content));
  468:         // Add the root entry to our maps.
  469:         BookmarkItem* item = GetWrapperFor(content);
  470:         [gMenuToBookmarkMap setObject: item forKey: aMenu];
  471:         [gBookmarkToMenuMap setObject: aMenu forKey: item];
  472:     }
  473:     
  474:     // Now walk our children, and for folders also recur into them.
  475:     PRInt32 childCount;
  476:     content->ChildCount(childCount);
  477:     
  478:     for (PRInt32 i = 0; i < childCount; i++) {
  479:         nsCOMPtr<nsIContent> child;
  480:         content->ChildAt(i, *getter_AddRefs(child));
  481:         
  482:         // Obtain our name attribute.
  483:         nsAutoString name;
  484:         child->GetAttr(kNameSpaceID_None, gNameAtom, name);
  485:         nsCAutoString nameCStr; nameCStr.AssignWithConversion(name);
  486:         NSString* title = [NSString stringWithCString: nameCStr.get()];
  487:                 
  488:         // Create a menu or menu item for the child.
  489:         nsCOMPtr<nsIAtom> tag;
  490:         content->GetTag(*getter_AddRefs(tag));
  491:         if (tag == gFolderAtom) {
  492:             // We are building a menu.
  493:             NSMenu* menu = [[[NSMenu alloc] initWithTitle: title] autorelease];
  494:             BookmarkItem* item = GetWrapperFor(child);
  495:             [gMenuToBookmarkMap setObject: item forKey: menu];
  496:             [gBookmarkToMenuMap setObject: menu forKey: item];
  497:             
  498:             [aMenu addItem: menu];
  499:                         
  500:             ConstructBookmarksMenu(menu, child);
  501:         }
  502:         else {
  503:             // We are building a menu item.
  504:             NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
  505:             BookmarkItem* item = GetWrapperFor(child);
  506:             [gMenuToBookmarkMap setObject: item forKey: menuItem];
  507:             [gBookmarkToMenuMap setObject: menuItem forKey: item];
  508:             
  509:             [aMenu addItem: menuItem];
  510:         }
  511:     }
  512: }

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