File:  [mozdev] / chimera / BookmarksService.mm
Revision 1.10: download - view: text, annotated - select for diffs - revision graph
Sun Feb 10 03:51:31 2002 UTC (17 years, 5 months ago) by hyatt
Branches: MAIN
CVS tags: HEAD
Adding a context menu to bookmarks.

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

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