File:  [mozdev] / chimera / BookmarksService.mm
Revision 1.8: download - view: text, annotated - select for diffs - revision graph
Sun Feb 10 00:29:08 2002 UTC (17 years, 5 months ago) by hyatt
Branches: MAIN
CVS tags: HEAD
Bookmarks in the menu bar work!

    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: MainController* BookmarksService::gMainController = nil;
  305: nsIAtom* BookmarksService::gFolderAtom = nsnull;
  306: nsIAtom* BookmarksService::gBookmarkAtom = nsnull;
  307: nsIAtom* BookmarksService::gHrefAtom = nsnull;
  308: nsIAtom* BookmarksService::gNameAtom = nsnull;
  309: nsVoidArray* BookmarksService::gInstances = nsnull;
  310: 
  311: BookmarksService::BookmarksService(BookmarksDataSource* aDataSource)
  312: {
  313:     mDataSource = aDataSource;
  314: }
  315: 
  316: BookmarksService::~BookmarksService()
  317: {
  318: }
  319: 
  320: void
  321: BookmarksService::GetRootContent(nsIContent** aResult)
  322: {
  323:     *aResult = nsnull;
  324:     if (gBookmarks) {
  325:         nsCOMPtr<nsIDOMElement> elt;
  326:         nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  327:         domDoc->GetDocumentElement(getter_AddRefs(elt));
  328:         elt->QueryInterface(NS_GET_IID(nsIContent), (void**)aResult); // Addref happens here.
  329:     }
  330: }
  331: 
  332: BookmarkItem*
  333: BookmarksService::GetWrapperFor(nsIContent* aContent)
  334: {
  335:     if (!gDictionary)
  336:         gDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
  337:     
  338:     PRUint32 contentID;
  339:     aContent->GetContentID(&contentID);
  340:     
  341:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: contentID]];
  342:     if (item)
  343:         return item;
  344:     else {
  345:         // Create an item.
  346:         item = [[[BookmarkItem alloc] init] autorelease]; // The dictionary retains us.
  347:         [item setContentNode: aContent];
  348:         [gDictionary setObject: item forKey: [NSNumber numberWithInt: contentID]];
  349:     }
  350:     return item;
  351: }
  352: 
  353: void
  354: BookmarksService::NotifyObservers(nsIContent* aContainer, PRBool aReloadChildren)
  355: {
  356:     if (!gInstances)
  357:         return;
  358:     
  359:     PRInt32 count = gInstances->Count();
  360:     for (PRInt32 i = 0; i < count; i++) {
  361:         BookmarksService* instance = (BookmarksService*)gInstances->ElementAt(i);
  362:         instance->NotifyObserver(aContainer, aReloadChildren);
  363:     }
  364:     
  365:     FlushBookmarks();
  366: }
  367: 
  368: 
  369: void
  370: BookmarksService::NotifyObserver(nsIContent* aContainer, PRBool aReloadChildren)
  371: {
  372:     if (!gDictionary)
  373:         return;
  374:    
  375:     nsCOMPtr<nsIContent> parent;
  376:     aContainer->GetParent(*getter_AddRefs(parent));
  377:     
  378:     BookmarkItem* item = nil;
  379:     if (parent)
  380:         // We're not the root.
  381:         item = GetWrapperFor(aContainer);
  382:     
  383:     [mDataSource reloadDataForItem: item reloadChildren: aReloadChildren];
  384: }
  385: 
  386: void
  387: BookmarksService::AddObserver()
  388: {
  389:     gRefCnt++;
  390:     if (gRefCnt == 1) {
  391:         gBookmarkAtom = NS_NewAtom("bookmark");
  392:         gFolderAtom = NS_NewAtom("folder");
  393:         gNameAtom = NS_NewAtom("name");
  394:         gHrefAtom = NS_NewAtom("href");
  395:         gInstances = new nsVoidArray();
  396:                 
  397:         nsCOMPtr<nsIFile> profileDir;
  398:         NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(profileDir));
  399:         profileDir->Append("bookmarks.xml");
  400:     
  401:         nsXPIDLCString bookmarksFileURL;
  402:         NS_GetURLSpecFromFile(profileDir, getter_Copies(bookmarksFileURL));
  403:         
  404:         nsCOMPtr<nsIURI> uri;
  405:         NS_NewURI(getter_AddRefs(uri), bookmarksFileURL.get());
  406:     
  407:         nsCOMPtr<nsIXBLService> xblService(do_GetService("@mozilla.org/xbl;1"));    
  408:         xblService->FetchSyncXMLDocument(uri, &gBookmarks); // The addref is here.
  409:         
  410:         nsCOMPtr<nsIContent> rootNode;
  411:         GetRootContent(getter_AddRefs(rootNode));
  412:         StripWhitespaceNodes(rootNode);
  413:     }
  414:     
  415:     gInstances->AppendElement(this);
  416: }
  417: 
  418: void
  419: BookmarksService::RemoveObserver()
  420: {
  421:     if (gRefCnt == 0)
  422:         return;
  423:  
  424:     gInstances->RemoveElement(this);
  425:      
  426:     gRefCnt--;
  427:     if (gRefCnt == 0) {
  428:         NS_IF_RELEASE(gBookmarks);
  429:         NS_RELEASE(gBookmarkAtom);
  430:         NS_RELEASE(gFolderAtom);
  431:         NS_RELEASE(gNameAtom);
  432:         NS_RELEASE(gHrefAtom);
  433:         [gDictionary release];
  434:     }
  435: }
  436: 
  437: void
  438: BookmarksService::FlushBookmarks()
  439: {
  440:     nsCOMPtr<nsIFile> bookmarksFile;
  441:     NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(bookmarksFile));
  442:     bookmarksFile->Append("bookmarks.xml");
  443: 
  444:     nsCOMPtr<nsIOutputStream> outputStream;
  445:     NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), bookmarksFile);
  446: 
  447:     nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(gBookmarks));
  448:     
  449:     nsCOMPtr<nsIDOMSerializer> domSerializer(do_CreateInstance(NS_XMLSERIALIZER_CONTRACTID));
  450:     domSerializer->SerializeToStream(domDoc, outputStream, nsnull);
  451: }
  452: 
  453: void
  454: BookmarksService::ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent)
  455: {
  456:     nsCOMPtr<nsIContent> content = aContent;
  457:     if (!content) {
  458:         GetRootContent(getter_AddRefs(content));
  459:         GetWrapperFor(content);
  460:     }
  461:     
  462:     // Now walk our children, and for folders also recur into them.
  463:     PRInt32 childCount;
  464:     content->ChildCount(childCount);
  465:     
  466:     for (PRInt32 i = 0; i < childCount; i++) {
  467:         nsCOMPtr<nsIContent> child;
  468:         content->ChildAt(i, *getter_AddRefs(child));
  469:         
  470:         // Obtain our name attribute.
  471:         nsAutoString name;
  472:         child->GetAttr(kNameSpaceID_None, gNameAtom, name);
  473:         nsCAutoString nameCStr; nameCStr.AssignWithConversion(name);
  474:         NSString* title = [NSString stringWithCString: nameCStr.get()];
  475:                 
  476:         // Create a menu or menu item for the child.
  477:         NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
  478:         GetWrapperFor(child);
  479:         [aMenu addItem: menuItem];
  480:         
  481:         nsCOMPtr<nsIAtom> tag;
  482:         child->GetTag(*getter_AddRefs(tag));
  483:         
  484:         if (tag == gFolderAtom) {
  485:             NSMenu* menu = [[[NSMenu alloc] initWithTitle: title] autorelease];
  486:             [aMenu setSubmenu: menu forItem: menuItem];
  487:             [menu setAutoenablesItems: NO];
  488:             ConstructBookmarksMenu(menu, child);
  489:         }
  490:         else {
  491:             [menuItem setTarget: gMainController];
  492:             [menuItem setAction: @selector(openMenuBookmark:)];
  493:         }
  494:         
  495:         PRUint32 contentID;
  496:         child->GetContentID(&contentID);
  497:         [menuItem setTag: contentID];
  498:     }
  499: }
  500: 
  501: void 
  502: BookmarksService::OpenMenuBookmark(BrowserWindowController* aController, id aMenuItem)
  503: {
  504:     // Get the corresponding bookmark item.
  505:     BookmarkItem* item = [gDictionary objectForKey: [NSNumber numberWithInt: [aMenuItem tag]]];
  506:         
  507:     // Get the content node.
  508:     nsIContent* content = [item contentNode];
  509:         
  510:     // Get the href attribute.  This is the URL we want to load.
  511:     nsAutoString href;
  512:     content->GetAttr(kNameSpaceID_None, gHrefAtom, href);
  513:     nsCAutoString cref; cref.AssignWithConversion(href);
  514:     if (cref.IsEmpty())
  515:         return;
  516:         
  517:     NSString* url = [NSString stringWithCString: cref.get()];
  518:     
  519:     // Now load the URL in the window.
  520:     [aController loadURL:[NSURL URLWithString: url]];
  521: }

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