Removing files which have been moved to other locations under mozilla/chimera

This commit is contained in:
sfraser%netscape.com 2002-08-21 22:59:47 +00:00
parent 14ee2d2a80
commit 68dbb3ba37
408 changed files with 0 additions and 43134 deletions

View File

@ -1,17 +0,0 @@
{
IBClasses = (
{
ACTIONS = {showPanel = id; };
CLASS = AboutBox;
LANGUAGE = ObjC;
OUTLETS = {
buildNumberField = NSTextField;
creditsField = NSTextView;
window = NSWindow;
};
SUPERCLASS = NSObject;
},
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBLockedObjects</key>
<array>
<integer>7</integer>
</array>
<key>IBOpenObjects</key>
<array>
<integer>5</integer>
</array>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,74 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
#import "SecurityDialogs.h"
#import "CocoaPromptService.h"
#include "nsIGenericFactory.h"
// {0ffd3880-7a1a-11d6-a384-975d1d5f86fc}
#define NS_BADCERTHANDLER_CID \
{0x0ffd3880, 0x7a1a, 0x11d6,{0xa3, 0x84, 0x97, 0x5d, 0x1d, 0x5f, 0x86, 0xfc}}
#define NS_PROMPTSERVICE_CID \
{0xa2112d6a, 0x0e28, 0x421f, {0xb4, 0x6a, 0x25, 0xc0, 0xb3, 0x8, 0xcb, 0xd0}}
NS_GENERIC_FACTORY_CONSTRUCTOR(SecurityDialogs);
NS_GENERIC_FACTORY_CONSTRUCTOR(CocoaPromptService);
static const nsModuleComponentInfo components[] = {
{
"Bad Cert Handler",
NS_BADCERTHANDLER_CID,
NS_NSSDIALOGS_CONTRACTID,
SecurityDialogsConstructor
},
{
"Prompt Service",
NS_PROMPTSERVICE_CID,
"@mozilla.org/embedcomp/prompt-service;1",
CocoaPromptServiceConstructor
}
};
const nsModuleComponentInfo* GetAppModuleComponentInfo(int* outNumComponents)
{
*outNumComponents = sizeof(components) / sizeof(components[0]);
return components;
}

View File

@ -1,155 +0,0 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001, 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Conrad Carlen <ccarlen@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "AppDirServiceProvider.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsILocalFileMac.h"
#include <Carbon/Carbon.h>
// Defines
#define APP_REGISTRY_NAME NS_LITERAL_CSTRING("Application.regs")
#define PROFILES_ROOT_NAME NS_LITERAL_CSTRING("Profiles")
//*****************************************************************************
// AppDirServiceProvider::Constructor/Destructor
//*****************************************************************************
AppDirServiceProvider::AppDirServiceProvider(const nsACString& productDirName)
{
NS_INIT_ISUPPORTS();
mProductDirName.Assign(productDirName);
}
AppDirServiceProvider::~AppDirServiceProvider()
{
}
//*****************************************************************************
// AppDirServiceProvider::nsISupports
//*****************************************************************************
NS_IMPL_ISUPPORTS1(AppDirServiceProvider, nsIDirectoryServiceProvider)
//*****************************************************************************
// AppDirServiceProvider::nsIDirectoryServiceProvider
//*****************************************************************************
NS_IMETHODIMP
AppDirServiceProvider::GetFile(const char *prop, PRBool *persistant, nsIFile **_retval)
{
nsCOMPtr<nsILocalFile> localFile;
nsresult rv = NS_ERROR_FAILURE;
nsCAutoString strBuf;
*_retval = nsnull;
*persistant = PR_TRUE;
if (strcmp(prop, NS_APP_APPLICATION_REGISTRY_DIR) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
}
else if (strcmp(prop, NS_APP_APPLICATION_REGISTRY_FILE) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_SUCCEEDED(rv))
rv = localFile->AppendNative(APP_REGISTRY_NAME);
}
else if (strcmp(prop, NS_APP_USER_PROFILES_ROOT_DIR) == 0)
{
rv = GetProductDirectory(getter_AddRefs(localFile));
if (NS_FAILED(rv))
return rv;
rv = localFile->AppendNative(PROFILES_ROOT_NAME);
if (NS_FAILED(rv))
return rv;
PRBool exists;
rv = localFile->Exists(&exists);
if (NS_SUCCEEDED(rv) && !exists)
rv = localFile->Create(nsIFile::DIRECTORY_TYPE, 0775);
if (NS_FAILED(rv))
return rv;
}
if (localFile && NS_SUCCEEDED(rv))
return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval);
return rv;
}
//*****************************************************************************
// AppDirServiceProvider::AppDirServiceProvider
//*****************************************************************************
NS_METHOD
AppDirServiceProvider::GetProductDirectory(nsILocalFile **aLocalFile)
{
NS_ENSURE_ARG_POINTER(aLocalFile);
*aLocalFile = nsnull;
nsresult rv;
FSRef foundRef;
OSErr err = ::FSFindFolder(kUserDomain, kApplicationSupportFolderType, kCreateFolder, &foundRef);
if (err != noErr)
return NS_ERROR_FAILURE;
nsCOMPtr<nsILocalFileMac> localDir(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
if (!localDir)
return NS_ERROR_FAILURE;
rv = localDir->InitWithFSRef(&foundRef);
if (NS_FAILED(rv))
return rv;
rv = localDir->AppendNative(mProductDirName);
if (NS_FAILED(rv))
return rv;
PRBool exists;
rv = localDir->Exists(&exists);
if (NS_SUCCEEDED(rv) && !exists)
rv = localDir->Create(nsIFile::DIRECTORY_TYPE, 0775);
if (NS_FAILED(rv))
return rv;
*aLocalFile = localDir;
NS_ADDREF(*aLocalFile);
return rv;
}

View File

@ -1,70 +0,0 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001, 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Conrad Carlen <ccarlen@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __AppDirServiceProvider_h__
#define __AppDirServiceProvider_h__
#include "nsIDirectoryService.h"
#include "nsILocalFile.h"
#include "nsString.h"
class nsIFile;
//*****************************************************************************
// class AppDirServiceProvider
//*****************************************************************************
class AppDirServiceProvider : public nsIDirectoryServiceProvider
{
public:
AppDirServiceProvider(const nsACString& productDirName);
NS_DECL_ISUPPORTS
NS_DECL_NSIDIRECTORYSERVICEPROVIDER
protected:
virtual ~AppDirServiceProvider();
NS_METHOD GetProductDirectory(nsILocalFile **aLocalFile);
NS_METHOD GetDefaultUserProfileRoot(nsILocalFile **aLocalFile);
nsCString mProductDirName;
};
#endif // __AppDirServiceProvider_h__

View File

@ -1,46 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ben Goodger <ben@netscape.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*/
#import <AppKit/AppKit.h>
#import "BookmarksService.h"
@interface BookmarkInfoController : NSWindowController {
IBOutlet NSTextField* mNameField;
IBOutlet NSTextField* mLocationField;
IBOutlet NSTextField* mKeywordField;
IBOutlet NSTextField* mDescriptionField;
IBOutlet NSTextField* mNameLabel;
IBOutlet NSTextField* mLocationLabel;
IBOutlet NSTextField* mKeywordLabel;
IBOutlet NSTextField* mDescriptionLabel;
BookmarkItem* mBookmarkItem;
NSTextView* mFieldEditor;
}
+ (id)sharedBookmarkInfoController;
-(void)setBookmark:(BookmarkItem*)aBookmark;
@end

View File

@ -1,231 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Ben Goodger <ben@netscape.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*/
#import "NSString+Utils.h"
#import "BookmarkInfoController.h"
#import "BookmarksDataSource.h"
#include "nsIContent.h"
#include "nsINamespaceManager.h"
@interface BookmarkInfoController(Private)
- (void)showUIElementPair: (id)aLabel control: (id) aControl;
- (void)hideUIElementPair: (id)aLabel control: (id) aControl;
- (void)commitChanges:(id)sender;
- (void)commitField:(id)textField toProperty:(nsIAtom*)propertyAtom;
@end;
@implementation BookmarkInfoController
/* BookmarkInfoController singelton */
static BookmarkInfoController *sharedBookmarkInfoController = nil;
+ (id)sharedBookmarkInfoController
{
if (!sharedBookmarkInfoController) {
sharedBookmarkInfoController = [[BookmarkInfoController alloc] init];
}
return sharedBookmarkInfoController;
}
-(id) init
{
[super initWithWindowNibName:@"BookmarkInfoPanel"];
//custom field editor lets us undo our changes
mFieldEditor = [[NSTextView alloc] init];
[mFieldEditor setAllowsUndo:YES];
[mFieldEditor setFieldEditor:YES];
return self;
}
-(void)dealloc
{
if (self == sharedBookmarkInfoController)
sharedBookmarkInfoController = nil;
[mFieldEditor release];
[super dealloc];
}
-(void)controlTextDidEndEditing: (NSNotification*) aNotification
{
[self commitChanges:[aNotification object]];
[[mFieldEditor undoManager] removeAllActions];
}
-(void)windowDidBecomeKey:(NSNotification*) aNotification
{
[[self window] makeFirstResponder:mNameField];
}
-(void)windowDidResignKey:(NSNotification*) aNotification
{
[[self window] makeFirstResponder:[self window]];
}
- (void)commitChanges:(id)changedField
{
if (![mBookmarkItem contentNode])
return;
// Name
if (changedField == mNameField)
[self commitField:mNameField toProperty:BookmarksService::gNameAtom];
// Location
if (changedField == mLocationField)
[self commitField:mLocationField toProperty:BookmarksService::gHrefAtom];
// Keyword
if (changedField == mKeywordField)
[self commitField:mKeywordField toProperty:BookmarksService::gKeywordAtom];
// Description
if (changedField == mDescriptionField)
[self commitField:mDescriptionField toProperty:BookmarksService::gDescriptionAtom];
[[mFieldEditor undoManager] removeAllActions];
BookmarksService::BookmarkChanged([mBookmarkItem contentNode], TRUE);
}
- (void)commitField:(id)textField toProperty:(nsIAtom*)propertyAtom
{
unsigned int len;
PRUnichar* buffer;
nsXPIDLString buf;
// we really need a category on NSString for this
len = [[textField stringValue] length];
buffer = new PRUnichar[len + 1];
if (!buffer) return;
[[textField stringValue] getCharacters:buffer];
buffer[len] = (PRUnichar)'\0';
buf.Adopt(buffer);
[mBookmarkItem contentNode]->SetAttr(kNameSpaceID_None, propertyAtom, buf, PR_TRUE);
}
-(void)setBookmark: (BookmarkItem*) aBookmark
{
// See bug 154081 - don't show this window if Bookmark doesn't exist
// after fix - this should never happen unless disaster strikes.
if (![aBookmark contentNode])
return;
nsAutoString group;
[aBookmark contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gGroupAtom, group);
BOOL isGroup = !group.IsEmpty();
BOOL isFolder = !isGroup && [aBookmark isFolder];
// First, Show/Hide the appropriate UI
if (isGroup) {
[self showUIElementPair: mNameLabel control: mNameField];
[mNameField setNextKeyView:mKeywordField];
[self hideUIElementPair: mLocationLabel control: mLocationField];
[self showUIElementPair: mKeywordLabel control: mKeywordField];
[self showUIElementPair: mDescriptionLabel control: mDescriptionField];
}
else if (isFolder) {
[self showUIElementPair: mNameLabel control: mNameField];
[mNameField setNextKeyView:mDescriptionField];
[self hideUIElementPair: mLocationLabel control: mLocationField];
[self hideUIElementPair: mKeywordLabel control: mKeywordField];
[self showUIElementPair: mDescriptionLabel control: mDescriptionField];
}
else {
[self showUIElementPair: mNameLabel control: mNameField];
[mNameField setNextKeyView:mLocationField];
[self showUIElementPair: mLocationLabel control: mLocationField];
[self showUIElementPair: mKeywordLabel control: mKeywordField];
[self showUIElementPair: mDescriptionLabel control: mDescriptionField];
}
// Then, fill with appropriate values from Bookmarks
nsAutoString value;
[aBookmark contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, value);
NSString* bookmarkName = [NSString stringWith_nsAString: value];
[mNameField setStringValue: bookmarkName];
NSString* infoForString = [NSString stringWithFormat:NSLocalizedString(@"BookmarkInfoTitle",@"Info for "), bookmarkName];
[[self window] setTitle: infoForString];
if (!isGroup && !isFolder) {
[aBookmark contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, value);
[mLocationField setStringValue: [NSString stringWith_nsAString: value]];
}
if (!isFolder) {
[aBookmark contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gKeywordAtom, value);
[mKeywordField setStringValue: [NSString stringWith_nsAString: value]];
}
[aBookmark contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gDescriptionAtom, value);
[mDescriptionField setStringValue: [NSString stringWith_nsAString: value]];
mBookmarkItem = aBookmark;
}
-(void)showUIElementPair: (id)aLabel control:(id)aControl
{
if ([aLabel superview] == nil) {
[[[self window] contentView] addSubview: aLabel];
[aLabel autorelease];
}
if ([aControl superview] == nil) {
[[[self window] contentView] addSubview: aControl];
[aControl autorelease];
}
}
-(void)hideUIElementPair: (id)aLabel control:(id)aControl
{
if ([aLabel superview] != nil) {
[aLabel removeFromSuperview];
[aLabel retain];
}
if ([aControl superview] != nil) {
[aControl removeFromSuperview];
[aControl retain];
}
}
-(NSText *)windowWillReturnFieldEditor:(NSWindow *)aPanel toObject:(id)aObject
{
return mFieldEditor;
}
-(void) close
{
mBookmarkItem = nil;
[super close];
}
@end

View File

@ -1,22 +0,0 @@
{
IBClasses = (
{
CLASS = BookmarkInfoController;
LANGUAGE = ObjC;
OUTLETS = {
mDescriptionField = NSTextField;
mDescriptionLabel = NSTextField;
mKeywordField = NSTextField;
mKeywordLabel = NSTextField;
mLocationField = NSTextField;
mLocationLabel = NSTextField;
mNameField = NSTextField;
mNameLabel = NSTextField;
};
SUPERCLASS = NSWindowController;
},
{CLASS = BookmarkItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>144 74 366 258 0 0 1280 1002 </string>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,123 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Foundation/Foundation.h>
#import <Appkit/Appkit.h>
#import "MainController.h"
#import "CHBookmarksToolbar.h"
#import "CHExtendedOutlineView.h"
class nsIContent;
class BookmarksService;
@class BookmarkInfoController;
// data source for the bookmarks sidebar. We make one per browser window.
@interface BookmarksDataSource : NSObject
{
BookmarksService* mBookmarks;
IBOutlet id mOutlineView;
IBOutlet id mBrowserWindowController;
IBOutlet id mEditBookmarkButton;
IBOutlet id mDeleteBookmarkButton;
NSString* mCachedHref;
}
-(id) init;
-(void) windowClosing;
-(void) ensureBookmarks;
-(IBAction)addBookmark:(id)aSender;
-(void)endAddBookmark: (int)aCode;
-(IBAction)deleteBookmarks: (id)aSender;
-(void)deleteBookmark: (id)aItem;
-(IBAction)addFolder:(id)aSender;
-(void)addBookmark:(id)aSender useSelection:(BOOL)aSel isFolder:(BOOL)aIsFolder URL:(NSString*)aURL title:(NSString*)aTitle;
-(NSString*)resolveKeyword:(NSString*)aKeyword;
- (IBAction)openBookmarkInNewTab:(id)aSender;
- (IBAction)openBookmarkInNewWindow:(id)aSender;
- (void)openBookmarkGroup:(id)aTabView groupElement:(nsIDOMElement*)aFolder;
- (IBAction)showBookmarkInfo:(id)aSender;
- (BOOL)haveSelectedRow;
// Datasource methods.
- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item;
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item;
- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item;
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
- (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
- (BOOL)outlineView:(NSOutlineView *)ov writeItems:(NSArray*)items toPasteboard:(NSPasteboard*)pboard;
- (NSDragOperation)outlineView:(NSOutlineView*)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index;
- (BOOL)outlineView:(NSOutlineView*)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index;
- (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren;
// Delegate methods
- (void)outlineViewItemWillExpand:(NSNotification *)notification;
- (void)outlineViewItemWillCollapse:(NSNotification *)notification;
@end
@interface BookmarkItem : NSObject
{
nsIContent* mContentNode;
NSImage* mSiteIcon;
}
- (nsIContent*)contentNode;
- (void)setContentNode: (nsIContent*)aContentNode;
- (void)setSiteIcon:(NSImage*)image;
- (NSString*)url;
- (NSImage*)siteIcon;
- (NSNumber*)contentID;
- (id)copyWithZone:(NSZone *)aZone;
- (BOOL)isFolder;
@end

View File

@ -1,928 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "BookmarksDataSource.h"
#import "BookmarkInfoController.h"
#import "SiteIconProvider.h"
#include "nsCOMPtr.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIDocumentObserver.h"
#include "nsIDOMDocument.h"
#include "nsIDOMElement.h"
#include "nsINamespaceManager.h"
#include "nsIPrefBranch.h"
#include "nsIServiceManager.h"
#include "nsVoidArray.h"
#import "BookmarksService.h"
@implementation BookmarksDataSource
-(id) init
{
if ( (self = [super init]) ) {
mBookmarks = nsnull;
mCachedHref = nil;
}
return self;
}
-(void) awakeFromNib
{
// make sure these are disabled at the start since the outliner
// starts off with no selection.
[mEditBookmarkButton setEnabled:NO];
[mDeleteBookmarkButton setEnabled:NO];
}
-(void) windowClosing
{
if (mBookmarks) {
mBookmarks->RemoveObserver();
delete mBookmarks;
}
}
-(void) ensureBookmarks
{
if (mBookmarks)
return;
mBookmarks = new BookmarksService(self);
mBookmarks->AddObserver();
[mOutlineView setTarget: self];
[mOutlineView setDoubleAction: @selector(openBookmark:)];
[mOutlineView setDeleteAction: @selector(deleteBookmarks:)];
[mOutlineView reloadData];
}
-(IBAction)addBookmark:(id)aSender
{
[self addBookmark: aSender useSelection: YES isFolder: NO URL:nil title:nil];
}
-(IBAction)addFolder:(id)aSender
{
[self addBookmark: aSender useSelection: YES isFolder: YES URL:nil title:nil];
}
-(void)addBookmark:(id)aSender useSelection:(BOOL)aUseSel isFolder:(BOOL)aIsFolder URL:(NSString*)aURL title:(NSString*)aTitle
{
if (!mBookmarks)
return;
// We use the selected item to determine the parent only if aUseSel is YES.
BookmarkItem* item = nil;
if (aUseSel && ([mOutlineView numberOfSelectedRows] == 1)) {
// There is only one selected row. If it is a folder, use it as our parent.
// Otherwise, use our parent,
int index = [mOutlineView selectedRow];
item = [mOutlineView itemAtRow: index];
if (![mOutlineView isExpandable: item]) {
// We can't be used as the parent. Try our parent.
nsIContent* content = [item contentNode];
if (!content)
return;
nsCOMPtr<nsIContent> parentContent;
content->GetParent(*getter_AddRefs(parentContent));
nsCOMPtr<nsIContent> root;
mBookmarks->GetRootContent(getter_AddRefs(root));
// The root has no item, so we don't need to do a lookup unless we
// aren't the root.
if (parentContent != root) {
PRUint32 contentID;
parentContent->GetContentID(&contentID);
item = [(BookmarksService::gDictionary) objectForKey: [NSNumber numberWithInt: contentID]];
}
}
}
nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mBookmarks->gBookmarks));
nsAutoString title, href;
if (!aIsFolder) {
// If no URL and title were specified, get them from the current page.
if (aURL && aTitle) {
[aURL assignTo_nsAString:href];
[aTitle assignTo_nsAString:title];
} else {
BookmarksService::GetTitleAndHrefForBrowserView([[mBrowserWindowController getBrowserWrapper] getBrowserView],
title, href);
}
mCachedHref = [NSString stringWith_nsAString: href];
[mCachedHref retain];
} else { // Folder
mCachedHref = nil;
title = NS_LITERAL_STRING("New Folder"); // XXX localize me
}
NSTextField* textField = [mBrowserWindowController getAddBookmarkTitle];
NSString* bookmarkTitle = [NSString stringWith_nsAString: title];
NSString* cleanedTitle = [bookmarkTitle stringByReplacingCharactersInSet:[NSCharacterSet controlCharacterSet] withString:@" "];
[textField setStringValue: cleanedTitle];
[mBrowserWindowController cacheBookmarkDS: self];
// Show/hide the bookmark all tabs checkbox as appropriate.
NSTabView* tabView = [mBrowserWindowController getTabBrowser];
id checkbox = [mBrowserWindowController getAddBookmarkCheckbox];
BOOL hasSuperview = [checkbox superview] != nil;
if (aIsFolder && hasSuperview) {
// Just don't show it at all.
[checkbox removeFromSuperview];
[checkbox retain];
}
else if (!aIsFolder && !hasSuperview) {
// Put it back in.
[[[mBrowserWindowController getAddBookmarkSheetWindow] contentView] addSubview: checkbox];
[checkbox autorelease];
}
// Enable the bookmark all tabs checkbox if appropriate.
if (!aIsFolder)
[[mBrowserWindowController getAddBookmarkCheckbox] setEnabled: ([tabView numberOfTabViewItems] > 1)];
// Build up the folder list.
NSPopUpButton* popup = [mBrowserWindowController getAddBookmarkFolder];
BookmarksService::ConstructAddBookmarkFolderList(popup, item);
[NSApp beginSheet: [mBrowserWindowController getAddBookmarkSheetWindow]
modalForWindow: [mBrowserWindowController window]
modalDelegate: nil //self
didEndSelector: nil //@selector(sheetDidEnd:)
contextInfo: nil];
}
-(void)endAddBookmark: (int)aCode
{
if (aCode == 0)
return;
BOOL isGroup = NO;
id checkbox = [mBrowserWindowController getAddBookmarkCheckbox];
if (([checkbox superview] != nil) && [checkbox isEnabled] && ([checkbox state] == NSOnState)) {
mCachedHref = nil;
isGroup = YES;
}
nsAutoString title;
[[[mBrowserWindowController getAddBookmarkTitle] stringValue] assignTo_nsAString:title];
nsAutoString tagName;
if (mCachedHref)
tagName = NS_LITERAL_STRING("bookmark");
else
tagName = NS_LITERAL_STRING("folder");
nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mBookmarks->gBookmarks));
nsCOMPtr<nsIDOMElement> elt;
domDoc->CreateElementNS(NS_LITERAL_STRING("http://chimera.mozdev.org/bookmarks/"),
tagName,
getter_AddRefs(elt));
elt->SetAttribute(NS_LITERAL_STRING("name"), title);
if (mCachedHref) {
nsAutoString href;
[mCachedHref assignTo_nsAString:href];
[mCachedHref release];
elt->SetAttribute(NS_LITERAL_STRING("href"), href);
}
if (isGroup) {
// We have to iterate over each tab and create content nodes using the
// title/href of all the pages. They are inserted underneath the parent.
elt->SetAttribute(NS_LITERAL_STRING("group"), NS_LITERAL_STRING("true"));
id tabBrowser = [mBrowserWindowController getTabBrowser];
int count = [tabBrowser numberOfTabViewItems];
for (int i = 0; i < count; i++) {
id browserView = [[[tabBrowser tabViewItemAtIndex: i] view] getBrowserView];
nsAutoString title, href;
BookmarksService::GetTitleAndHrefForBrowserView(browserView, title, href);
nsCOMPtr<nsIDOMElement> childElt;
domDoc->CreateElementNS(NS_LITERAL_STRING("http://chimera.mozdev.org/bookmarks/"),
NS_LITERAL_STRING("bookmark"),
getter_AddRefs(childElt));
childElt->SetAttribute(NS_LITERAL_STRING("name"), title);
childElt->SetAttribute(NS_LITERAL_STRING("href"), href);
nsCOMPtr<nsIDOMNode> dummy;
elt->AppendChild(childElt, getter_AddRefs(dummy));
}
}
// Figure out the parent element.
nsCOMPtr<nsIDOMElement> parentElt;
nsCOMPtr<nsIContent> parentContent;
NSPopUpButton* popup = [mBrowserWindowController getAddBookmarkFolder];
NSMenuItem* selectedItem = [popup selectedItem];
int tag = [selectedItem tag];
if (tag == -1) {
mBookmarks->GetRootContent(getter_AddRefs(parentContent));
parentElt = do_QueryInterface(parentContent);
}
else {
BookmarkItem* item = [(BookmarksService::gDictionary) objectForKey: [NSNumber numberWithInt: tag]];
// Get the content node.
parentContent = [item contentNode];
parentElt = do_QueryInterface(parentContent);
}
nsCOMPtr<nsIDOMNode> dummy;
parentElt->AppendChild(elt, getter_AddRefs(dummy));
nsCOMPtr<nsIContent> childContent(do_QueryInterface(elt));
mBookmarks->BookmarkAdded(parentContent, childContent);
}
-(IBAction)deleteBookmarks: (id)aSender
{
if (!mBookmarks)
return;
int index = [mOutlineView selectedRow];
if (index == -1)
return;
// first, see how many items are selected
BOOL haveBookmarks = NO;
NSEnumerator* testSelRows = [mOutlineView selectedRowEnumerator];
for (NSNumber* currIndex = [testSelRows nextObject];
currIndex != nil;
currIndex = [testSelRows nextObject])
{
index = [currIndex intValue];
BookmarkItem* item = [mOutlineView itemAtRow: index];
if ([mOutlineView isExpandable: item]) {
// dumb check to see if we're deleting an empty folder. Should really
// recurse down
if ([self outlineView:mOutlineView numberOfChildrenOfItem: item] > 0)
haveBookmarks = YES;
} else
haveBookmarks = YES;
}
// ideally, we should count the number of doomed bookmarks and tell the user
if (haveBookmarks) {
NSString *alert = NSLocalizedString(@"DeteleBookmarksAlert",@"");
NSString *message = NSLocalizedString(@"DeteleBookmarksMsg",@"");
NSString *okButton = NSLocalizedString(@"DeteleBookmarksOKButton",@"");
NSString *cancelButton = NSLocalizedString(@"DeteleBookmarksCancelButton",@"");
if (NSRunAlertPanel(alert, message, okButton, cancelButton, nil) != NSAlertDefaultReturn)
return;
}
// The alert panel was the key window. As soon as we dismissed it, Cocoa will
// pick a new one for us. Ideally, it'll be the window we were using when
// we clicked the delete button. However, if by chance the BookmarkInfoController
// is visible, it will become the key window since it's a panel. If we then delete
// the bookmark and try to close the window before we've setup a new bookmark,
// we'll trigger the windowDidResignKey message, which will try to update the bookmark
// we just deleted, and things will crash. So, we'll trigger windowDidResignKey now
// and avoid the unpleasentness of a crash log.
if (![[mBrowserWindowController window] isKeyWindow])
[[mBrowserWindowController window] makeKeyWindow];
// we'll run into problems if a parent item and one if its children are both selected.
// A cheap way of having to avoid scanning the list to remove children is to have the
// outliner collapse all items that are being deleted. This will cull the selection
// for us and eliminate any children that happened to be selected.
NSEnumerator* selRows = [mOutlineView selectedRowEnumerator];
for (NSNumber* currIndex = [selRows nextObject];
currIndex != nil;
currIndex = [selRows nextObject]) {
index = [currIndex intValue];
BookmarkItem* item = [mOutlineView itemAtRow: index];
[mOutlineView collapseItem: item];
}
// create array of items we need to delete. Deleting items out of of the
// selection array is problematic for some reason.
NSMutableArray* itemsToDelete = [[[NSMutableArray alloc] init] autorelease];
selRows = [mOutlineView selectedRowEnumerator];
for (NSNumber* currIndex = [selRows nextObject];
currIndex != nil;
currIndex = [selRows nextObject]) {
index = [currIndex intValue];
BookmarkItem* item = [mOutlineView itemAtRow: index];
[itemsToDelete addObject: item];
}
// delete all bookmarks that are in our array
int count = [itemsToDelete count];
for (int i = 0; i < count; i++) {
BookmarkItem* item = [itemsToDelete objectAtIndex: i];
[self deleteBookmark: item];
}
// restore selection to location near last item deleted or last item
int total = [mOutlineView numberOfRows];
if (index >= total)
index = total - 1;
[mOutlineView selectRow: index byExtendingSelection: NO];
// lame, but makes sure we catch all delete events in Info Panel
[[NSNotificationCenter defaultCenter] postNotificationName:@"NSOutlineViewSelectionDidChangeNotification" object:mOutlineView];
}
-(void)deleteBookmark:(id)aItem
{
nsCOMPtr<nsIContent> content = [aItem contentNode];
nsCOMPtr<nsIDOMElement> child(do_QueryInterface(content));
if (!child)
return;
if (child == BookmarksService::gToolbarRoot)
return; // Don't allow the personal toolbar to be deleted.
nsCOMPtr<nsIDOMNode> parent;
child->GetParentNode(getter_AddRefs(parent));
nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parent));
nsCOMPtr<nsIDOMNode> dummy;
if (parent)
parent->RemoveChild(child, getter_AddRefs(dummy));
mBookmarks->BookmarkRemoved(parentContent, content);
}
-(IBAction)openBookmark: (id)aSender
{
int index = [mOutlineView selectedRow];
if (index == -1)
return;
id item = [mOutlineView itemAtRow: index];
if (!item)
return;
nsIContent* content = [item contentNode];
nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(content));
nsAutoString group;
content->GetAttr(kNameSpaceID_None, BookmarksService::gGroupAtom, group);
if (!group.IsEmpty())
mBookmarks->OpenBookmarkGroup([mBrowserWindowController getTabBrowser], elt);
else if ([mOutlineView isExpandable: item]) {
if ([mOutlineView isItemExpanded: item])
[mOutlineView collapseItem: item];
else
[mOutlineView expandItem: item];
}
else {
nsAutoString href;
content->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, href);
if (!href.IsEmpty()) {
NSString* url = [NSString stringWith_nsAString: href];
[[mBrowserWindowController getBrowserWrapper] loadURI: url referrer:nil flags: NSLoadFlagsNone activate:YES];
}
}
}
-(NSString*) resolveKeyword: (NSString*) aKeyword
{
return BookmarksService::ResolveKeyword(aKeyword);
}
#pragma mark -
//
// outlineView:shouldEditTableColumn:item: (delegate method)
//
// Called by the outliner to determine whether or not we should allow the
// user to edit this item. For now, Cocoa doesn't correctly handle editing
// of attributed strings with icons, so we can't turn this on. :(
//
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
return NO;
}
- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
{
if (!mBookmarks)
return nil;
nsCOMPtr<nsIContent> content;
if (!item)
BookmarksService::GetRootContent(getter_AddRefs(content));
else
content = [item contentNode];
nsCOMPtr<nsIContent> child;
content->ChildAt(index, *getter_AddRefs(child));
if ( child )
return BookmarksService::GetWrapperFor(child);
return nil;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
if (!mBookmarks)
return NO;
if (!item)
return YES; // The root node is always open.
BOOL isExpandable = [item isFolder];
// XXXben - persistence of folder open state
// I'm adding this code, turned off, until I can figure out how to refresh the NSOutlineView's
// row count. Currently the items are expanded, but the outline view continues to believe it had
// the number of rows it had before the item was opened visible, until the view is resized.
#if 0
if (isExpandable) {
PRBool isOpen = content->HasAttr(kNameSpaceID_None, BookmarksService::gOpenAtom);
if (isOpen)
[mOutlineView expandItem: item];
else
[mOutlineView collapseItem: item];
}
#endif
return isExpandable;
}
- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
if (!mBookmarks)
return 0;
nsCOMPtr<nsIContent> content;
if (!item)
mBookmarks->GetRootContent(getter_AddRefs(content));
else
content = [item contentNode];
PRInt32 childCount;
content->ChildCount(childCount);
return childCount;
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
NSString *columnName = [tableColumn identifier];
NSMutableAttributedString *cellValue = [[NSMutableAttributedString alloc] init];
NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:nil];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];
NSMutableAttributedString *attachmentAttrString = nil;
NSCell *attachmentAttrStringCell;
if ([columnName isEqualToString: @"name"]) {
nsIContent* content = [item contentNode];
nsAutoString nameAttr;
content->GetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr);
//Set cell's textual contents
[cellValue replaceCharactersInRange:NSMakeRange(0, [cellValue length]) withString:[NSString stringWith_nsAString: nameAttr]];
//Create an attributed string to hold the empty attachment, then release the components.
attachmentAttrString = [[NSMutableAttributedString attributedStringWithAttachment:textAttachment] retain];
[textAttachment release];
[fileWrapper release];
//Get the cell of the text attachment.
attachmentAttrStringCell = (NSCell *)[(NSTextAttachment *)[attachmentAttrString attribute:NSAttachmentAttributeName atIndex:0 effectiveRange:nil] attachmentCell];
nsCOMPtr<nsIDOMElement> elt(do_QueryInterface(content));
NSImage* bookmarkImage = mBookmarks->CreateIconForBookmark(elt);
[attachmentAttrStringCell setImage:bookmarkImage];
//Insert the image
[cellValue replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attachmentAttrString];
//Tweak the baseline to vertically center the text.
[cellValue addAttribute:NSBaselineOffsetAttributeName
value:[NSNumber numberWithFloat:-3.0]
range:NSMakeRange(0, 1)];
}
return cellValue;
}
- (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
#if NOT_USED
// ignore all this. It doesn't work, but i'm leaving it here just in case we ever try to turn
// this code back on. We have to remove the attributes from the string in order to correctly
// set it in the DOM.
NSString *columnName = [tableColumn identifier];
if ( [columnName isEqualTo:@"name"] ) {
// remove the attributes
int strLen = [object length];
NSMutableAttributedString *cellValue = [[NSMutableAttributedString alloc] initWithAttributedString:object];
[cellValue removeAttribute:NSBaselineOffsetAttributeName range:NSMakeRange(0,1)];
[cellValue removeAttribute:NSAttachmentAttributeName range:NSMakeRange(0,strLen)];
// extract the unicode
strLen = [cellValue length];
PRUnichar* buffer = new PRUnichar[strLen + 1];
buffer[strLen] = '\0';
if ( !buffer )
return;
[cellValue getCharacters: buffer];
nsAutoString nameAttr;
nameAttr.Adopt(buffer);
// stash it into the dom.
nsIContent* content = [item contentNode];
content->SetAttr(kNameSpaceID_None, BookmarksService::gNameAtom, nameAttr, PR_TRUE);
[cellValue release];
}
#endif
}
- (BOOL)outlineView:(NSOutlineView *)ov writeItems:(NSArray*)items toPasteboard:(NSPasteboard*)pboard
{
if (!mBookmarks)
return NO;
#ifdef FILTER_DESCENDANT_ON_DRAG
NSArray *toDrag = BookmarksService::FilterOutDescendantsForDrag(items);
#else
NSArray *toDrag = items;
#endif
int count = [toDrag count];
if (count > 0) {
// Create Pasteboard Data
NSMutableArray *draggedID = [NSMutableArray arrayWithCapacity: count];
for (int i = 0; i < count; i++)
[draggedID addObject: [[toDrag objectAtIndex: i] contentID]];
if (count == 1) {
// if we have just one item, we add some more flavours
[pboard declareTypes: [NSArray arrayWithObjects:
@"MozBookmarkType", NSURLPboardType, NSStringPboardType, nil] owner: self];
[pboard setPropertyList: draggedID forType: @"MozBookmarkType"];
NSString* itemURL = [[toDrag objectAtIndex: 0] url];
[pboard setString:itemURL forType: NSStringPboardType];
[[NSURL URLWithString:itemURL] writeToPasteboard: pboard];
// maybe construct the @"MozURLType" type here also
}
else {
// multiple bookmarks. Array sof strings or NSURLs seem to
// confuse receivers. Not sure what the correct way is.
[pboard declareTypes: [NSArray arrayWithObject: @"MozBookmarkType"] owner: self];
[pboard setPropertyList: draggedID forType: @"MozBookmarkType"];
}
return YES;
}
return NO;
}
- (NSDragOperation)outlineView:(NSOutlineView*)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
{
NSArray* types = [[info draggingPasteboard] types];
// if the index is -1, deny the drop
if (index == NSOutlineViewDropOnItemIndex)
return NSDragOperationNone;
if ([types containsObject: @"MozBookmarkType"]) {
NSArray *draggedIDs = [[info draggingPasteboard] propertyListForType: @"MozBookmarkType"];
BookmarkItem* parent;
parent = (item) ? item : BookmarksService::GetRootItem();
return (BookmarksService::IsBookmarkDropValid(parent, index, draggedIDs)) ? NSDragOperationGeneric : NSDragOperationNone;
} else if ([types containsObject: @"MozURLType"]) {
return NSDragOperationGeneric;
} else if ([types containsObject: NSStringPboardType]) {
return NSDragOperationGeneric;
}
return NSDragOperationNone;
}
- (BOOL)outlineView:(NSOutlineView*)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
{
NSArray *types = [[info draggingPasteboard] types];
BookmarkItem* parent = (item) ? item : BookmarksService::GetRootItem();
if ([types containsObject: @"MozBookmarkType"])
{
NSArray *draggedItems = [[info draggingPasteboard] propertyListForType: @"MozBookmarkType"];
return BookmarksService::PerformBookmarkDrop(parent, index, draggedItems);
}
else if ([types containsObject: @"MozURLType"])
{
NSDictionary* proxy = [[info draggingPasteboard] propertyListForType: @"MozURLType"];
BookmarkItem* beforeItem = [self outlineView:ov child:index ofItem:item];
return BookmarksService::PerformProxyDrop(parent, beforeItem, proxy);
}
else if ([types containsObject: NSStringPboardType])
{
NSString* draggedText = [[info draggingPasteboard] stringForType:NSStringPboardType];
BookmarkItem* beforeItem = [self outlineView:ov child:index ofItem:item];
return BookmarksService::PerformURLDrop(parent, beforeItem, draggedText, draggedText);
}
return NO;
}
- (NSString *)outlineView:(NSOutlineView *)outlineView tooltipStringForItem:(id)item
{
NSString* descStr = nil;
NSString* hrefStr = nil;
nsIContent* content = [item contentNode];
nsAutoString value;
content->GetAttr(kNameSpaceID_None, BookmarksService::gDescriptionAtom, value);
if (value.Length())
descStr = [NSString stringWith_nsAString:value];
// Only description for folders
if ([item isFolder])
return descStr;
// Extract the URL from the item
content->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, value);
if (value.Length())
hrefStr = [NSString stringWith_nsAString:value];
if (!hrefStr)
return descStr;
else if (!descStr)
return hrefStr;
// Display both URL and description
return [NSString stringWithFormat:@"%@\n%@", hrefStr, descStr];
}
/*
- (NSMenu *)outlineView:(NSOutlineView *)outlineView contextMenuForItem:(id)item
{
// TODO - return (custom?) context menu for item here.
// Note that according to HIG, there should never be disabled items in
// a context menu - instead, items that do not apply should be removed.
// We could nicely do that here.
}
*/
- (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren
{
if (!item)
[mOutlineView reloadData];
else
[mOutlineView reloadItem: item reloadChildren: aReloadChildren];
}
-(IBAction)openBookmarkInNewTab:(id)aSender
{
int index = [mOutlineView selectedRow];
if (index == -1)
return;
if ([mOutlineView numberOfSelectedRows] == 1) {
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return; // Something bad happened if we can't get prefs.
BookmarkItem* item = [mOutlineView itemAtRow: index];
nsAutoString hrefAttr;
[item contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, hrefAttr);
// stuff it into the string
NSString* hrefStr = [NSString stringWith_nsAString:hrefAttr];
PRBool loadInBackground;
pref->GetBoolPref("browser.tabs.loadInBackground", &loadInBackground);
[mBrowserWindowController openNewTabWithURL: hrefStr referrer:nil loadInBackground: loadInBackground];
}
}
-(IBAction)openBookmarkInNewWindow:(id)aSender
{
int index = [mOutlineView selectedRow];
if (index == -1)
return;
if ([mOutlineView numberOfSelectedRows] == 1) {
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return; // Something bad happened if we can't get prefs.
BookmarkItem* item = [mOutlineView itemAtRow: index];
nsAutoString hrefAttr;
[item contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gHrefAtom, hrefAttr);
// stuff it into the string
NSString* hrefStr = [NSString stringWith_nsAString:hrefAttr];
PRBool loadInBackground;
pref->GetBoolPref("browser.tabs.loadInBackground", &loadInBackground);
nsAutoString group;
[item contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gGroupAtom, group);
if (group.IsEmpty())
[mBrowserWindowController openNewWindowWithURL: hrefStr referrer: nil loadInBackground: loadInBackground];
else {
nsCOMPtr<nsIDOMElement> elt(do_QueryInterface([item contentNode]));
[mBrowserWindowController openNewWindowWithGroup: elt loadInBackground: loadInBackground];
}
}
}
-(void)openBookmarkGroup:(id)aTabView groupElement:(nsIDOMElement*)aFolder
{
mBookmarks->OpenBookmarkGroup(aTabView, aFolder);
}
-(IBAction)showBookmarkInfo:(id)aSender
{
BookmarkInfoController *bic = [BookmarkInfoController sharedBookmarkInfoController];
int index = [mOutlineView selectedRow];
BookmarkItem* item = [mOutlineView itemAtRow: index];
[bic setBookmark:item];
[bic showWindow:bic];
}
- (BOOL)haveSelectedRow
{
return ([mOutlineView selectedRow] != -1);
}
-(void)outlineViewSelectionDidChange: (NSNotification*) aNotification
{
BookmarkInfoController *bic = [BookmarkInfoController sharedBookmarkInfoController];
int index = [mOutlineView selectedRow];
if (index == -1) {
[mEditBookmarkButton setEnabled:NO];
[mDeleteBookmarkButton setEnabled:NO];
[bic close];
}
else {
[mEditBookmarkButton setEnabled:YES];
[mDeleteBookmarkButton setEnabled:YES];
if ([[bic window] isVisible])
[bic setBookmark:[mOutlineView itemAtRow:index]];
}
}
-(BOOL)validateMenuItem:(NSMenuItem*)aMenuItem
{
int index = [mOutlineView selectedRow];
if (index == -1)
return NO;
BookmarkItem* item = [mOutlineView itemAtRow: index];
BOOL isBookmark = [mOutlineView isExpandable:item] == NO;
nsAutoString group;
[item contentNode]->GetAttr(kNameSpaceID_None, BookmarksService::gGroupAtom, group);
BOOL isGroup = !group.IsEmpty();
if (([aMenuItem action] == @selector(openBookmarkInNewWindow:))) {
// Bookmarks and Bookmark Groups can be opened in a new window
return (isBookmark || isGroup);
}
else if (([aMenuItem action] == @selector(openBookmarkInNewTab:))) {
// Only Bookmarks can be opened in new tabs
return isBookmark && [mBrowserWindowController newTabsAllowed];
}
return YES;
}
- (void)outlineViewItemWillExpand:(NSNotification *)notification
{
BookmarkItem* item = [[notification userInfo] objectForKey:[[[notification userInfo] allKeys] objectAtIndex: 0]];
[item contentNode]->SetAttr(kNameSpaceID_None, BookmarksService::gOpenAtom, NS_LITERAL_STRING("true"), PR_FALSE);
}
- (void)outlineViewItemWillCollapse:(NSNotification *)notification
{
BookmarkItem* item = [[notification userInfo] objectForKey:[[[notification userInfo] allKeys] objectAtIndex: 0]];
[item contentNode]->UnsetAttr(kNameSpaceID_None, BookmarksService::gOpenAtom, PR_FALSE);
}
@end
#pragma mark -
@implementation BookmarkItem
-(void)dealloc
{
[mSiteIcon release];
[super dealloc];
}
-(nsIContent*)contentNode
{
return mContentNode;
}
- (NSNumber*)contentID
{
PRUint32 contentID = 0;
mContentNode->GetContentID(&contentID);
return [NSNumber numberWithInt: contentID];
}
- (NSString *)description
{
nsCOMPtr<nsIContent> item = [self contentNode];
nsCOMPtr<nsIDOMElement> element(do_QueryInterface(item));
nsAutoString href;
element->GetAttribute(NS_LITERAL_STRING("name"), href);
NSString* info = [NSString stringWith_nsAString: href];
return [NSString stringWithFormat:@"<BookmarkItem, name = \"%@\">", info];
}
- (NSString *)url
{
nsCOMPtr<nsIContent> item = [self contentNode];
nsCOMPtr<nsIDOMElement> element(do_QueryInterface(item));
nsAutoString href;
element->GetAttribute(NS_LITERAL_STRING("href"), href);
return [NSString stringWith_nsAString: href];
}
- (void)setSiteIcon:(NSImage*)image
{
//NSLog(@"Setting site icon for %@", [self url]);
[mSiteIcon autorelease];
mSiteIcon = [image retain];
}
- (NSImage*)siteIcon
{
return mSiteIcon;
}
-(void)setContentNode: (nsIContent*)aContentNode
{
mContentNode = aContentNode;
}
- (id)copyWithZone:(NSZone *)aZone
{
BookmarkItem* copy = [[[self class] allocWithZone: aZone] init];
[copy setContentNode: mContentNode];
[copy setSiteIcon: mSiteIcon];
return copy;
}
- (BOOL)isFolder
{
nsCOMPtr<nsIAtom> tagName;
mContentNode->GetTag(*getter_AddRefs(tagName));
return (tagName == BookmarksService::gFolderAtom);
}
@end

View File

@ -1,164 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <Appkit/Appkit.h>
#include <Carbon/Carbon.h>
#include "nsCOMPtr.h"
#include "nsIDocument.h"
#include "nsIDocumentObserver.h"
#include "nsVoidArray.h"
#import "MainController.h"
#import "CHBookmarksToolbar.h"
#import "CHExtendedOutlineView.h"
class nsIAtom;
class nsIDOMHTMLDocument;
@class BookmarksDataSource;
@class BookmarkItem;
// despite appearances, BookmarksService is not a singleton. We make one for the bookmarks menu,
// one each per BookmarksDataSource, and one per bookmarks toolbar. It relies on a bunch of global
// variables, which is evil.
class BookmarksService
{
public:
BookmarksService(BookmarksDataSource* aDataSource);
BookmarksService(CHBookmarksToolbar* aToolbar);
virtual ~BookmarksService();
void AddObserver();
void RemoveObserver();
public:
static void BookmarkAdded(nsIContent* aContainer, nsIContent* aChild, bool shouldFlush = true);
static void BookmarkChanged(nsIContent* aItem, bool shouldFlush = true);
static void BookmarkRemoved(nsIContent* aContainer, nsIContent* aChild, bool shouldFlush = true);
static void AddBookmarkToFolder(nsString& aURL, nsString& aTitle, nsIDOMElement* aFolder, nsIDOMElement* aBeforeElt);
static void MoveBookmarkToFolder(nsIDOMElement* aBookmark, nsIDOMElement* aFolder, nsIDOMElement* aBeforeElt);
static void DeleteBookmark(nsIDOMElement* aBookmark);
static void GetRootContent(nsIContent** aResult);
static BookmarkItem* GetRootItem();
static BookmarkItem* GetWrapperFor(nsIContent* aItem);
static BookmarkItem* GetWrapperFor(PRUint32 contentID);
static void ReadBookmarks();
static void FlushBookmarks();
static void ConstructBookmarksMenu(NSMenu* aMenu, nsIContent* aContent);
static void OpenMenuBookmark(BrowserWindowController* aController, id aMenuItem);
static void AddMenuBookmark(NSMenu* aMenu, nsIContent* aParent, nsIContent* aChild, PRInt32 aIndex);
static NSMenu* LocateMenu(nsIContent* aContent);
static void ConstructAddBookmarkFolderList(NSPopUpButton* aPopup, BookmarkItem* aItem);
static NSImage* CreateIconForBookmark(nsIDOMElement* aElement);
static void EnsureToolbarRoot();
static void ImportBookmarks(nsIDOMHTMLDocument* aHTMLDoc);
static void GetTitleAndHrefForBrowserView(id aBrowserView, nsString& aTitle, nsString& aHref);
static void OpenBookmarkGroup(id aTabView, nsIDOMElement* aFolder);
static NSString* ResolveKeyword(NSString* aKeyword);
static BOOL DoAncestorsIncludeNode(BookmarkItem* bookmark, BookmarkItem* searchItem);
static bool IsBookmarkDropValid(BookmarkItem* proposedParent, int index, NSArray* draggedIDs);
static bool PerformBookmarkDrop(BookmarkItem* parent, int index, NSArray* draggedIDs);
static bool PerformProxyDrop(BookmarkItem* parentItem, BookmarkItem* beforeItem, NSDictionary* data);
static bool PerformURLDrop(BookmarkItem* parentItem, BookmarkItem* beforeItem, NSString* title, NSString* url);
public:
// Global counter and pointers to our singletons.
static PRUint32 gRefCnt;
// A dictionary that maps from content IDs (which uniquely identify content nodes)
// to Obj-C bookmarkItem objects. These objects are handed back to UI elements like
// the outline view.
static NSMutableDictionary* gDictionary;
static MainController* gMainController;
static NSMenu* gBookmarksMenu;
static nsIDOMElement* gToolbarRoot;
static nsIAtom* gFolderAtom;
static nsIAtom* gNameAtom;
static nsIAtom* gHrefAtom;
static nsIAtom* gKeywordAtom;
static nsIAtom* gDescriptionAtom;
static nsIAtom* gBookmarkAtom;
static nsIAtom* gOpenAtom;
static nsIAtom* gGroupAtom;
static nsIDocument* gBookmarks;
static BOOL gBookmarksFileReadOK;
static nsVoidArray* gInstances;
static int CHInsertNone;
static int CHInsertInto;
static int CHInsertBefore;
static int CHInsertAfter;
private:
// There are three kinds of bookmarks data sources:
// tree views (mDataSource), the personal toolbar (mToolbar)
// and menus (gBookmarksMenu).
CHBookmarksToolbar* mToolbar;
BookmarksDataSource* mDataSource;
};
// singleton bookmarks manager object
@interface BookmarksManager : NSObject
{
}
+ (BookmarksManager*)sharedBookmarksManager;
- (void)loadProxyImageFor:(id)requestor withURI:(NSString*)inURIString;
@end

File diff suppressed because it is too large Load Diff

View File

@ -1,45 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Matt Judy. Portions
* of code @2002 nibfile.com.
*/
#import <Cocoa/Cocoa.h>
#import "BrowserTabViewItem.h"
@interface BrowserTabView : NSTabView
{
BOOL autoHides;
BOOL mIsDropTarget;
BOOL mLastClickIsPotentialDrag;
int maxNumberOfTabs; // 0 means 'no max'
}
+ (BrowserTabViewItem*)makeNewTabItem;
// Behavior: Autohiding overrides the default tab visibility state.
// To switch back to usual tabView behavior, setAutoHides:NO.
// Initial value is read from defaults.
- (BOOL)autoHides;
- (void)setAutoHides:(BOOL)newSetting;
- (int)maxNumberOfTabs;
- (void)setMaxNumberOfTabs:(int)maxTabs;
- (BOOL)canMakeNewTabs;
- (void)addTabForURL:(NSString*)aURL referrer:(NSString*)aReferrer;
@end

View File

@ -1,406 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Matt Judy <matt@nibfile.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "BrowserTabView.h"
#import "BookmarksService.h"
#import "BookmarksDataSource.h"
#include "nsCOMPtr.h"
#include "nsIDOMElement.h"
#include "nsIContent.h"
#include "nsIAtom.h"
#include "nsString.h"
#include "nsCRT.h"
//////////////////////////
// NEEDS IMPLEMENTED : Implement drag tracking for moving tabs around.
// Implementation hints : Track drags ;)
// : Change tab controlTint to indicate drag location?
// : Move tab titles around when dragging.
//////////////////////////
@interface BrowserTabView (Private)
- (void)showOrHideTabsAsAppropriate;
- (BOOL)handleDropOnTab:(NSTabViewItem*)overTabViewItem overContent:(BOOL)overContentArea withURL:(NSString*)url;
- (BrowserTabViewItem*)getTabViewItemFromWindowPoint:(NSPoint)point;
- (void)showDragDestinationIndicator;
- (void)hideDragDestinationIndicator;
@end
#define kTabDropTargetHeight 18.0
@implementation BrowserTabView
/******************************************/
/*** Initialization ***/
/******************************************/
- (id)initWithFrame:(NSRect)frameRect
{
if ( (self = [super initWithFrame:frameRect]) ) {
autoHides = YES;
maxNumberOfTabs = 0; // no max
}
return self;
}
- (void)awakeFromNib
{
[self showOrHideTabsAsAppropriate];
[self registerForDraggedTypes:[NSArray arrayWithObjects:
@"MozURLType", @"MozBookmarkType", NSStringPboardType, NSFilenamesPboardType, nil]];
}
/******************************************/
/*** Overridden Methods ***/
/******************************************/
- (BOOL)isOpaque
{
if ( ([self tabViewType] == NSNoTabsBezelBorder) && (NSAppKitVersionNumber < 633) )
return NO;
return [super isOpaque];
}
- (void)drawRect:(NSRect)aRect
{
if (mIsDropTarget)
{
NSRect hilightRect = aRect;
hilightRect.size.height = kTabDropTargetHeight; // no need to move origin.y; our coords are flipped
NSBezierPath* dropTargetOutline = [NSBezierPath bezierPathWithRect:hilightRect];
[[[NSColor colorForControlTint:NSDefaultControlTint] colorWithAlphaComponent:0.5] set];
[dropTargetOutline fill];
}
[super drawRect:aRect];
}
- (void)addTabViewItem:(NSTabViewItem *)tabViewItem
{
[super addTabViewItem:tabViewItem];
[self showOrHideTabsAsAppropriate];
}
- (void)removeTabViewItem:(NSTabViewItem *)tabViewItem
{
[super removeTabViewItem:tabViewItem];
[self showOrHideTabsAsAppropriate];
}
- (void)insertTabViewItem:(NSTabViewItem *)tabViewItem atIndex:(int)index
{
[super insertTabViewItem:tabViewItem atIndex:index];
[self showOrHideTabsAsAppropriate];
}
/******************************************/
/*** Accessor Methods ***/
/******************************************/
- (BOOL)autoHides
{
return autoHides;
}
- (void)setAutoHides:(BOOL)newSetting
{
autoHides = newSetting;
}
- (int)maxNumberOfTabs
{
return maxNumberOfTabs;
}
- (void)setMaxNumberOfTabs:(int)maxTabs
{
maxNumberOfTabs = maxTabs;
}
- (BOOL)canMakeNewTabs
{
return maxNumberOfTabs == 0 || [self numberOfTabViewItems] < maxNumberOfTabs;
}
/******************************************/
/*** Instance Methods ***/
/******************************************/
// 03-03-2002 mlj: Modifies tab view size and type appropriately... Fragile.
// Only to be used with the 2 types of tab view which we use in Chimera.
- (void)showOrHideTabsAsAppropriate
{
//if ( autoHides == YES )
{
BOOL tabVisibilityChanged = NO;
BOOL tabsVisible = NO;
if ( [[self tabViewItems] count] < 2)
{
if ( [self tabViewType] != NSNoTabsBezelBorder )
{
[self setFrameSize:NSMakeSize( NSWidth([self frame]), NSHeight([self frame]) + 10 )];
[self setTabViewType:NSNoTabsBezelBorder];
tabVisibilityChanged = YES;
}
tabsVisible = NO;
}
else
{
if ( [self tabViewType] != NSTopTabsBezelBorder )
{
[self setFrameSize:NSMakeSize( NSWidth([self frame]), NSHeight([self frame]) - 10 )];
[self setTabViewType:NSTopTabsBezelBorder];
tabVisibilityChanged = YES;
}
tabsVisible = YES;
}
// tell the tabs that visibility changed
NSArray* tabViewItems = [self tabViewItems];
for (unsigned int i = 0; i < [tabViewItems count]; i ++)
{
NSTabViewItem* tabItem = [tabViewItems objectAtIndex:i];
if ([tabItem isMemberOfClass:[BrowserTabViewItem class]])
[(BrowserTabViewItem*)tabItem updateTabVisibility:tabsVisible];
}
if (tabVisibilityChanged)
[self setNeedsDisplay:YES];
}
}
- (BOOL)handleDropOnTab:(NSTabViewItem*)overTabViewItem overContent:(BOOL)overContentArea withURL:(NSString*)url
{
if (overTabViewItem)
{
[[overTabViewItem view] loadURI: url referrer:nil flags: NSLoadFlagsNone activate:NO];
return YES;
}
else if (overContentArea)
{
[[[self selectedTabViewItem] view] loadURI: url referrer:nil flags: NSLoadFlagsNone activate:NO];
return YES;
}
else if ([self canMakeNewTabs])
{
[self addTabForURL:url referrer:nil];
return YES;
}
return NO;
}
- (BrowserTabViewItem*)getTabViewItemFromWindowPoint:(NSPoint)point
{
NSPoint localPoint = [self convertPoint: point fromView: nil];
NSTabViewItem* overTabViewItem = [self tabViewItemAtPoint: localPoint];
return (BrowserTabViewItem*)overTabViewItem;
}
- (void)showDragDestinationIndicator
{
if (!mIsDropTarget)
{
NSRect invalidRect = [self bounds];
invalidRect.size.height = kTabDropTargetHeight;
[self setNeedsDisplayInRect:invalidRect];
mIsDropTarget = YES;
}
}
- (void)hideDragDestinationIndicator
{
if (mIsDropTarget)
{
NSRect invalidRect = [self bounds];
invalidRect.size.height = kTabDropTargetHeight;
[self setNeedsDisplayInRect:invalidRect];
mIsDropTarget = NO;
}
}
#pragma mark -
// NSDraggingDestination ///////////
- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
NSPoint localPoint = [self convertPoint: [sender draggingLocation] fromView: nil];
NSTabViewItem* overTabViewItem = [self tabViewItemAtPoint: localPoint];
BOOL overContentArea = NSPointInRect(localPoint, [self contentRect]);
if (overTabViewItem)
return NSDragOperationNone; // the tab will handle it
if (!overContentArea && ![self canMakeNewTabs])
return NSDragOperationNone;
[self showDragDestinationIndicator]; // XXX optimize
return NSDragOperationGeneric;
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
NSPoint localPoint = [self convertPoint: [sender draggingLocation] fromView: nil];
NSTabViewItem* overTabViewItem = [self tabViewItemAtPoint: localPoint];
BOOL overContentArea = NSPointInRect(localPoint, [self contentRect]);
if (overTabViewItem)
return NSDragOperationNone; // the tab will handle it
if (!overContentArea && ![self canMakeNewTabs])
{
[self hideDragDestinationIndicator];
return NSDragOperationNone;
}
[self showDragDestinationIndicator];
return NSDragOperationGeneric;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
[self hideDragDestinationIndicator];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
// determine if we are over a tab or the content area
NSPoint localPoint = [self convertPoint: [sender draggingLocation] fromView: nil];
NSTabViewItem* overTabViewItem = [self tabViewItemAtPoint: localPoint];
BOOL overContentArea = NSPointInRect(localPoint, [self contentRect]);
NSArray* pasteBoardTypes = [[sender draggingPasteboard] types];
[self hideDragDestinationIndicator];
if ([pasteBoardTypes containsObject: @"MozBookmarkType"])
{
NSArray* contentIds = [[sender draggingPasteboard] propertyListForType: @"MozBookmarkType"];
if (contentIds) {
// drag type is chimera bookmarks
for (unsigned int i = 0; i < [contentIds count]; ++i) {
BookmarkItem* item = [BookmarksService::gDictionary objectForKey: [contentIds objectAtIndex:i]];
nsCOMPtr<nsIDOMElement> bookmarkElt = do_QueryInterface([item contentNode]);
nsCOMPtr<nsIAtom> tagName;
[item contentNode]->GetTag(*getter_AddRefs(tagName));
nsAutoString href;
bookmarkElt->GetAttribute(NS_LITERAL_STRING("href"), href);
NSString* url = [NSString stringWith_nsAString: href];
nsAutoString group;
bookmarkElt->GetAttribute(NS_LITERAL_STRING("group"), group);
if (!group.IsEmpty()) {
BookmarksService::OpenBookmarkGroup(self, bookmarkElt);
} else {
return [self handleDropOnTab:overTabViewItem overContent:overContentArea withURL:url];
}
} // for each item
}
}
else if ([pasteBoardTypes containsObject: @"MozURLType"])
{
// drag type is MozURLType
NSDictionary* data = [[sender draggingPasteboard] propertyListForType: @"MozURLType"];
if (data) {
NSString* urlString = [data objectForKey:@"url"];
return [self handleDropOnTab:overTabViewItem overContent:overContentArea withURL:urlString];
}
}
else if ([pasteBoardTypes containsObject: NSStringPboardType])
{
NSString* urlString = [[sender draggingPasteboard] stringForType: NSStringPboardType];
return [self handleDropOnTab:overTabViewItem overContent:overContentArea withURL:urlString];
}
else if ([pasteBoardTypes containsObject: NSURLPboardType])
{
NSURL* urlData = [NSURL URLFromPasteboard:[sender draggingPasteboard]];
return [self handleDropOnTab:overTabViewItem overContent:overContentArea withURL:[urlData absoluteString]];
}
else if ([pasteBoardTypes containsObject: NSFilenamesPboardType])
{
NSString* urlString = [[sender draggingPasteboard] stringForType: NSFilenamesPboardType];
return [self handleDropOnTab:overTabViewItem overContent:overContentArea withURL:urlString];
}
return NO;
}
#pragma mark -
-(void)addTabForURL:(NSString*)aURL referrer:(NSString*)aReferrer
{
// We need to make a new tab.
BrowserTabViewItem *tabViewItem= [BrowserTabView makeNewTabItem];
CHBrowserWrapper *newView = [[[CHBrowserWrapper alloc] initWithTab: tabViewItem andWindow: [self window]] autorelease];
[tabViewItem setLabel: NSLocalizedString(@"UntitledPageTitle", @"")];
[tabViewItem setView: newView];
[self addTabViewItem: tabViewItem];
[[tabViewItem view] loadURI: aURL referrer:aReferrer flags: NSLoadFlagsNone activate:NO];
}
#pragma mark -
+ (BrowserTabViewItem*)makeNewTabItem
{
return [[[BrowserTabViewItem alloc] init] autorelease];
}
@end

View File

@ -1,57 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
#import "CHIconTabViewItem.h"
// a subclass of CHIconTabViewItem that handles dragging of site icons
@class BrowserTabItemContainerView;
@interface BrowserTabViewItem : CHIconTabViewItem
{
NSRect mLastDrawRect; // cached draw rect, used for dragging location
BrowserTabItemContainerView* mTabContentsView;
BOOL mDraggable;
}
- (void)updateTabVisibility:(BOOL)nowVisible;
- (NSView*)tabItemContentsView;
- (void)setTabIcon:(NSImage *)newIcon isDraggable:(BOOL)draggable;
@end

View File

@ -1,557 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "BrowserTabViewItem.h"
#import "CHBrowserView.h"
#import "MainController.h"
#import "BrowserWindowController.h"
@interface BrowserTabViewItem(Private)
- (void)buildTabContents;
- (void)relocateTabContents:(NSRect)inRect;
- (BOOL)draggable;
@end
#pragma mark -
@interface NSBezierPath (ChimeraBezierPathUtils)
+ (NSBezierPath*)bezierPathWithRoundCorneredRect:(NSRect)rect cornerRadius:(float)cornerRadius;
@end
@implementation NSBezierPath (ChimeraBezierPathUtils)
+ (NSBezierPath*)bezierPathWithRoundCorneredRect:(NSRect)rect cornerRadius:(float)cornerRadius
{
float maxRadius = cornerRadius;
if (NSWidth(rect) / 2.0 < maxRadius)
maxRadius = NSWidth(rect) / 2.0;
if (NSHeight(rect) / 2.0 < maxRadius)
maxRadius = NSHeight(rect) / 2.0;
NSBezierPath* newPath = [NSBezierPath bezierPath];
[newPath moveToPoint:NSMakePoint(NSMinX(rect) + maxRadius, NSMinY(rect))];
[newPath appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect) - maxRadius, NSMinY(rect) + maxRadius)
radius:maxRadius startAngle:270.0 endAngle:0.0];
[newPath appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect) - maxRadius, NSMaxY(rect) - maxRadius)
radius:maxRadius startAngle:0.0 endAngle:90.0];
[newPath appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect) + maxRadius, NSMaxY(rect) - maxRadius)
radius:maxRadius startAngle:90.0 endAngle:180.0];
[newPath appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect) + maxRadius, NSMinY(rect) + maxRadius)
radius:maxRadius startAngle:180.0 endAngle:270.0];
[newPath closePath];
return newPath;
}
@end
#pragma mark -
// XXX move this to a new file
@interface NSTruncatingTextAndImageCell : NSCell
{
NSImage *mImage;
NSMutableString *mTruncLabelString;
int mLabelStringWidth; // -1 if not known
float mImagePadding;
float mImageSpace;
float mImageAlpha;
}
- (id)initTextCell:(NSString*)aString;
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView;
- (void)setImagePadding:(float)padding;
- (void)setImageSpace:(float)space;
- (void)setImageAlpha:(float)alpha;
- (void)setImage:(NSImage *)anImage;
- (NSImage *)image;
@end
@implementation NSTruncatingTextAndImageCell
- (id)initTextCell:(NSString*)aString
{
if ((self = [super initTextCell:aString]))
{
mLabelStringWidth = -1;
mImagePadding = 0;
mImageSpace = 2;
}
return self;
}
- (void)dealloc
{
[mImage release];
[mTruncLabelString release];
[super dealloc];
}
- copyWithZone:(NSZone *)zone
{
NSTruncatingTextAndImageCell *cell = (NSTruncatingTextAndImageCell *)[super copyWithZone:zone];
cell->mImage = [mImage retain];
cell->mTruncLabelString = nil;
cell->mLabelStringWidth = -1;
return cell;
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
NSRect textRect = cellFrame;
NSRect imageRect;
// we always reserve space for the image, even if there isn't one
// assume the image rect is always square
float imageWidth = NSHeight(cellFrame) - 2 * mImagePadding;
NSDivideRect(cellFrame, &imageRect, &textRect, imageWidth, NSMinXEdge);
if (mImage)
{
NSRect imageSrcRect = NSZeroRect;
imageSrcRect.size = [mImage size];
[mImage drawInRect:NSInsetRect(imageRect, mImagePadding, mImagePadding)
fromRect:imageSrcRect operation:NSCompositeSourceOver fraction:mImageAlpha];
}
// remove image space
NSDivideRect(textRect, &imageRect, &textRect, mImageSpace, NSMinXEdge);
int cellWidth = (int)NSWidth(textRect);
NSDictionary *cellAttributes = [[self attributedStringValue] attributesAtIndex:0 effectiveRange:nil];
if (mLabelStringWidth != cellWidth || !mTruncLabelString)
{
[mTruncLabelString release];
mTruncLabelString = [[NSMutableString alloc] initWithString:[self stringValue]];
[mTruncLabelString truncateToWidth:cellWidth at:kTruncateAtEnd withAttributes:cellAttributes];
mLabelStringWidth = cellWidth;
}
[mTruncLabelString drawInRect:textRect withAttributes:cellAttributes];
}
- (void)setStringValue:(NSString *)aString
{
if (![aString isEqualToString:[self stringValue]])
{
[mTruncLabelString release];
mTruncLabelString = nil;
}
[super setStringValue:aString];
}
- (void)setAttributedStringValue:(NSAttributedString *)attribStr
{
if (![attribStr isEqualToAttributedString:[self attributedStringValue]])
{
[mTruncLabelString release];
mTruncLabelString = nil;
}
[super setAttributedStringValue:attribStr];
}
- (void)setImage:(NSImage *)anImage
{
if (anImage != mImage)
{
[mImage release];
mImage = [anImage retain];
}
}
- (NSImage *)image
{
return mImage;
}
- (void)setImagePadding:(float)padding
{
mImagePadding = padding;
}
- (void)setImageSpace:(float)space
{
mImageSpace = space;
}
- (void)setImageAlpha:(float)alpha
{
mImageAlpha = alpha;
}
@end
#pragma mark -
// a container view for the items in the tab view item. We use a subclass of
// NSView to handle drag and drop
@interface BrowserTabItemContainerView : NSView
{
BrowserTabViewItem* mTabViewItem;
NSTruncatingTextAndImageCell* mLabelCell;
BOOL mIsDropTarget;
BOOL mSelectTabOnMouseUp;
}
- (NSTruncatingTextAndImageCell*)labelCell;
- (void)showDragDestinationIndicator;
- (void)hideDragDestinationIndicator;
@end
@implementation BrowserTabItemContainerView
- (id)initWithFrame:(NSRect)frameRect andTabItem:(NSTabViewItem*)tabViewItem
{
if ( (self = [super initWithFrame:frameRect]) )
{
mTabViewItem = tabViewItem;
mLabelCell = [[NSTruncatingTextAndImageCell alloc] init];
[mLabelCell setControlSize:NSSmallControlSize]; // doesn't work?
[mLabelCell setImagePadding:0.0];
[mLabelCell setImageSpace:2.0];
[self registerForDraggedTypes:[NSArray arrayWithObjects:
@"MozURLType", @"MozBookmarkType", NSStringPboardType, NSFilenamesPboardType, nil]];
}
return self;
}
- (void)dealloc
{
[mLabelCell release];
[super dealloc];
}
- (NSTruncatingTextAndImageCell*)labelCell
{
return mLabelCell;
}
- (void)drawRect:(NSRect)aRect
{
[mLabelCell drawWithFrame:[self bounds] inView:self];
if (mIsDropTarget)
{
NSRect hilightRect = NSOffsetRect(NSInsetRect([self bounds], 1.0, 0), -1.0, 0);
NSBezierPath* dropTargetOutline = [NSBezierPath bezierPathWithRoundCorneredRect:hilightRect cornerRadius:4.0];
[[NSColor colorWithCalibratedWhite:0.0 alpha:0.15] set];
[dropTargetOutline fill];
}
}
- (void)showDragDestinationIndicator
{
if (!mIsDropTarget)
{
mIsDropTarget = YES;
[self setNeedsDisplay:YES];
}
}
- (void)hideDragDestinationIndicator
{
if (mIsDropTarget)
{
mIsDropTarget = NO;
[self setNeedsDisplay:YES];
}
}
- (BOOL)shouldAcceptDragFrom:(id)sender
{
if ((sender == self) || (sender == mTabViewItem))
return NO;
NSWindowController *windowController = [[[mTabViewItem view] window] windowController];
if ([windowController isMemberOfClass:[BrowserWindowController class]])
{
if (sender == [windowController proxyIconView])
return NO;
}
return YES;
}
#pragma mark -
// NSDraggingDestination destination methods
- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
if (![self shouldAcceptDragFrom:[sender draggingSource]])
return NSDragOperationNone;
[self showDragDestinationIndicator];
return NSDragOperationGeneric;
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
if (![self shouldAcceptDragFrom:[sender draggingSource]]) {
[self hideDragDestinationIndicator];
return NSDragOperationNone;
}
[self showDragDestinationIndicator];
return NSDragOperationGeneric;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
[self hideDragDestinationIndicator];
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
[self hideDragDestinationIndicator];
if (![self shouldAcceptDragFrom:[sender draggingSource]])
return NO;
// let the tab view handle it
return [[mTabViewItem tabView] performDragOperation:sender];
}
#pragma mark -
// NSDraggingSource methods
- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)flag
{
return NSDragOperationGeneric;
}
// NSResponder methods
- (void)mouseDown:(NSEvent *)theEvent
{
NSRect iconRect = NSMakeRect(0, 0, 16, 16);
NSPoint localPoint = [self convertPoint: [theEvent locationInWindow] fromView: nil];
// this is a bit evil. Because the tab view's mouseDown captures the mouse, we'll
// never get to mouseDragged if we allow the next responder (the tab view) to
// handle the mouseDown. This prevents dragging from background tabs. So we break
// things slightly by intercepting the mouseDown on the icon, so that our mouseDragged
// gets called. If the users didn't drag, we select the tab in the mouse up.
if (NSPointInRect(localPoint, iconRect) && [mTabViewItem draggable])
{
mSelectTabOnMouseUp = YES;
return; // we want dragging
}
mSelectTabOnMouseUp = NO;
[[self nextResponder] mouseDown:theEvent];
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (mSelectTabOnMouseUp)
{
[[mTabViewItem tabView] selectTabViewItem:mTabViewItem];
mSelectTabOnMouseUp = NO;
}
[[self nextResponder] mouseUp:theEvent];
}
- (void)mouseDragged:(NSEvent*)theEvent
{
NSRect iconRect = NSMakeRect(0, 0, 16, 16);
NSPoint localPoint = [self convertPoint: [theEvent locationInWindow] fromView: nil];
if (!NSPointInRect(localPoint, iconRect) || ![mTabViewItem draggable])
{
[[self nextResponder] mouseDragged:theEvent];
return;
}
mSelectTabOnMouseUp = NO;
CHBrowserView* browserView = (CHBrowserView*)[mTabViewItem view];
NSString *url = [browserView getCurrentURLSpec];
NSString *title = [mLabelCell stringValue];
NSString *cleanedTitle = [title stringByReplacingCharactersInSet:[NSCharacterSet controlCharacterSet] withString:@" "];
NSArray *dataVals = [NSArray arrayWithObjects: url, cleanedTitle, nil];
NSArray *dataKeys = [NSArray arrayWithObjects: @"url", @"title", nil];
NSDictionary *data = [NSDictionary dictionaryWithObjects:dataVals forKeys:dataKeys];
NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObjects:@"MozURLType", NSURLPboardType, NSStringPboardType, nil] owner:self];
// MozURLType
[pboard setPropertyList:data forType: @"MozURLType"];
// NSURLPboardType type
[[NSURL URLWithString:url] writeToPasteboard: pboard];
// NSStringPboardType
[pboard setString:url forType: NSStringPboardType];
NSPoint dragOrigin = [self frame].origin;
dragOrigin.y += [self frame].size.height;
[self dragImage: [MainController createImageForDragging:[mLabelCell image] title:title]
at:NSMakePoint(0, 0) offset:NSMakeSize(0, 0)
event:theEvent pasteboard:pboard source:self slideBack:YES];
}
@end
#pragma mark -
@implementation BrowserTabViewItem
-(id)initWithIdentifier:(id)identifier withTabIcon:(NSImage *)tabIcon
{
if ( (self = [super initWithIdentifier:identifier withTabIcon:tabIcon]) )
{
mTabContentsView = [[BrowserTabItemContainerView alloc]
initWithFrame:NSMakeRect(0, 0, 100, 16) andTabItem:self];
mDraggable = NO;
}
return self;
}
-(id)initWithIdentifier:(id)identifier
{
return [self initWithIdentifier:identifier withTabIcon:nil];
}
-(void)dealloc
{
// We can either be closing a single tab here, in which case we need to remove our view
// from the superview, or the tab view may be closing, in which case it has already
// removed all its subviews.
[mTabContentsView removeFromSuperview]; // may be noop
[mTabContentsView release]; // balance our init
[super dealloc];
}
- (NSView*)tabItemContentsView
{
return mTabContentsView;
}
- (void)updateTabVisibility:(BOOL)nowVisible
{
if (nowVisible)
{
if (![mTabContentsView superview])
[[self tabView] addSubview:mTabContentsView];
}
else
{
if ([mTabContentsView superview])
[mTabContentsView removeFromSuperview];
}
}
- (void)relocateTabContents:(NSRect)inRect
{
[mTabContentsView setFrame:inRect];
}
- (BOOL)draggable
{
return mDraggable;
}
-(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect
{
[self relocateTabContents:tabRect];
mLastDrawRect = tabRect;
}
- (NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel
{
return [super sizeOfLabel:shouldTruncateLabel];
}
- (void)setLabel:(NSString *)label
{
NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:label attributes:mLabelAttributes];
[[mTabContentsView labelCell] setAttributedStringValue:labelString];
[super setLabel:label];
}
- (NSString*)label
{
return [[mTabContentsView labelCell] stringValue];
}
-(void)setTabIcon:(NSImage *)newIcon
{
[super setTabIcon:newIcon];
[[mTabContentsView labelCell] setImage:mTabIcon];
}
- (void)setTabIcon:(NSImage *)newIcon isDraggable:(BOOL)draggable
{
[self setTabIcon:newIcon];
mDraggable = draggable;
[[mTabContentsView labelCell] setImageAlpha:(draggable ? 1.0 : 0.6)];
}
@end

View File

@ -1,46 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
@interface BrowserWindow : NSWindow
{
IBOutlet id mAutoCompleteTextField;
}
-(BOOL) makeFirstResponder:(NSResponder*) responder;
@end

View File

@ -1,66 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "BrowserWindow.h"
#import "BrowserWindowController.h"
#import "CHAutoCompleteTextField.h"
static const int kEscapeKeyCode = 53;
@implementation BrowserWindow
- (BOOL)makeFirstResponder:(NSResponder*)responder
{
NSResponder* oldResponder = [self firstResponder];
BOOL madeFirstResponder = [super makeFirstResponder:responder];
if (madeFirstResponder && oldResponder != [self firstResponder])
[(BrowserWindowController*)[self delegate] focusChangedFrom:oldResponder to:[self firstResponder]];
return madeFirstResponder;
}
- (void)sendEvent:(NSEvent *)theEvent
{
// We need this hack because NSWindow::sendEvent will eat the escape key
// and won't pass it down to the key handler of responders in the window.
// We have to override sendEvent for all of our escape key needs.
if ([theEvent keyCode] == kEscapeKeyCode && [theEvent type] == NSKeyDown && [self firstResponder] == [mAutoCompleteTextField fieldEditor])
[mAutoCompleteTextField revertText];
else
[super sendEvent:theEvent];
}
@end

View File

@ -1,162 +0,0 @@
{
IBClasses = (
{CLASS = BookmarkItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {
addBookmark = id;
addFolder = id;
deleteBookmarks = id;
openBookmarkInNewTab = id;
openBookmarkInNewWindow = id;
showBookmarkInfo = id;
};
CLASS = BookmarksDataSource;
LANGUAGE = ObjC;
OUTLETS = {
mBrowserWindowController = id;
mDeleteBookmarkButton = id;
mEditBookmarkButton = id;
mOutlineView = id;
};
SUPERCLASS = NSObject;
},
{CLASS = BookmarksToolbar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{CLASS = BrowserTabView; LANGUAGE = ObjC; SUPERCLASS = NSTabView; },
{
CLASS = BrowserWindow;
LANGUAGE = ObjC;
OUTLETS = {mAutoCompleteTextField = id; };
SUPERCLASS = NSWindow;
},
{
ACTIONS = {
back = id;
bookmarkLink = id;
bookmarkPage = id;
cancelAddBookmarkSheet = id;
cancelLocationSheet = id;
copyLinkLocation = id;
endAddBookmarkSheet = id;
endLocationSheet = id;
forward = id;
goToLocationFromToolbarURLField = id;
home = id;
manageBookmarks = id;
openLinkInNewTab = id;
openLinkInNewWindow = id;
performSearch = id;
printDocument = id;
reload = id;
saveImageAs = id;
saveLinkAs = id;
savePageAs = id;
stop = id;
toggleSidebar = id;
viewOnlyThisImage = id;
viewSource = id;
};
CLASS = BrowserWindowController;
LANGUAGE = ObjC;
OUTLETS = {
mAddBookmarkCheckbox = NSButton;
mAddBookmarkFolderField = NSPopUpButton;
mAddBookmarkSheetWindow = NSWindow;
mAddBookmarkTitleField = NSTextField;
mBackItem = NSMenuItem;
mCachedBMDS = id;
mForwardItem = NSMenuItem;
mHistoryDataSource = CHHistoryDataSource;
mImageLinkMenu = NSMenu;
mImageMenu = NSMenu;
mInputMenu = NSMenu;
mLinkMenu = NSMenu;
mLocationSheetURLField = NSTextField;
mLocationSheetWindow = NSWindow;
mLocationToolbarView = NSView;
mLock = NSImageView;
mPageMenu = NSMenu;
mPersonalToolbar = CHBookmarksToolbar;
mProgress = NSProgressIndicator;
mProxyIcon = NSImageView;
mSidebarBookmarksDataSource = BookmarksDataSource;
mSidebarBrowserView = id;
mSidebarDrawer = NSDrawer;
mSidebarSourceTabView = NSTabView;
mSidebarTabView = NSTabView;
mStatus = NSTextField;
mStatusBar = NSView;
mTabBrowser = CHExtendedTabView;
mURLBar = NSTextField;
};
SUPERCLASS = NSWindowController;
},
{CLASS = CHAutoCompleteDataSource; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {onBlur = id; onResize = id; };
CLASS = CHAutoCompleteTextField;
LANGUAGE = ObjC;
OUTLETS = {mProxyIcon = CHPageProxyIcon; };
SUPERCLASS = NSTextField;
},
{
CLASS = CHBookmarksOutlineView;
LANGUAGE = ObjC;
SUPERCLASS = CHExtendedOutlineView;
},
{CLASS = CHBookmarksToolbar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{
ACTIONS = {load = id; };
CLASS = CHBrowserWrapper;
LANGUAGE = ObjC;
OUTLETS = {
mLockIcon = id;
mWindowController = id;
progress = id;
progressSuper = id;
status = id;
urlbar = id;
};
SUPERCLASS = NSView;
},
{CLASS = CHExtendedOutlineView; LANGUAGE = ObjC; SUPERCLASS = NSOutlineView; },
{
CLASS = CHHistoryDataSource;
LANGUAGE = ObjC;
OUTLETS = {mBrowserWindowController = id; };
SUPERCLASS = CHRDFOutlineViewDataSource;
},
{CLASS = CHLocationBar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{CLASS = CHPageProxyIcon; LANGUAGE = ObjC; SUPERCLASS = NSImageView; },
{
CLASS = CHRDFOutlineViewDataSource;
LANGUAGE = ObjC;
OUTLETS = {mOutlineView = id; };
SUPERCLASS = NSObject;
},
{CLASS = ExtendedOutlineView; LANGUAGE = ObjC; SUPERCLASS = NSOutlineView; },
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = LocationBar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{CLASS = MainController; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {load = id; };
CLASS = MyBrowserView;
LANGUAGE = ObjC;
OUTLETS = {
mImageLinkMenu = id;
mImageMenu = id;
mInputMenu = id;
mLinkMenu = id;
mPageMenu = id;
mWindowController = id;
progress = id;
progressSuper = id;
status = id;
urlbar = id;
};
SUPERCLASS = NSView;
},
{CLASS = RDFOutlineViewItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = ThrobberHandler; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,49 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>176 79 632 495 0 0 1280 1002 </string>
<key>IBEditorPositions</key>
<dict>
<key>124</key>
<string>345 803 170 144 0 0 1280 1002 </string>
<key>160</key>
<string>524 326 195 666 0 0 1280 1002 </string>
<key>28</key>
<string>524 439 195 457 0 0 1280 1002 </string>
<key>297</key>
<string>233 646 176 162 0 0 1152 848 </string>
<key>314</key>
<string>418 732 139 66 0 0 1152 848 </string>
<key>336</key>
<string>630 666 200 132 0 0 1152 848 </string>
<key>365</key>
<string>22 587 93 162 0 0 1152 848 </string>
<key>463</key>
<string>22 619 200 180 0 0 1152 848 </string>
<key>56</key>
<string>450 634 343 68 0 0 1280 1002 </string>
</dict>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBGroupedObjects</key>
<dict>
<key>3</key>
<array>
<string>8</string>
<string>9</string>
</array>
</dict>
<key>IBLastGroupID</key>
<string>4</string>
<key>IBLockedObjects</key>
<array/>
<key>IBOpenObjects</key>
<array>
<integer>10</integer>
</array>
<key>IBSystem Version</key>
<string>5S60</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,285 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
#import "CHBrowserWrapper.h"
#import "CHFind.h"
#import "CHBookmarksToolbar.h"
class nsIDOMEvent;
class nsIDOMNode;
//
// ThrobberHandler
//
// A helper class that handles animating the throbber when it's alive. It starts
// automatically when you init it. To get it to stop, call |stopThrobber|. Calling
// |release| is not enough because the timer used to animate the images holds a strong
// ref back to the handler so it won't go away unless you break that cycle manually with
// |stopThrobber|.
//
// This class must be separate from BrowserWindowController else the
// same thing will happen there and the timer will cause it to stay alive and continue
// loading the webpage even though the window has gone away.
//
@interface ThrobberHandler : NSObject
{
NSTimer* mTimer;
NSArray* mImages;
unsigned int mFrame;
}
// public
- (id)initWithToolbarItem:(NSToolbarItem*)inButton images:(NSArray*)inImages;
- (void)stopThrobber;
// internal
- (void)startThrobber;
- (void)pulseThrobber:(id)aSender;
@end
@class BookmarksDataSource;
@class CHHistoryDataSource;
@class BrowserTabView;
@class CHPageProxyIcon;
@interface BrowserWindowController : NSWindowController<CHFind>
{
IBOutlet BrowserTabView* mTabBrowser;
IBOutlet NSDrawer* mSidebarDrawer;
IBOutlet NSTabView* mSidebarTabView;
IBOutlet NSTabView* mSidebarSourceTabView;
IBOutlet NSView* mLocationToolbarView;
IBOutlet NSTextField* mURLBar;
IBOutlet NSTextField* mStatus;
IBOutlet NSProgressIndicator* mProgress;
IBOutlet NSImageView* mLock;
IBOutlet NSWindow* mLocationSheetWindow;
IBOutlet NSTextField* mLocationSheetURLField;
IBOutlet NSView* mStatusBar; // contains the status text, progress bar, and lock
IBOutlet CHPageProxyIcon* mProxyIcon;
IBOutlet id mSidebarBrowserView; // currently unused
IBOutlet BookmarksDataSource* mSidebarBookmarksDataSource;
IBOutlet CHHistoryDataSource* mHistoryDataSource;
IBOutlet CHBookmarksToolbar* mPersonalToolbar;
IBOutlet NSWindow* mAddBookmarkSheetWindow;
IBOutlet NSTextField* mAddBookmarkTitleField;
IBOutlet NSPopUpButton* mAddBookmarkFolderField;
IBOutlet NSButton* mAddBookmarkCheckbox;
// Context menu outlets.
IBOutlet NSMenu* mPageMenu;
IBOutlet NSMenu* mImageMenu;
IBOutlet NSMenu* mInputMenu;
IBOutlet NSMenu* mLinkMenu;
IBOutlet NSMenu* mImageLinkMenu;
// Context menu item outlets
IBOutlet NSMenuItem* mBackItem;
IBOutlet NSMenuItem* mForwardItem;
NSToolbarItem* mSidebarToolbarItem;
BOOL mInitialized;
NSString* mPendingURL;
NSString* mPendingReferrer;
BOOL mPendingActivate;
CHBrowserWrapper* mBrowserView;
BOOL mMoveReentrant;
NSModalSession mModalSession;
BOOL mShouldAutosave;
BOOL mShouldLoadHomePage;
BOOL mDrawerCachedFrame;
NSRect mCachedFrameBeforeDrawerOpen; // This is used by the drawer to figure out if the window should
// be returned to its original position when the drawer closes.
NSRect mCachedFrameAfterDrawerOpen;
unsigned int mChromeMask; // Indicates which parts of the window to show (e.g., don't show toolbars)
// Context menu members.
int mContextMenuFlags;
nsIDOMEvent* mContextMenuEvent;
nsIDOMNode* mContextMenuNode;
// Cached bookmark ds used when adding through a sheet
id mCachedBMDS;
// Throbber state variables.
ThrobberHandler* mThrobberHandler;
NSArray* mThrobberImages;
// Funky field editor for URL bar
NSTextView *mURLFieldEditor;
}
- (void)dealloc;
- (id)getTabBrowser;
- (BOOL)newTabsAllowed;
- (CHBrowserWrapper*)getBrowserWrapper;
- (void)loadURL:(NSString*)aURLSpec referrer:(NSString*)aReferrer activate:(BOOL)activate;
- (void)updateLocationFields:(NSString *)locationString;
- (void)updateSiteIcons:(NSImage *)siteIconImage;
- (void)updateToolbarItems;
- (void)focusURLBar;
// call to update the image of the lock icon with a value from nsIWebProgressListener
- (void)updateLock:(unsigned int)securityState;
- (void)performAppropriateLocationAction;
- (IBAction)goToLocationFromToolbarURLField:(id)sender;
- (void)beginLocationSheet;
- (IBAction)endLocationSheet:(id)sender;
- (IBAction)cancelLocationSheet:(id)sender;
- (IBAction)cancelAddBookmarkSheet:(id)sender;
- (IBAction)endAddBookmarkSheet:(id)sender;
- (void)cacheBookmarkDS: (id)aDS;
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize;
- (IBAction)viewSource:(id)aSender;
- (void)saveDocument: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList;
- (void)saveURL: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList
url: (NSString*)aURLSpec suggestedFilename: (NSString*)aFilename;
- (IBAction)printDocument:(id)aSender;
- (void)printPreview;
- (IBAction)performSearch:(id)aSender;
- (void)startThrobber;
- (void)stopThrobber;
- (void)clickThrobber:(id)aSender;
- (void)biggerTextSize;
- (void)smallerTextSize;
- (void)getInfo:(id)sender;
- (BOOL)canGetInfo;
- (BOOL)shouldShowBookmarkToolbar;
- (void)addBookmarkExtended: (BOOL)aIsFromMenu isFolder:(BOOL)aIsFolder URL:(NSString*)aURL title:(NSString*)aTitle;
- (IBAction)manageBookmarks: (id)aSender;
- (void)importBookmarks: (NSString*)aURLSpec;
- (IBAction)toggleSidebar:(id)aSender;
- (BOOL)bookmarksAreVisible:(BOOL)inRequireSelection;
- (void)newTab:(BOOL)allowHomepage;
- (void)closeTab;
- (void)previousTab;
- (void)nextTab;
- (IBAction)back:(id)aSender;
- (IBAction)forward:(id)aSender;
- (IBAction)reload:(id)aSender;
- (IBAction)stop:(id)aSender;
- (IBAction)home:(id)aSender;
-(void)enterModalSession;
-(void)openNewWindowWithURL: (NSString*)aURLSpec referrer:(NSString*)aReferrer loadInBackground: (BOOL)aLoadInBG;
-(void)openNewWindowWithGroup: (nsIDOMElement*)aFolderElement loadInBackground: (BOOL)aLoadInBG;
-(void)openNewTabWithURL: (NSString*)aURLSpec referrer: (NSString*)aReferrer loadInBackground: (BOOL)aLoadInBG;
-(void)autosaveWindowFrame;
-(void)disableAutosave;
-(void)disableLoadPage;
-(void)setChromeMask:(unsigned int)aMask;
-(unsigned int)chromeMask;
-(id)getAddBookmarkSheetWindow;
-(id)getAddBookmarkTitle;
-(id)getAddBookmarkFolder;
-(id)getAddBookmarkCheckbox;
// Called when a context menu should be shown.
- (void)onShowContextMenu:(int)flags domEvent:(nsIDOMEvent*)aEvent domNode:(nsIDOMNode*)aNode;
- (NSMenu*)getContextMenu;
// Context menu methods
- (IBAction)openLinkInNewWindow:(id)aSender;
- (IBAction)openLinkInNewTab:(id)aSender;
- (void)openLinkInNewWindowOrTab: (BOOL)aUseWindow;
- (IBAction)savePageAs:(id)aSender;
- (IBAction)saveLinkAs:(id)aSender;
- (IBAction)saveImageAs:(id)aSender;
- (IBAction)bookmarkPage: (id)aSender;
- (IBAction)bookmarkLink: (id)aSender;
- (IBAction)copyLinkLocation:(id)aSender;
- (IBAction)viewOnlyThisImage:(id)aSender;
- (CHBookmarksToolbar*) bookmarksToolbar;
- (BOOL) isResponderGeckoView:(NSResponder*) responder;
// called when the internal window focus has changed
// this allows us to dispatch activate and deactivate events as necessary
- (void) focusChangedFrom:(NSResponder*) oldResponder to:(NSResponder*) newResponder;
// Called to get cached versions of our security icons
+ (NSImage*) insecureIcon;
+ (NSImage*) secureIcon;
+ (NSImage*) brokenIcon;
// cache the toolbar defaults we parse from a plist
+ (NSArray*) toolbarDefaults;
// Accessor to get the sidebar drawer
- (NSDrawer *)sidebarDrawer;
// Accessor to get the proxy icon view
- (CHPageProxyIcon *)proxyIconView;
@end

File diff suppressed because it is too large Load Diff

View File

@ -1,56 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Matt Judy
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <Appkit/Appkit.h>
@interface CHAboutBox : NSObject
{
IBOutlet NSTextView* creditsField;
IBOutlet NSTextField* buildNumberField;
IBOutlet NSWindow* window;
NSTimer *scrollTimer;
float currentPosition;
float maxScrollHeight;
NSTimeInterval startTime;
BOOL restartAtTop;
}
+ (CHAboutBox *)sharedInstance;
- (IBAction)showPanel:(id)sender;
@end

View File

@ -1,154 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Matt Judy
* David Hyatt <hyatt@netscape.com>
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "CHAboutBox.h"
#include "nsBuildID.h"
@interface CHAboutBox(Private)
- (void)loadWindow;
@end
@implementation CHAboutBox
static CHAboutBox *sharedInstance = nil;
+ (CHAboutBox *)sharedInstance
{
return sharedInstance ? sharedInstance : [[self alloc] init];
}
- (id)init
{
if (sharedInstance) {
[self dealloc];
} else {
sharedInstance = [super init];
}
return sharedInstance;
}
- (IBAction)showPanel:(id)sender
{
if (!creditsField) {
[self loadWindow];
}
if (![window isVisible]) {
currentPosition = 0;
restartAtTop = NO;
startTime = [NSDate timeIntervalSinceReferenceDate] + 3.0;
[creditsField scrollPoint:NSMakePoint( 0, 0 )];
}
[window makeKeyAndOrderFront:nil];
}
- (void)windowDidBecomeKey:(NSNotification *)notification
{
scrollTimer = [NSTimer scheduledTimerWithTimeInterval:0.03
target:self
selector:@selector(scrollCredits:)
userInfo:nil
repeats:YES];
}
- (void)windowDidResignKey:(NSNotification *)notification
{
[scrollTimer invalidate];
}
- (void)scrollCredits:(NSTimer *)timer
{
if ([NSDate timeIntervalSinceReferenceDate] >= startTime)
{
if (restartAtTop) {
startTime = [NSDate timeIntervalSinceReferenceDate] + 3.0;
restartAtTop = NO;
[creditsField scrollPoint:NSMakePoint( 0, 0 )];
return;
}
if (currentPosition >= maxScrollHeight) {
startTime = [NSDate timeIntervalSinceReferenceDate] + 3.0;
currentPosition = 0;
restartAtTop = YES;
} else {
[creditsField scrollPoint:NSMakePoint( 0, currentPosition )];
currentPosition += 1;
}
}
}
- (void)loadWindow
{
NSString *creditsPath;
NSAttributedString *creditsString;
float fieldHeight;
float containerHeight;
if (![NSBundle loadNibNamed:@"AboutBox" owner:self]) {
NSLog( @"Failed to load AboutBox.nib" );
NSBeep();
return;
}
[window setTitle:[NSString stringWithFormat: @"About %@", NSLocalizedStringFromTable(@"CFBundleName", @"InfoPlist", nil)]];
creditsPath = [[NSBundle mainBundle] pathForResource:@"Credits" ofType:@"rtf"];
creditsString = [[NSAttributedString alloc] initWithPath:creditsPath documentAttributes:nil];
[creditsField replaceCharactersInRange:NSMakeRange( 0, 0 )
withRTF:[creditsString RTFFromRange:
NSMakeRange( 0, [creditsString length] )
documentAttributes:nil]];
fieldHeight = [creditsField frame].size.height;
(void)[[creditsField layoutManager] glyphRangeForTextContainer:[creditsField textContainer]];
containerHeight = [[creditsField layoutManager] usedRectForTextContainer:
[creditsField textContainer]].size.height;
maxScrollHeight = containerHeight - fieldHeight;
[buildNumberField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"BuildID", @""), NS_BUILD_ID]];
[window setExcludedFromWindowsMenu:YES];
[window setMenu:nil];
[window center];
}
@end

View File

@ -1,49 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import <AppKit/AppKit.h>
#import "CHAutoCompleteTextField.h"
#include "nsIAutoCompleteResults.h"
@class CHAutoCompleteTextField;
@interface CHAutoCompleteDataSource : NSObject
{
NSImage *mIconImage;
NSString* mErrorMessage;
nsIAutoCompleteResults *mResults;
}
- (id) init;
- (int) rowCount;
- (id) resultString:(int)aRow column:(NSString *)aColumn;
- (void) setErrorMessage: (NSString*) error;
- (NSString*) errorMessage;
- (void) setResults: (nsIAutoCompleteResults*) results;
- (nsIAutoCompleteResults*) results;
@end

View File

@ -1,127 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*
*/
#import "NSString+Utils.h"
#import <AppKit/AppKit.h>
#import "CHAutoCompleteTextField.h"
#include "nsString.h"
#include "nsCRT.h"
@implementation CHAutoCompleteDataSource
-(id)init
{
if ((self = [super init])) {
mResults = nil;
mIconImage = [NSImage imageNamed:@"globe_ico"];
}
return self;
}
-(void)dealloc
{
NS_IF_RELEASE(mResults);
[super dealloc];
}
- (void) setErrorMessage: (NSString*) error
{
[self setResults:nsnull];
mErrorMessage = error;
}
- (NSString*) errorMessage
{
return mErrorMessage;
}
- (void) setResults:(nsIAutoCompleteResults*)aResults
{
NS_IF_RELEASE(mResults);
mErrorMessage = nil;
mResults = aResults;
NS_IF_ADDREF(mResults);
}
- (nsIAutoCompleteResults *) results
{
return mResults;
}
- (int) rowCount
{
if (!mResults)
return 0;
nsCOMPtr<nsISupportsArray> items;
mResults->GetItems(getter_AddRefs(items));
PRUint32 count;
items->Count(&count);
return count;
}
- (id) resultString:(int)aRow column:(NSString *)aColumn
{
NSString *result = @"";
if (!mResults)
return result;
nsCOMPtr<nsISupportsArray> items;
mResults->GetItems(getter_AddRefs(items));
nsCOMPtr<nsISupports> itemSupports = dont_AddRef(items->ElementAt(aRow));
nsCOMPtr<nsIAutoCompleteItem> item = do_QueryInterface(itemSupports);
if (!item)
return result;
if ([aColumn isEqualToString:@"icon"]) {
return mIconImage;
} else if ([aColumn isEqualToString:@"col1"]) {
nsAutoString value;
item->GetValue(value);
result = [NSString stringWith_nsAString:value];
} else if ([aColumn isEqualToString:@"col2"]) {
nsXPIDLString commentStr;
item->GetComment(getter_Copies(commentStr));
result = [NSString stringWith_nsAString:commentStr];
}
return result;
}
-(int) numberOfRowsInTableView:(NSTableView*)aTableView
{
return [self rowCount];
}
-(id)tableView:(NSTableView*)aTableView objectValueForTableColumn:(NSTableColumn*)aTableColumn row:(int)aRowIndex
{
return [self resultString:aRowIndex column:[aTableColumn identifier]];
}
@end

View File

@ -1,93 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*/
#import <AppKit/AppKit.h>
#import "CHAutoCompleteDataSource.h"
#include "nsIAutoCompleteSession.h"
#include "nsIAutoCompleteResults.h"
#include "nsIAutoCompleteListener.h"
@class CHAutoCompleteDataSource, CHPageProxyIcon;
@interface CHAutoCompleteTextField : NSTextField
{
IBOutlet CHPageProxyIcon *mProxyIcon;
NSWindow *mPopupWin;
NSTableView *mTableView;
CHAutoCompleteDataSource *mDataSource;
nsIAutoCompleteSession *mSession;
nsIAutoCompleteResults *mResults;
nsIAutoCompleteListener *mListener;
NSString *mSearchString;
// used to remember if backspace was pressed in complete: so we can check this in controlTextDidChange
BOOL mBackspaced;
// determines if the search currently pending should complete the default result when it is ready
BOOL mCompleteResult;
// should the autocomplete fill in the default completion into the text field? The default
// is no, but this can be set with a user default pref.
BOOL mCompleteWhileTyping;
NSTimer *mOpenTimer;
}
- (void) setSession:(NSString *)aSession;
- (NSString *) session;
- (void) setPageProxyIcon:(NSImage *)aImage;
- (NSTableView *) tableView;
- (int) visibleRows;
- (void) startSearch:(NSString*)aString complete:(BOOL)aComplete;
- (void) performSearch;
- (void) dataReady:(nsIAutoCompleteResults*)aResults status:(AutoCompleteStatus)aStatus;
- (void) searchTimer:(NSTimer *)aTimer;
- (void) clearResults;
- (void) completeDefaultResult;
- (void) completeSelectedResult;
- (void) completeResult:(int)aRow;
- (void) enterResult:(int)aRow;
- (void) revertText;
- (void) selectRowAt:(int)aRow;
- (void) selectRowBy:(int)aRows;
- (void) openPopup;
- (void) closePopup;
- (void) resizePopup;
- (BOOL) isOpen;
- (void) onRowClicked:(NSNotification *)aNote;
- (void) onBlur:(NSNotification *)aNote;
- (void) onResize:(NSNotification *)aNote;
- (void) onUndoOrRedo:(NSNotification *)aNote;
- (void) setStringUndoably:(NSString*)aString fromLocation:(unsigned int)aLocation;
- (id) fieldEditor;
@end

View File

@ -1,588 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*/
#import "CHAutoCompleteTextField.h"
#import "BrowserWindowController.h"
#import "CHPageProxyIcon.h"
#include "nsIServiceManager.h"
#include "nsMemory.h"
#include "nsString.h"
#include "CHUserDefaults.h"
static const int kMaxRows = 6;
static const int kFrameMargin = 1;
@interface AutoCompleteWindow : NSWindow
- (BOOL)isKeyWindow;
@end
@implementation AutoCompleteWindow
- (BOOL)isKeyWindow
{
return YES;
}
@end
class AutoCompleteListener : public nsIAutoCompleteListener
{
public:
AutoCompleteListener(CHAutoCompleteTextField* aTextField)
{
NS_INIT_REFCNT();
mTextField = aTextField;
}
NS_DECL_ISUPPORTS
NS_IMETHODIMP OnStatus(const PRUnichar* aText) { return NS_OK; }
NS_IMETHODIMP SetParam(nsISupports *aParam) { return NS_OK; }
NS_IMETHODIMP GetParam(nsISupports **aParam) { return NS_OK; }
NS_IMETHODIMP OnAutoComplete(nsIAutoCompleteResults *aResults, AutoCompleteStatus aStatus)
{
[mTextField dataReady:aResults status:aStatus];
return NS_OK;
}
private:
CHAutoCompleteTextField *mTextField;
};
NS_IMPL_ISUPPORTS1(AutoCompleteListener, nsIAutoCompleteListener)
////////////////////////////////////////////////////////////////////////
@implementation CHAutoCompleteTextField
- (void) awakeFromNib
{
NSTableColumn *column;
NSScrollView *scrollView;
NSCell *dataCell;
mSearchString = nil;
mBackspaced = NO;
mCompleteResult = NO;
mOpenTimer = nil;
mSession = nsnull;
mResults = nsnull;
mListener = (nsIAutoCompleteListener *)new AutoCompleteListener(self);
NS_IF_ADDREF(mListener);
[self setFont:[NSFont controlContentFontOfSize:0]];
[self setDelegate: self];
// XXX the owner of the textfield should set this
[self setSession:@"history"];
// construct and configure the popup window
mPopupWin = [[AutoCompleteWindow alloc] initWithContentRect:NSMakeRect(0,0,0,0)
styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
[mPopupWin setReleasedWhenClosed:NO];
[mPopupWin setLevel:NSFloatingWindowLevel];
[mPopupWin setHasShadow:YES];
[mPopupWin setAlphaValue:0.9];
// construct and configure the view
mTableView = [[[NSTableView alloc] initWithFrame:NSMakeRect(0,0,0,0)] autorelease];
[mTableView setIntercellSpacing:NSMakeSize(1, 2)];
[mTableView setTarget:self];
[mTableView setAction:@selector(onRowClicked:)];
// Create the icon column if we have a proxy icon
if (mProxyIcon) {
column = [[[NSTableColumn alloc] initWithIdentifier:@"icon"] autorelease];
[column setWidth:[mProxyIcon frame].origin.x + [mProxyIcon frame].size.width];
dataCell = [[[NSImageCell alloc] initImageCell:nil] autorelease];
[column setDataCell:dataCell];
[mTableView addTableColumn: column];
}
// create the text columns
column = [[[NSTableColumn alloc] initWithIdentifier:@"col1"] autorelease];
[mTableView addTableColumn: column];
column = [[[NSTableColumn alloc] initWithIdentifier:@"col2"] autorelease];
[[column dataCell] setTextColor:[NSColor darkGrayColor]];
[mTableView addTableColumn: column];
// hide the table header
[mTableView setHeaderView:nil];
// construct the scroll view that contains the table view
scrollView = [[[NSScrollView alloc] initWithFrame:NSMakeRect(0,0,0,0)] autorelease];
[scrollView setHasVerticalScroller:YES];
[[scrollView verticalScroller] setControlSize:NSSmallControlSize];
[scrollView setDocumentView: mTableView];
// construct the datasource
mDataSource = [[CHAutoCompleteDataSource alloc] init];
[mTableView setDataSource: mDataSource];
[mPopupWin setContentView:scrollView];
// listen for when window resigns from key handling
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onBlur:)
name:NSWindowDidResignKeyNotification object:nil];
// listen for when window is about to be moved or resized
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onBlur:)
name:NSWindowWillMoveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResize:)
name:NSWindowDidResizeNotification object:nil];
// listen for Undo/Redo to make sure autocomplete doesn't get horked.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUndoOrRedo:)
name:NSUndoManagerDidRedoChangeNotification
object:[[self fieldEditor] undoManager]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUndoOrRedo:)
name:NSUndoManagerDidUndoChangeNotification
object:[[self fieldEditor] undoManager]];
// read the user default on if we should auto-complete the text field as the user
// types or make them pick something from a list (a-la mozilla).
mCompleteWhileTyping = [[NSUserDefaults standardUserDefaults] boolForKey:USER_DEFAULTS_AUTOCOMPLETE_WHILE_TYPING];
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (mSearchString)
[mSearchString release];
[mPopupWin release];
[mDataSource release];
NS_IF_RELEASE(mSession);
NS_IF_RELEASE(mResults);
NS_IF_RELEASE(mListener);
[super dealloc];
}
- (void) setSession:(NSString *)aSession
{
NS_IF_RELEASE(mSession);
// XXX add aSession to contract id
nsCOMPtr<nsIAutoCompleteSession> session =
do_GetService("@mozilla.org/autocompleteSession;1?type=history");
mSession = session;
NS_IF_ADDREF(mSession);
}
- (NSString *) session
{
// XXX return session name
return @"";
}
- (NSTableView *) tableView
{
return mTableView;
}
- (int) visibleRows
{
int minRows = [mDataSource rowCount];
return minRows < kMaxRows ? minRows : kMaxRows;
}
- (void) setPageProxyIcon:(NSImage *)aImage
{
[mProxyIcon setImage:aImage];
}
-(id) fieldEditor
{
return [[self window] fieldEditor:NO forObject:self];
}
// searching ////////////////////////////
- (void) startSearch:(NSString*)aString complete:(BOOL)aComplete
{
if (mSearchString)
[mSearchString release];
mSearchString = [aString retain];
mCompleteResult = aComplete;
if ([self isOpen]) {
[self performSearch];
} else {
// delay the search when the popup is not yet opened so that users
// don't see a jerky flashing popup when they start typing for the first time
if (mOpenTimer) {
[mOpenTimer invalidate];
[mOpenTimer release];
}
mOpenTimer = [[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(searchTimer:)
userInfo:nil repeats:NO] retain];
}
}
- (void) performSearch
{
PRUnichar* chars = nsMemory::Alloc(([mSearchString length]+1) * sizeof(PRUnichar));
[mSearchString getCharacters:chars];
chars[[mSearchString length]] = 0; // I shouldn't have to do this
nsresult rv = mSession->OnStartLookup(chars, mResults, mListener);
nsMemory::Free(chars);
if (NS_FAILED(rv))
NSLog(@"Unable to perform autocomplete lookup");
}
- (void) dataReady:(nsIAutoCompleteResults*)aResults status:(AutoCompleteStatus)aStatus
{
NS_IF_RELEASE(mResults);
mResults = nsnull;
if (aStatus == nsIAutoCompleteStatus::failed) {
[mDataSource setErrorMessage:@""];
} else if (aStatus == nsIAutoCompleteStatus::ignored) {
[mDataSource setErrorMessage:@""];
} else if (aStatus == nsIAutoCompleteStatus::noMatch) {
[mDataSource setErrorMessage:@""];
} else if (aStatus == nsIAutoCompleteStatus::matchFound) {
mResults = aResults;
NS_IF_ADDREF(mResults);
[mDataSource setResults:aResults];
[self completeDefaultResult];
}
if ([mDataSource rowCount] > 0) {
[mTableView noteNumberOfRowsChanged];
[self openPopup];
} else {
[self closePopup];
}
}
- (void) searchTimer:(NSTimer *)aTimer
{
[mOpenTimer release];
mOpenTimer = nil;
[self performSearch];
}
- (void) clearResults
{
// clear out search data
if (mSearchString)
[mSearchString release];
mSearchString = nil;
NS_IF_RELEASE(mResults);
mResults = nsnull;
[mDataSource setResults:nil];
[self closePopup];
}
// handling the popup /////////////////////////////////
- (void) openPopup
{
[self resizePopup];
// show the popup
if ([mPopupWin isVisible] == NO)
[mPopupWin orderFront:nil];
}
- (void) resizePopup
{
NSRect locationFrame, winFrame;
NSPoint locationOrigin;
int tableHeight;
if ([self visibleRows] == 0) {
[self closePopup];
return;
}
// get the origin of the location bar in coordinates of the root view
locationFrame = [[self superview] frame];
locationOrigin = [[[self superview] superview] convertPoint:locationFrame.origin
toView:[[[self window] contentView] superview]];
// get the height of the table view
winFrame = [[self window] frame];
tableHeight = (int)([mTableView rowHeight]+[mTableView intercellSpacing].height)*[self visibleRows];
// make the columns split the width of the popup
[[mTableView tableColumnWithIdentifier:@"col1"] setWidth:locationFrame.size.width/2];
// position the popup anchored to bottom/left of location bar (
[mPopupWin setFrame:NSMakeRect(winFrame.origin.x + locationOrigin.x + kFrameMargin,
((winFrame.origin.y + locationOrigin.y) - tableHeight) - kFrameMargin,
locationFrame.size.width - (2*kFrameMargin),
tableHeight) display:NO];
}
- (void) closePopup
{
[mPopupWin close];
}
- (BOOL) isOpen
{
return [mPopupWin isVisible];
}
// url completion ////////////////////////////
- (void) completeDefaultResult
{
PRInt32 defaultRow;
mResults->GetDefaultItemIndex(&defaultRow);
if (mCompleteResult && mCompleteWhileTyping) {
[self selectRowAt:defaultRow];
[self completeResult:defaultRow];
} else {
[self selectRowAt:-1];
}
}
- (void) completeSelectedResult
{
[self completeResult:[mTableView selectedRow]];
}
- (void) completeResult:(int)aRow
{
if (aRow < 0 && mSearchString) {
// reset to the original search string with the insertion point at the end. Note
// we have to make our range before we call setStringUndoably: because it calls
// clearResults() which destroys |mSearchString|.
NSRange selectAtEnd = NSMakeRange([mSearchString length],0);
[self setStringUndoably:mSearchString fromLocation:0];
[[self fieldEditor] setSelectedRange:selectAtEnd];
}
else {
if ([mDataSource rowCount] <= 0)
return;
// Fill in the suggestion from the list, but change only the text
// after what is typed and select just that part. This allows the
// user to see what they have typed and what change the autocomplete
// makes while allowing them to continue typing w/out having to
// reset the insertion point.
NSString *result = [mDataSource resultString:aRow column:@"col1"];
NSRange matchRange = [result rangeOfString:mSearchString];
if (matchRange.length > 0 && matchRange.location != NSNotFound) {
unsigned int location = matchRange.location + matchRange.length;
result = [result substringWithRange:NSMakeRange(location, [result length]-location)];
[self setStringUndoably:result fromLocation:[mSearchString length]];
}
}
}
- (void) enterResult:(int)aRow
{
if (aRow >= 0 && [mDataSource rowCount] > 0) {
[self setStringUndoably:[mDataSource resultString:[mTableView selectedRow] column:@"col1"] fromLocation:0];
[self closePopup];
} else if (mOpenTimer) {
// if there was a search timer going when we hit enter, cancel it
[mOpenTimer invalidate];
[mOpenTimer release];
mOpenTimer = nil;
}
}
- (void) revertText
{
BrowserWindowController *controller = (BrowserWindowController *)[[self window] windowController];
NSString *url = [[controller getBrowserWrapper] getCurrentURLSpec];
if (url) {
[self clearResults];
NSTextView *fieldEditor = [self fieldEditor];
[[fieldEditor undoManager] removeAllActions];
[fieldEditor setString:url];
[fieldEditor selectAll:self];
}
}
- (void) setStringUndoably:(NSString *)aString fromLocation:(unsigned int)aLocation
{
NSTextView *fieldEditor = [self fieldEditor];
NSRange aRange = NSMakeRange(aLocation,[[fieldEditor string] length] - aLocation);
if ([fieldEditor shouldChangeTextInRange:aRange replacementString:aString]) {
[[fieldEditor textStorage] replaceCharactersInRange:aRange withString:aString];
// Whenever we send [self didChangeText], we trigger the
// textDidChange method, which will begin a new search with
// a new search string (which we just inserted) if the selection
// is at the end of the string. So, we "select" the first character
// to prevent that badness from happening.
[fieldEditor setSelectedRange:NSMakeRange(0,0)];
[fieldEditor didChangeText];
}
aRange = NSMakeRange(aLocation,[[fieldEditor string] length] - aLocation);
[fieldEditor setSelectedRange:aRange];
}
// selecting rows /////////////////////////////////////////
- (void) selectRowAt:(int)aRow
{
if (aRow >= -1 && [mDataSource rowCount] > 0) {
// show the popup
if ([mPopupWin isVisible] == NO)
[mPopupWin orderFront:nil];
[mTableView selectRow:aRow byExtendingSelection:NO];
[mTableView scrollRowToVisible: aRow];
}
}
- (void) selectRowBy:(int)aRows
{
int row = [mTableView selectedRow];
if (row == -1 && aRows < 0) {
// if nothing is selected and you scroll up, go to last row
row = [mTableView numberOfRows]-1;
} else if (row == [mTableView numberOfRows]-1 && aRows == 1) {
// if the last row is selected and you scroll down, go to first row
row = 0;
} else if (aRows+row < 0) {
// if you scroll up beyond first row...
if (row == 0)
row = -1; // ...and first row is selected, select nothing
else
row = 0; // ...else, go to first row
} else if (aRows+row >= [mTableView numberOfRows]) {
// if you scroll down beyond the last row...
if (row == [mTableView numberOfRows]-1)
row = 0; // and last row is selected, select first row
else
row = [mTableView numberOfRows]-1; // else, go to last row
} else {
// no special case, just increment current row
row += aRows;
}
[self selectRowAt:row];
}
// event handlers ////////////////////////////////////////////
- (void) onRowClicked:(NSNotification *)aNote
{
[self enterResult:[mTableView clickedRow]];
[[[self window] windowController] goToLocationFromToolbarURLField:self];
}
- (void) onBlur:(NSNotification *)aNote
{
[self closePopup];
}
- (void) onResize:(NSNotification *)aNote
{
[self resizePopup];
}
- (void) onUndoOrRedo:(NSNotification *)aNote
{
[self clearResults];
}
// NSTextField delegate //////////////////////////////////
- (void)controlTextDidChange:(NSNotification *)aNote
{
NSTextView *fieldEditor = [[aNote userInfo] objectForKey:@"NSFieldEditor"];
NSRange range = [fieldEditor selectedRange];
// make sure we're typing at the end of the string
if (range.location == [[fieldEditor string] length]) {
// when we ask for a NSTextView string, Cocoa returns
// a pointer to the view's backing store. So, the value
// of the string continually changes as we edit the text view.
// Since we'll edit the text view as we add in autocomplete results,
// we've got to make a copy of the string as it currently stands
// to know what we were searching for in the first place.
NSString *searchString = [[fieldEditor string] copyWithZone:nil];
[self startSearch:searchString complete:!mBackspaced];
[searchString release];
}
else if (([mTableView selectedRow] == -1) || mBackspaced)
[self clearResults];
mBackspaced = NO;
}
- (void)controlTextDidEndEditing:(NSNotification *)aNote
{
[self closePopup];
[[[[aNote userInfo] objectForKey:@"NSFieldEditor"] undoManager] removeAllActions];
}
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command
{
if (command == @selector(insertNewline:)) {
[self enterResult:[mTableView selectedRow]];
} else if (command == @selector(moveUp:)) {
[self selectRowBy:-1];
[self completeSelectedResult];
return YES;
} else if (command == @selector(moveDown:)) {
[self selectRowBy:1];
[self completeSelectedResult];
return YES;
} else if (command == @selector(scrollPageUp:)) {
[self selectRowBy:-kMaxRows];
[self completeSelectedResult];
} else if (command == @selector(scrollPageDown:)) {
[self selectRowBy:kMaxRows];
[self completeSelectedResult];
} else if (command == @selector(moveToBeginningOfDocument:)) {
[self selectRowAt:0];
[self completeSelectedResult];
} else if (command == @selector(moveToEndOfDocument:)) {
[self selectRowAt:[mTableView numberOfRows]-1];
[self completeSelectedResult];
} else if (command == @selector(insertTab:)) {
if ([mPopupWin isVisible]) {
[self selectRowBy:1];
[self completeSelectedResult];
return YES;
}
} else if (command == @selector(deleteBackward:) ||
command == @selector(deleteForward:)) {
// if the user deletes characters, we need to know so that
// we can prevent autocompletion later when search results come in
if ([[textView string] length] > 1)
mBackspaced = YES;
}
return NO;
}
@end

View File

@ -1,47 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import <Foundation/Foundation.h>
#import <Appkit/Appkit.h>
class nsIDOMElement;
class BookmarksService;
@class BookmarkItem;
@interface CHBookmarksButton : NSButton
{
nsIDOMElement* mElement;
BookmarkItem* mBookmarkItem;
BookmarksService* mBookmarksService;
BOOL mIsFolder;
}
-(id)initWithFrame:(NSRect)frame element:(nsIDOMElement*)element bookmarksService:(BookmarksService*)bookmarksService;
-(void)setElement: (nsIDOMElement*)aElt;
-(nsIDOMElement*)element;
-(IBAction)openBookmark:(id)aSender;
@end

View File

@ -1,271 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import "NSString+Utils.h"
#import "CHBookmarksButton.h"
#include "nsCOMPtr.h"
#include "nsIContent.h"
#include "nsIDOMElement.h"
#include "nsINamespaceManager.h"
#include "nsIPrefBranch.h"
#include "nsIServiceManager.h"
#include "nsString.h"
#include "nsCRT.h"
#import "BookmarkInfoController.h"
#import "BookmarksDataSource.h"
#import "BookmarksService.h"
@implementation CHBookmarksButton
- (id)initWithFrame:(NSRect)frame
{
if ( (self = [super initWithFrame:frame]) ) {
[self setBezelStyle: NSRegularSquareBezelStyle];
[self setButtonType: NSMomentaryChangeButton];
[self setBordered: NO];
[self setImagePosition: NSImageLeft];
[self setRefusesFirstResponder: YES];
[self setFont: [NSFont labelFontOfSize: 11.0]];
}
return self;
}
-(id)initWithFrame:(NSRect)frame element:(nsIDOMElement*)element bookmarksService:(BookmarksService*)bookmarksService
{
if ( (self = [self initWithFrame:frame]) ) {
mBookmarksService = bookmarksService;
[self setElement:element];
}
return self;
}
-(IBAction)openBookmark:(id)aSender
{
// See if we're a group.
nsAutoString group;
mElement->GetAttribute(NS_LITERAL_STRING("group"), group);
if (!group.IsEmpty()) {
BookmarksService::OpenBookmarkGroup([[[self window] windowController] getTabBrowser], mElement);
return;
}
// Get the href attribute. This is the URL we want to load.
nsAutoString href;
mElement->GetAttribute(NS_LITERAL_STRING("href"), href);
if (href.IsEmpty())
return;
NSString* url = [NSString stringWith_nsAString: href];
// Now load the URL in the window.
BrowserWindowController* brController = [[self window] windowController];
[brController loadURL: url referrer:nil activate:YES];
}
-(IBAction)openBookmarkInNewTab:(id)aSender
{
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return; // Something bad happened if we can't get prefs.
// Get the href attribute. This is the URL we want to load.
nsAutoString hrefAttr;
mElement->GetAttribute(NS_LITERAL_STRING("href"), hrefAttr);
NSString* hrefStr = [NSString stringWith_nsAString:hrefAttr];
PRBool loadInBackground;
pref->GetBoolPref("browser.tabs.loadInBackground", &loadInBackground);
BrowserWindowController* brController = [[self window] windowController];
[brController openNewTabWithURL: hrefStr referrer:nil loadInBackground: loadInBackground];
}
-(IBAction)openBookmarkInNewWindow:(id)aSender
{
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return; // Something bad happened if we can't get prefs.
// Get the href attribute. This is the URL we want to load.
nsAutoString hrefAttr;
mElement->GetAttribute(NS_LITERAL_STRING("href"), hrefAttr);
NSString* hrefStr = [NSString stringWith_nsAString:hrefAttr];
PRBool loadInBackground;
pref->GetBoolPref("browser.tabs.loadInBackground", &loadInBackground);
nsAutoString group;
mElement->GetAttribute(NS_LITERAL_STRING("group"), group);
BrowserWindowController* brController = [[self window] windowController];
if (group.IsEmpty())
[brController openNewWindowWithURL: hrefStr referrer: nil loadInBackground: loadInBackground];
else
[brController openNewWindowWithGroup: mElement loadInBackground: loadInBackground];
}
-(IBAction)showBookmarkInfo:(id)aSender
{
BookmarkInfoController *bic = [BookmarkInfoController sharedBookmarkInfoController];
[bic showWindow:bic];
[bic setBookmark:mBookmarkItem];
}
-(IBAction)deleteBookmarks: (id)aSender
{
if (mElement == BookmarksService::gToolbarRoot)
return; // Don't allow the personal toolbar to be deleted.
nsCOMPtr<nsIContent> content(do_QueryInterface(mElement));
nsCOMPtr<nsIDOMNode> parent;
mElement->GetParentNode(getter_AddRefs(parent));
nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parent));
nsCOMPtr<nsIDOMNode> dummy;
if (parent)
parent->RemoveChild(mElement, getter_AddRefs(dummy));
BookmarksService::BookmarkRemoved(parentContent, content);
}
-(IBAction)addFolder:(id)aSender
{
// TODO
}
-(void)drawRect:(NSRect)aRect
{
[super drawRect: aRect];
}
-(NSMenu*)menuForEvent:(NSEvent*)aEvent
{
// Make a copy of the context menu but change it to target us
// FIXME - this will stop to work as soon as we add items to the context menu
// that have different targets. In that case, we probably should add code to
// CHBookmarksToolbar that manages the context menu for the CHBookmarksButtons.
NSMenu* myMenu = [[[self superview] menu] copy];
[[myMenu itemArray] makeObjectsPerformSelector:@selector(setTarget:) withObject: self];
[myMenu update];
return [myMenu autorelease];
}
-(BOOL)validateMenuItem:(NSMenuItem*)aMenuItem
{
if (!mBookmarkItem)
return NO;
BOOL isBookmark = [mBookmarkItem isFolder] == NO;
nsAutoString group;
mElement->GetAttribute(NS_LITERAL_STRING("group"), group);
BOOL isGroup = !group.IsEmpty();
if (([aMenuItem action] == @selector(openBookmarkInNewWindow:))) {
// Bookmarks and Bookmark Groups can be opened in a new window
return (isBookmark || isGroup);
}
else if (([aMenuItem action] == @selector(openBookmarkInNewTab:))) {
// Only Bookmarks can be opened in new tabs
BrowserWindowController* brController = [[self window] windowController];
return isBookmark && [brController newTabsAllowed];
}
return YES;
}
-(void)mouseDown:(NSEvent*)aEvent
{
// pop up a "context menu" on folders showing their contents. we check
// for single click to fix issues with dblclicks (bug 162367)
if (mIsFolder && [aEvent clickCount] == 1) {
nsCOMPtr<nsIContent> content(do_QueryInterface(mElement));
NSMenu* menu = BookmarksService::LocateMenu(content);
[NSMenu popUpContextMenu: menu withEvent: aEvent forView: self];
}
else
[super mouseDown:aEvent];
}
-(void)setElement: (nsIDOMElement*)aElt
{
mElement = aElt;
nsAutoString tag;
mElement->GetLocalName(tag);
NSImage* bookmarkImage = mBookmarksService->CreateIconForBookmark(aElt);
nsAutoString group;
mElement->GetAttribute(NS_LITERAL_STRING("group"), group);
if (!group.IsEmpty()) {
mIsFolder = NO;
[self setImage: bookmarkImage];
[self setAction: @selector(openBookmark:)];
[self setTarget: self];
}
else if (tag.Equals(NS_LITERAL_STRING("folder"))) {
[self setImage: bookmarkImage];
mIsFolder = YES;
}
else {
mIsFolder = NO;
[self setImage: bookmarkImage];
[self setAction: @selector(openBookmark:)];
[self setTarget: self];
nsAutoString href;
mElement->GetAttribute(NS_LITERAL_STRING("href"), href);
NSString* helpText = [NSString stringWith_nsAString:href];
[self setToolTip: helpText];
}
nsAutoString name;
mElement->GetAttribute(NS_LITERAL_STRING("name"), name);
[self setTitle: [NSString stringWith_nsAString: name]];
nsCOMPtr<nsIContent> content(do_QueryInterface(mElement));
mBookmarkItem = BookmarksService::GetWrapperFor(content);
}
-(nsIDOMElement*)element
{
return mElement;
}
- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)flag
{
return NSDragOperationGeneric;
}
- (void) mouseDragged: (NSEvent*) aEvent
{
// XXX mouseDragged is never called because buttons cancel dragging while you mouse down
// I have to fix this in an ugly way, by doing the "click" stuff myself and never relying
// on the superclass for that. Bah!
// perhaps you could just implement mouseUp to perform the action (which should be the case
// things shouldn't happen on mouse down) Then does mouseDragged get overridden?
// BookmarksService::DragBookmark(mElement, self, aEvent);
}
@end

View File

@ -1,31 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import <AppKit/AppKit.h>
#import "CHExtendedOutlineView.h"
@interface CHBookmarksOutlineView : CHExtendedOutlineView {
}
@end

View File

@ -1,64 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import "CHBookmarksOutlineView.h"
#import "BookmarksService.h"
#import "BookmarksDataSource.h"
#include "nsCOMPtr.h"
#include "nsIDOMElement.h"
#include "nsIContent.h"
#include "nsIDOMNode.h"
@implementation CHBookmarksOutlineView
- (void)awakeFromNib
{
[self registerForDraggedTypes:[NSArray arrayWithObjects:@"MozURLType", @"MozBookmarkType", NSStringPboardType, nil]];
}
- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
{
if (operation == NSDragOperationDelete) {
NSArray* contentIds = nil;
NSPasteboard* pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
contentIds = [pboard propertyListForType: @"MozBookmarkType"];
if (contentIds) {
for (unsigned int i = 0; i < [contentIds count]; ++i) {
BookmarkItem* item = [BookmarksService::gDictionary objectForKey: [contentIds objectAtIndex:i]];
nsCOMPtr<nsIDOMElement> bookmarkElt = do_QueryInterface([item contentNode]);
BookmarksService::DeleteBookmark(bookmarkElt);
}
}
}
}
- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)flag
{
unsigned int result = [super draggingSourceOperationMaskForLocal:flag];
if (flag == NO)
result &= NSDragOperationDelete;
return result;
}
@end

View File

@ -1,58 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import <AppKit/AppKit.h>
class nsIDOMElement;
class BookmarksService;
class CHBookmarksButton;
@interface CHBookmarksToolbar : NSView
{
BookmarksService* mBookmarks;
NSMutableArray* mButtons;
CHBookmarksButton* mDragInsertionButton;
int mDragInsertionPosition;
BOOL mIsShowing;
}
-(void)initializeToolbar;
// Called to construct & edit the initial set of personal toolbar buttons.
-(void)buildButtonList;
-(void)addButton: (nsIDOMElement*)aElt atIndex: (int)aIndex;
-(void)editButton: (nsIDOMElement*)aElt;
-(void)removeButton: (nsIDOMElement*)aElt;
// Called to lay out the buttons on the toolbar.
-(void)reflowButtons;
-(void)reflowButtonsStartingAtIndex: (int)aIndex;
-(BOOL)isShown;
-(void)showBookmarksToolbar: (BOOL)aShow;
- (void) setButtonInsertionPoint:(NSPoint)aPoint;
- (NSRect)insertionRectForButton:(NSView*)aButton position:(int)aPosition;
@end

View File

@ -1,464 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
* Kathy Brade <brade@netscape.com>
* David Haas <haasd@cae.wisc.edu>
*/
#import "CHBookmarksButton.h"
#import "CHBookmarksToolbar.h"
#import "BookmarksService.h"
#import "BookmarksDataSource.h"
#include "nsIDOMElement.h"
#include "nsIContent.h"
@interface CHBookmarksToolbar(Private)
- (CHBookmarksButton*)makeNewButtonWithElement:(nsIDOMElement*)element;
@end
@implementation CHBookmarksToolbar
- (id)initWithFrame:(NSRect)frame
{
if ( (self = [super initWithFrame:frame]) ) {
mBookmarks = nsnull;
mButtons = [[NSMutableArray alloc] init];
mDragInsertionButton = nil;
mDragInsertionPosition = BookmarksService::CHInsertNone;
[self registerForDraggedTypes:[NSArray arrayWithObjects:@"MozURLType", @"MozBookmarkType", NSStringPboardType, nil]];
mIsShowing = YES;
}
return self;
}
-(void)initializeToolbar
{
// Initialization code here.
mBookmarks = new BookmarksService(self);
mBookmarks->AddObserver();
mBookmarks->EnsureToolbarRoot();
[self buildButtonList];
}
-(void) dealloc
{
[mButtons autorelease];
mBookmarks->RemoveObserver();
delete mBookmarks;
[super dealloc];
}
- (void)drawRect:(NSRect)aRect {
// Fill the background with our background color.
//[[NSColor colorWithCalibratedWhite: 0.98 alpha: 1.0] set];
//NSRectFill(aRect);
//printf("The rect is: %f %f %f %f\n", aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height);
if (aRect.origin.y + aRect.size.height ==
[self bounds].size.height) {
// The personal toolbar is 21 pixels tall. The bottom two pixels
// are a separator.
[[NSColor colorWithCalibratedWhite: 0.90 alpha: 1.0] set];
//NSRectFill(NSMakeRect(aRect.origin.x, [self bounds].size.height-2, aRect.size.width, [self bounds].size.height));
}
// The buttons will paint themselves. Just call our base class method.
[super drawRect: aRect];
// draw a separator at drag n drop insertion point if there is one
if (mDragInsertionPosition) {
[[[NSColor controlShadowColor] colorWithAlphaComponent:0.6] set];
NSRectFill([self insertionRectForButton:mDragInsertionButton position:mDragInsertionPosition]);
}
}
-(void)buildButtonList
{
// Build the buttons, and then lay them all out.
nsCOMPtr<nsIDOMNode> child;
BookmarksService::gToolbarRoot->GetFirstChild(getter_AddRefs(child));
while (child) {
nsCOMPtr<nsIDOMElement> childElt(do_QueryInterface(child));
if (childElt) {
CHBookmarksButton* button = [self makeNewButtonWithElement:childElt];
[self addSubview: button];
[mButtons addObject: button];
}
nsCOMPtr<nsIDOMNode> temp = child;
temp->GetNextSibling(getter_AddRefs(child));
}
if ([self isShown])
[self reflowButtons];
}
-(void)addButton: (nsIDOMElement*)aElt atIndex: (int)aIndex
{
CHBookmarksButton* button = [self makeNewButtonWithElement:aElt];
[self addSubview: button];
[mButtons insertObject: button atIndex: aIndex];
if ([self isShown])
[self reflowButtonsStartingAtIndex: aIndex];
}
-(void)editButton: (nsIDOMElement*)aElt
{
int count = [mButtons count];
for (int i = 0; i < count; i++) {
CHBookmarksButton* button = [mButtons objectAtIndex: i];
if ([button element] == aElt) {
[button setElement: aElt];
if (count > i && [self isShown])
[self reflowButtonsStartingAtIndex: i];
break;
}
}
[self setNeedsDisplay: [self isShown]];
}
-(void)removeButton: (nsIDOMElement*)aElt
{
int count = [mButtons count];
for (int i = 0; i < count; i++) {
CHBookmarksButton* button = [mButtons objectAtIndex: i];
if ([button element] == aElt) {
[mButtons removeObjectAtIndex: i];
[button removeFromSuperview];
if (count > i && [self isShown])
[self reflowButtonsStartingAtIndex: i];
break;
}
}
[self setNeedsDisplay: [self isShown]];
}
-(void)reflowButtons
{
[self reflowButtonsStartingAtIndex: 0];
}
-(void)reflowButtonsStartingAtIndex: (int)aIndex
{
float oldHeight = [self frame].size.height;
float computedHeight = 18;
int count = [mButtons count];
float currY = 1.0;
float prevX = 2.0;
if (aIndex > 0) {
CHBookmarksButton* prevButton = [mButtons objectAtIndex: (aIndex-1)];
prevX += [prevButton frame].origin.x + [prevButton frame].size.width;
currY = [prevButton frame].origin.y;
}
for (int i = aIndex; i < count; i++) {
CHBookmarksButton* button = [mButtons objectAtIndex: i];
[button sizeToFit];
float width = [button frame].size.width;
float height = [button frame].size.height;
if (width > 150)
width = 150;
if (height < 16)
height = 16; // Our folder tiff is only 15 pixels for some reason.
[button setFrame: NSMakeRect(prevX, currY, width, height)];
prevX += [button frame].size.width + 2;
if ([self bounds].size.width < prevX) {
// The previous button didn't fit. We need to make a new row. There's no need to adjust the
// view's frame yet, we'll do that below.
currY += 18;
computedHeight += 18;
prevX = 2;
[button setFrame: NSMakeRect(prevX, currY, width, height)];
prevX += [button frame].size.width + 2;
}
[button setNeedsDisplay: YES];
}
// our size has changed, readjust our view's frame and the content area
if (computedHeight != oldHeight) {
[self setFrame: NSMakeRect([self frame].origin.x, [self frame].origin.y + (oldHeight - computedHeight),
[self frame].size.width, computedHeight)];
[self setNeedsDisplay: [self isShown]];
// adjust the content area.
float sizeChange = computedHeight - oldHeight;
NSView* view = [[[self window] windowController] getTabBrowser];
[view setFrame: NSMakeRect([view frame].origin.x, [view frame].origin.y,
[view frame].size.width, [view frame].size.height - sizeChange)];
}
}
-(BOOL)isFlipped
{
return YES; // Use flipped coords, so we can layout out from top row to bottom row.
}
-(void)setFrame:(NSRect)aRect
{
NSRect oldFrame = [self frame];
[super setFrame:aRect];
if (oldFrame.size.width == aRect.size.width || aRect.size.height == 0)
return;
int count = [mButtons count];
if (count <= 2)
return; // We have too few buttons to care.
// Do some optimizations when we have only one row.
if (aRect.size.height < 25) // We have only one row.
{
if (oldFrame.size.width < aRect.size.width)
// We got bigger. If we already only have one row, just bail.
// This will optimize for a common resizing case.
return;
else {
// We got smaller. Just go to the last button and see if it is outside
// our bounds.
CHBookmarksButton* button = [mButtons objectAtIndex:(count-1)];
if ([button frame].origin.x + [button frame].size.width >
[self bounds].size.width - 2) {
// The button doesn't fit any more. Reflow starting at this index.
[self reflowButtonsStartingAtIndex:(count-1)];
}
}
}
else {
// See if we got bigger or smaller. We could gain or lose a row.
[self reflowButtons];
}
}
-(BOOL)isShown
{
return mIsShowing;
}
-(void)showBookmarksToolbar: (BOOL)aShow
{
if (!aShow) {
float height = [self bounds].size.height;
[self setFrame: NSMakeRect([self frame].origin.x, [self frame].origin.y + height,
[self frame].size.width, 0)];
// We need to adjust the content area.
NSView* view = [[[self window] windowController] getTabBrowser];
[view setFrame: NSMakeRect([view frame].origin.x, [view frame].origin.y,
[view frame].size.width, [view frame].size.height + height)];
}
else
// Reflowing the buttons will do the right thing.
[self reflowButtons];
mIsShowing = aShow;
}
- (void)setButtonInsertionPoint:(NSPoint)aPoint
{
int count = [mButtons count];
mDragInsertionButton = nsnull;
mDragInsertionPosition = BookmarksService::CHInsertAfter;
for (int i = 0; i < count; ++i) {
CHBookmarksButton* button = [mButtons objectAtIndex: i];
//NSLog(@"check %d - %d,%d %d,%d\n", i, [button frame].origin.x, [button frame].origin.y, aPoint.x, aPoint.y);
// XXX origin.y is coming up zero here! Need that to check the row we're dragging in :(
nsCOMPtr<nsIAtom> tagName;
nsCOMPtr<nsIContent> contentNode = do_QueryInterface([button element]);
contentNode->GetTag(*getter_AddRefs(tagName));
if (tagName == BookmarksService::gFolderAtom) {
if (([button frame].origin.x+([button frame].size.width) > aPoint.x)) {
mDragInsertionButton = button;
mDragInsertionPosition = BookmarksService::CHInsertInto;
return;
}
} else if (([button frame].origin.x+([button frame].size.width/2) > aPoint.x)) {
mDragInsertionButton = button;
mDragInsertionPosition = BookmarksService::CHInsertBefore;
return;
} else if (([button frame].origin.x+([button frame].size.width) > aPoint.x)) {
mDragInsertionButton = button;
mDragInsertionPosition = BookmarksService::CHInsertAfter;
return;
}
}
}
- (BOOL)dropDestinationValid:(NSPasteboard*)draggingPasteboard
{
NSArray* types = [draggingPasteboard types];
if ([types containsObject: @"MozBookmarkType"])
{
NSArray *draggedIDs = [draggingPasteboard propertyListForType: @"MozBookmarkType"];
nsCOMPtr<nsIContent> destinationContent;
int index = 0;
if (mDragInsertionPosition == BookmarksService::CHInsertInto) // drop onto folder
{
nsCOMPtr<nsIDOMElement> parentElt = [mDragInsertionButton element];
destinationContent = do_QueryInterface(parentElt);
index = 0;
}
else if (mDragInsertionPosition == BookmarksService::CHInsertBefore ||
mDragInsertionPosition == BookmarksService::CHInsertAfter) // drop onto toolbar
{
nsCOMPtr<nsIDOMElement> toolbarRoot = BookmarksService::gToolbarRoot;
destinationContent = do_QueryInterface(toolbarRoot);
index = [mButtons indexOfObject: mDragInsertionButton];
}
BookmarkItem* toolbarFolderItem = BookmarksService::GetWrapperFor(destinationContent);
if (!BookmarksService::IsBookmarkDropValid(toolbarFolderItem, index, draggedIDs)) {
return NO;
}
}
return YES;
}
// NSDraggingDestination ///////////
- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
if (![self dropDestinationValid:[sender draggingPasteboard]])
return NSDragOperationNone;
return NSDragOperationGeneric;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
if (mDragInsertionPosition)
[self setNeedsDisplayInRect:[self insertionRectForButton:mDragInsertionButton position:mDragInsertionPosition]];
mDragInsertionButton = nil;
mDragInsertionPosition = BookmarksService::CHInsertNone;
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
if (mDragInsertionPosition)
[self setNeedsDisplayInRect:[self insertionRectForButton:mDragInsertionButton position:mDragInsertionPosition]];
if (![self dropDestinationValid:[sender draggingPasteboard]])
return NSDragOperationNone;
[self setButtonInsertionPoint:[sender draggingLocation]];
if (mDragInsertionPosition)
[self setNeedsDisplayInRect:[self insertionRectForButton:mDragInsertionButton position:mDragInsertionPosition]];
return NSDragOperationGeneric;
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
BookmarkItem* parent = nsnull;
int index = 0;
if (mDragInsertionPosition == BookmarksService::CHInsertInto) { // drop onto folder
nsCOMPtr<nsIDOMElement> parentElt = [mDragInsertionButton element];
nsCOMPtr<nsIContent> parentContent(do_QueryInterface(parentElt));
parent = BookmarksService::GetWrapperFor(parentContent);
index = 0;
}
else if (mDragInsertionPosition == BookmarksService::CHInsertBefore ||
mDragInsertionPosition == BookmarksService::CHInsertAfter) { // drop onto toolbar
nsCOMPtr<nsIDOMElement> rootElt = BookmarksService::gToolbarRoot;
nsCOMPtr<nsIContent> rootContent(do_QueryInterface(rootElt));
parent = BookmarksService::GetWrapperFor(rootContent);
index = [mButtons indexOfObject: mDragInsertionButton];
if (index == NSNotFound)
rootContent->ChildCount(index);
else if (mDragInsertionPosition == BookmarksService::CHInsertAfter)
index++;
} else {
mDragInsertionButton = nil;
mDragInsertionPosition = BookmarksService::CHInsertNone;
[self setNeedsDisplay:YES];
return NO;
}
BOOL dropHandled = NO;
NSArray *draggedTypes = [[sender draggingPasteboard] types];
if ( [draggedTypes containsObject:@"MozBookmarkType"] )
{
NSArray *draggedItems = [[sender draggingPasteboard] propertyListForType: @"MozBookmarkType"];
dropHandled = BookmarksService::PerformBookmarkDrop(parent, index, draggedItems);
}
else if ( [draggedTypes containsObject:@"MozURLType"] )
{
NSDictionary* proxy = [[sender draggingPasteboard] propertyListForType: @"MozURLType"];
nsCOMPtr<nsIContent> beforeContent;
[parent contentNode]->ChildAt(index, *getter_AddRefs(beforeContent));
BookmarkItem* beforeItem = mBookmarks->GetWrapperFor(beforeContent); // can handle nil content
dropHandled = BookmarksService::PerformProxyDrop(parent, beforeItem, proxy);
}
else if ( [draggedTypes containsObject:NSStringPboardType] )
{
NSString* draggedText = [[sender draggingPasteboard] stringForType:NSStringPboardType];
nsCOMPtr<nsIContent> beforeContent;
[parent contentNode]->ChildAt(index, *getter_AddRefs(beforeContent));
BookmarkItem* beforeItem = mBookmarks->GetWrapperFor(beforeContent); // can handle nil content
// maybe fix URL drags to include the selected text as the title
dropHandled = BookmarksService::PerformURLDrop(parent, beforeItem, draggedText, draggedText);
}
mDragInsertionButton = nil;
mDragInsertionPosition = BookmarksService::CHInsertNone;
[self setNeedsDisplay: [self isShown]];
return dropHandled;
}
- (NSRect)insertionRectForButton:(NSView*)aButton position:(int) aPosition
{
if (aPosition == BookmarksService::CHInsertInto) {
return NSMakeRect([aButton frame].origin.x, [aButton frame].origin.y, [aButton frame].size.width, [aButton frame].size.height);
} else if (aPosition == BookmarksService::CHInsertAfter) {
return NSMakeRect([aButton frame].origin.x+[aButton frame].size.width, [aButton frame].origin.y, 2, [aButton frame].size.height);
} else {// if (aPosition == BookmarksService::CHInsertBefore) {
return NSMakeRect([aButton frame].origin.x - 2, [aButton frame].origin.y, 2, [aButton frame].size.height);
}
}
- (CHBookmarksButton*)makeNewButtonWithElement:(nsIDOMElement*)element
{
return [[[CHBookmarksButton alloc] initWithFrame: NSMakeRect(2, 1, 100, 17) element:element bookmarksService:mBookmarks] autorelease];
}
@end

View File

@ -1,200 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __nsCocoaBrowserView_h__
#define __nsCocoaBrowserView_h__
#undef DARWIN
#import <Cocoa/Cocoa.h>
@class CHBrowserView;
class nsCocoaBrowserListener;
class nsIDOMWindow;
class nsIWebBrowser;
class nsIDOMNode;
class nsIDOMEvent;
class nsIWebBrowserFind;
class nsIEventSink;
class nsIDragHelperService;
// Protocol implemented by anyone interested in progress
// related to a BrowserView. A listener should explicitly
// register itself with the view using the addListener
// method.
@protocol NSBrowserListener
- (void)onLoadingStarted;
- (void)onLoadingCompleted:(BOOL)succeeded;
// Invoked regularly as data associated with a page streams
// in. If the total number of bytes expected is unknown,
// maxBytes is -1.
- (void)onProgressChange:(int)currentBytes outOf:(int)maxBytes;
- (void)onLocationChange:(NSString*)urlSpec;
- (void)onStatusChange:(NSString*)aMessage;
- (void)onSecurityStateChange:(unsigned long)newState;
// Called when a context menu should be shown.
- (void)onShowContextMenu:(int)flags domEvent:(nsIDOMEvent*)aEvent domNode:(nsIDOMNode*)aNode;
// Called when a tooltip should be shown or hidden
- (void)onShowTooltip:(NSPoint)where withText:(NSString*)text;
- (void)onHideTooltip;
@end
typedef enum {
NSStatusTypeScript = 0x0001,
NSStatusTypeScriptDefault = 0x0002,
NSStatusTypeLink = 0x0003,
} NSStatusType;
@protocol NSBrowserContainer
- (void)setStatus:(NSString *)statusString ofType:(NSStatusType)type;
- (NSString *)title;
- (void)setTitle:(NSString *)title;
// Set the dimensions of our NSView. The container might need to do
// some adjustment, so the view doesn't do it directly.
- (void)sizeBrowserTo:(NSSize)dimensions;
// Create a new browser container window and return the contained view.
- (CHBrowserView*)createBrowserWindow:(unsigned int)mask;
- (NSMenu*)getContextMenu;
- (NSWindow*)getNativeWindow;
// Ask whether the browser should accept a drag from the given source.
// Should return NO if the source is a container for the browser, or
// another item that represents the same entity (e.g. tab or proxy icon)
- (BOOL)shouldAcceptDragFromSource:(id)dragSource;
@end
enum {
NSLoadFlagsNone = 0x0000,
NSLoadFlagsDontPutInHistory = 0x0010,
NSLoadFlagsReplaceHistoryEntry = 0x0020,
NSLoadFlagsBypassCacheAndProxy = 0x0040
};
enum {
NSStopLoadNetwork = 0x01,
NSStopLoadContent = 0x02,
NSStopLoadAll = 0x03
};
@interface CHBrowserView : NSView
{
nsIWebBrowser* _webBrowser;
nsCocoaBrowserListener* _listener;
NSWindow* mWindow;
nsIDragHelperService* mDragHelper;
NSPoint mLastTrackedLocation;
NSWindow* mLastTrackedWindow;
}
// NSView overrides
- (id)initWithFrame:(NSRect)frame;
- (id)initWithFrame:(NSRect)frame andWindow:(NSWindow*)aWindow;
- (void)dealloc;
- (void)setFrame:(NSRect)frameRect;
// nsIWebBrowser methods
- (void)addListener:(id <NSBrowserListener>)listener;
- (void)removeListener:(id <NSBrowserListener>)listener;
- (void)setContainer:(id <NSBrowserContainer>)container;
- (nsIDOMWindow*)getContentWindow;
// nsIWebNavigation methods
- (void)loadURI:(NSString *)urlSpec referrer:(NSString*)referrer flags:(unsigned int)flags;
- (void)reload:(unsigned int)flags;
- (BOOL)canGoBack;
- (BOOL)canGoForward;
- (void)goBack;
- (void)goForward;
- (void)gotoIndex:(int)index;
- (void)stop:(unsigned int)flags;
- (NSString*)getCurrentURI;
- (void)saveDocument: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList;
- (void)saveURL: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList
url: (NSString*)aURLSpec suggestedFilename: (NSString*)aFilename;
- (void)printDocument;
- (BOOL)findInPageWithPattern:(NSString*)inText caseSensitive:(BOOL)inCaseSensitive
wrap:(BOOL)inWrap backwards:(BOOL)inBackwards;
-(BOOL)validateMenuItem: (NSMenuItem*)aMenuItem;
-(IBAction)cut:(id)aSender;
-(BOOL)canCut;
-(IBAction)copy:(id)aSender;
-(BOOL)canCopy;
-(IBAction)paste:(id)aSender;
-(BOOL)canPaste;
-(IBAction)delete:(id)aSender;
-(BOOL)canDelete;
-(IBAction)selectAll:(id)aSender;
-(IBAction)undo:(id)aSender;
-(IBAction)redo:(id)aSender;
- (BOOL)canUndo;
- (BOOL)canRedo;
-(NSString*)getCurrentURLSpec;
- (void)setActive: (BOOL)aIsActive;
- (NSMenu*)getContextMenu;
- (NSWindow*)getNativeWindow;
- (void)destroyWebBrowser;
- (nsIWebBrowser*)getWebBrowser;
- (nsCocoaBrowserListener*)getCocoaBrowserListener;
- (void)setWebBrowser:(nsIWebBrowser*)browser;
- (NSString*)getFocusedURLString;
// given a point in window coordinates, find the Gecko event sink of the ChildView the
// point is over.
- (void) findEventSink:(nsIEventSink**)outSink forPoint:(NSPoint)inPoint inWindow:(NSWindow*)inWind;
@end
#endif // __nsCocoaBrowserView_h__

View File

@ -1,870 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#include "nsCWebBrowser.h"
#include "nsIBaseWindow.h"
#include "nsIWebNavigation.h"
#include "nsComponentManagerUtils.h"
#include "nsIURI.h"
#include "nsIDOMWindow.h"
#include "nsIWidget.h"
// Printing
#include "nsIWebBrowserPrint.h"
//#include "nsIPrintSettings.h"
// Saving of links/images/docs
#include "nsIWebBrowserFocus.h"
#include "nsIDOMNSDocument.h"
#include "nsIDOMLocation.h"
#include "nsIWebBrowserPersist.h"
#include "nsIProperties.h"
//#include "nsIRequest.h"
//#include "nsIPrefService.h"
#include "nsISHistory.h"
#include "nsIHistoryEntry.h"
#include "nsISHEntry.h"
#include "nsNetUtil.h"
#include "SaveHeaderSniffer.h"
#import "CHBrowserWrapper.h"
#import "CHBrowserView.h"
#import "FindDlgController.h"
#import "nsCocoaBrowserService.h"
#import "nsCocoaBrowserListener.h"
#import "mozView.h"
typedef unsigned int DragReference;
#include "nsIDragHelperService.h"
// Cut/copy/paste
#include "nsIClipboardCommands.h"
#include "nsIInterfaceRequestorUtils.h"
// Undo/redo
#include "nsICommandManager.h"
#include "nsICommandParams.h"
const char kPersistContractID[] = "@mozilla.org/embedding/browser/nsWebBrowserPersist;1";
const char kDirServiceContractID[] = "@mozilla.org/file/directory_service;1";
@implementation CHBrowserView
- (id)initWithFrame:(NSRect)frame andWindow:(NSWindow*)aWindow
{
mWindow = aWindow;
return [self initWithFrame:frame];
}
- (id)initWithFrame:(NSRect)frame
{
if ( (self = [super initWithFrame:frame]) )
{
nsresult rv = nsCocoaBrowserService::InitEmbedding();
if (NS_FAILED(rv)) {
// XXX need to throw
}
_listener = new nsCocoaBrowserListener(self);
NS_ADDREF(_listener);
// Create the web browser instance
nsCOMPtr<nsIWebBrowser> browser = do_CreateInstance(NS_WEBBROWSER_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
// XXX need to throw
}
_webBrowser = browser;
NS_ADDREF(_webBrowser);
// Set the container nsIWebBrowserChrome
_webBrowser->SetContainerWindow(NS_STATIC_CAST(nsIWebBrowserChrome *, _listener));
// Register as a listener for web progress
nsCOMPtr<nsIWeakReference> weak = do_GetWeakReference(NS_STATIC_CAST(nsIWebProgressListener*, _listener));
_webBrowser->AddWebBrowserListener(weak, NS_GET_IID(nsIWebProgressListener));
// Hook up the widget hierarchy with us as the parent
nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(_webBrowser);
baseWin->InitWindow((NSView*)self, nsnull, 0, 0,
frame.size.width, frame.size.height);
baseWin->Create();
// register the view as a drop site for text, files, and urls.
[self registerForDraggedTypes: [NSArray arrayWithObjects:
@"MozURLType", NSStringPboardType, NSURLPboardType, NSFilenamesPboardType, nil]];
}
return self;
}
- (void)destroyWebBrowser
{
nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(_webBrowser);
baseWin->Destroy();
}
- (void)dealloc
{
NS_RELEASE(_listener);
NS_IF_RELEASE(_webBrowser);
nsCocoaBrowserService::BrowserClosed();
#if DEBUG
NSLog(@"CHBrowserView died.");
#endif
[super dealloc];
}
- (void)setFrame:(NSRect)frameRect
{
[super setFrame:frameRect];
if (_webBrowser) {
nsCOMPtr<nsIBaseWindow> window = do_QueryInterface(_webBrowser);
window->SetSize((PRInt32)frameRect.size.width,
(PRInt32)frameRect.size.height,
PR_TRUE);
}
}
- (void)addListener:(id <NSBrowserListener>)listener
{
_listener->AddListener(listener);
}
- (void)removeListener:(id <NSBrowserListener>)listener
{
_listener->RemoveListener(listener);
}
- (void)setContainer:(id <NSBrowserContainer>)container
{
_listener->SetContainer(container);
}
- (nsIDOMWindow*)getContentWindow
{
nsIDOMWindow* window;
_webBrowser->GetContentDOMWindow(&window);
return window;
}
- (void)loadURI:(NSString *)urlSpec referrer:(NSString*)referrer flags:(unsigned int)flags
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
int length = [urlSpec length];
PRUnichar* specStr = nsMemory::Alloc((length+1) * sizeof(PRUnichar));
[urlSpec getCharacters:specStr];
specStr[length] = PRUnichar(0);
nsCOMPtr<nsIURI> referrerURI;
if ( referrer )
NS_NewURI(getter_AddRefs(referrerURI), [referrer UTF8String]);
PRUint32 navFlags = nsIWebNavigation::LOAD_FLAGS_NONE;
if (flags & NSLoadFlagsDontPutInHistory) {
navFlags |= nsIWebNavigation::LOAD_FLAGS_BYPASS_HISTORY;
}
if (flags & NSLoadFlagsReplaceHistoryEntry) {
navFlags |= nsIWebNavigation::LOAD_FLAGS_REPLACE_HISTORY;
}
if (flags & NSLoadFlagsBypassCacheAndProxy) {
navFlags |= nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE |
nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY;
}
nsresult rv = nav->LoadURI(specStr, navFlags, referrerURI, nsnull, nsnull);
if (NS_FAILED(rv)) {
// XXX need to throw
}
nsMemory::Free(specStr);
}
- (void)reload:(unsigned int)flags
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
PRUint32 navFlags = nsIWebNavigation::LOAD_FLAGS_NONE;
if (flags & NSLoadFlagsBypassCacheAndProxy) {
navFlags |= nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE |
nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY;
}
nsresult rv = nav->Reload(navFlags);
if (NS_FAILED(rv)) {
// XXX need to throw
}
}
- (BOOL)canGoBack
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
PRBool can;
nav->GetCanGoBack(&can);
return can ? YES : NO;
}
- (BOOL)canGoForward
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
PRBool can;
nav->GetCanGoForward(&can);
return can ? YES : NO;
}
- (void)goBack
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
nsresult rv = nav->GoBack();
if (NS_FAILED(rv)) {
// XXX need to throw
}
}
- (void)goForward
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
nsresult rv = nav->GoForward();
if (NS_FAILED(rv)) {
// XXX need to throw
}
}
- (void)gotoIndex:(int)index
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
nsresult rv = nav->GotoIndex(index);
if (NS_FAILED(rv)) {
// XXX need to throw
}
}
- (void)stop:(unsigned int)flags
{
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
nsresult rv = nav->Stop(flags);
if (NS_FAILED(rv)) {
// XXX need to throw
}
}
// XXXbryner This isn't used anywhere. how is it different from getCurrentURLSpec?
- (NSString*)getCurrentURI
{
nsCOMPtr<nsIURI> uri;
nsCOMPtr<nsIWebNavigation> nav = do_QueryInterface(_webBrowser);
nav->GetCurrentURI(getter_AddRefs(uri));
if (!uri) {
return nsnull;
}
nsCAutoString spec;
uri->GetSpec(spec);
const char* cstr = spec.get();
NSString* str = [NSString stringWithCString:cstr];
return str;
}
- (nsCocoaBrowserListener*)getCocoaBrowserListener
{
return _listener;
}
- (nsIWebBrowser*)getWebBrowser
{
NS_IF_ADDREF(_webBrowser);
return _webBrowser;
}
- (void)setWebBrowser:(nsIWebBrowser*)browser
{
_webBrowser = browser;
if (_webBrowser) {
// Set the container nsIWebBrowserChrome
_webBrowser->SetContainerWindow(NS_STATIC_CAST(nsIWebBrowserChrome *,
_listener));
NSRect frame = [self frame];
// Hook up the widget hierarchy with us as the parent
nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(_webBrowser);
baseWin->InitWindow((NSView*)self, nsnull, 0, 0,
frame.size.width, frame.size.height);
baseWin->Create();
}
}
-(void) saveInternal: (nsIURI*)aURI
withDocument: (nsIDOMDocument*)aDocument
suggestedFilename: (const char*)aFilename
bypassCache: (BOOL)aBypassCache
filterView: (NSView*)aFilterView
filterList: (NSPopUpButton*)aFilterList
{
// Create our web browser persist object. This is the object that knows
// how to actually perform the saving of the page (and of the images
// on the page).
nsCOMPtr<nsIWebBrowserPersist> webPersist(do_CreateInstance(kPersistContractID));
if (!webPersist)
return;
// Make a temporary file object that we can save to.
nsCOMPtr<nsIProperties> dirService(do_GetService(kDirServiceContractID));
if (!dirService)
return;
nsCOMPtr<nsIFile> tmpFile;
dirService->Get("TmpD", NS_GET_IID(nsIFile), getter_AddRefs(tmpFile));
static short unsigned int tmpRandom = 0;
nsAutoString tmpNo; tmpNo.AppendInt(tmpRandom++);
nsAutoString saveFile(NS_LITERAL_STRING("-sav"));
saveFile += tmpNo;
saveFile += NS_LITERAL_STRING("tmp");
tmpFile->Append(saveFile);
// Get the post data if we're an HTML doc.
nsCOMPtr<nsIInputStream> postData;
if (aDocument) {
nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(_webBrowser));
nsCOMPtr<nsISHistory> sessionHistory;
webNav->GetSessionHistory(getter_AddRefs(sessionHistory));
nsCOMPtr<nsIHistoryEntry> entry;
PRInt32 sindex;
sessionHistory->GetIndex(&sindex);
sessionHistory->GetEntryAtIndex(sindex, PR_FALSE, getter_AddRefs(entry));
nsCOMPtr<nsISHEntry> shEntry(do_QueryInterface(entry));
if (shEntry)
shEntry->GetPostData(getter_AddRefs(postData));
}
// when saving, we first fire off a save with a nsHeaderSniffer as a progress
// listener. This allows us to look for the content-disposition header, which
// can supply a filename, and maybe has something to do with CGI-generated
// content (?)
nsCAutoString fileName(aFilename);
nsHeaderSniffer* sniffer = new nsHeaderSniffer(webPersist, tmpFile, aURI,
aDocument, postData, fileName, aBypassCache,
aFilterView, aFilterList);
if (!sniffer)
return;
webPersist->SetProgressListener(sniffer); // owned
webPersist->SaveURI(aURI, nsnull, tmpFile);
}
-(void)printDocument
{
nsCOMPtr<nsIDOMWindow> domWindow;
_webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
nsCOMPtr<nsIInterfaceRequestor> ir(do_QueryInterface(domWindow));
nsCOMPtr<nsIWebBrowserPrint> print;
ir->GetInterface(NS_GET_IID(nsIWebBrowserPrint), getter_AddRefs(print));
print->Print(nsnull, nsnull);
}
- (BOOL)findInPageWithPattern:(NSString*)inText caseSensitive:(BOOL)inCaseSensitive
wrap:(BOOL)inWrap backwards:(BOOL)inBackwards
{
PRBool found = PR_FALSE;
nsCOMPtr<nsIWebBrowserFocus> wbf(do_QueryInterface(_webBrowser));
nsCOMPtr<nsIDOMWindow> rootWindow;
nsCOMPtr<nsIDOMWindow> focusedWindow;
_webBrowser->GetContentDOMWindow(getter_AddRefs(rootWindow));
wbf->GetFocusedWindow(getter_AddRefs(focusedWindow));
if (!focusedWindow)
focusedWindow = rootWindow;
nsCOMPtr<nsIWebBrowserFind> webFind(do_GetInterface(_webBrowser));
if ( webFind ) {
nsCOMPtr<nsIWebBrowserFindInFrames> framesFind(do_QueryInterface(webFind));
framesFind->SetRootSearchFrame(rootWindow);
framesFind->SetCurrentSearchFrame(focusedWindow);
webFind->SetMatchCase(inCaseSensitive ? PR_TRUE : PR_FALSE);
webFind->SetWrapFind(inWrap ? PR_TRUE : PR_FALSE);
webFind->SetFindBackwards(inBackwards ? PR_TRUE : PR_FALSE);
PRUnichar* text = (PRUnichar*)nsMemory::Alloc(([inText length]+1)*sizeof(PRUnichar));
if ( text ) {
[inText getCharacters:text];
text[[inText length]] = 0;
webFind->SetSearchString(text);
webFind->FindNext(&found);
nsMemory::Free(text);
}
}
return found;
}
- (void)saveURL: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList
url: (NSString*)aURLSpec suggestedFilename: (NSString*)aFilename
{
nsCOMPtr<nsIURI> url;
nsresult rv = NS_NewURI(getter_AddRefs(url), [aURLSpec UTF8String]);
if (NS_FAILED(rv))
return;
[self saveInternal: url.get()
withDocument: nsnull
suggestedFilename: (([aFilename length] > 0) ? [aFilename fileSystemRepresentation] : "")
bypassCache: YES
filterView: aFilterView
filterList: aFilterList];
}
-(NSString*)getFocusedURLString
{
nsCOMPtr<nsIWebBrowserFocus> wbf(do_QueryInterface(_webBrowser));
nsCOMPtr<nsIDOMWindow> domWindow;
wbf->GetFocusedWindow(getter_AddRefs(domWindow));
if (!domWindow)
_webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow)
return @"";
nsCOMPtr<nsIDOMDocument> domDocument;
domWindow->GetDocument(getter_AddRefs(domDocument));
if (!domDocument)
return @"";
nsCOMPtr<nsIDOMNSDocument> nsDoc(do_QueryInterface(domDocument));
if (!nsDoc)
return @"";
nsCOMPtr<nsIDOMLocation> location;
nsDoc->GetLocation(getter_AddRefs(location));
if (!location)
return @"";
nsAutoString urlStr;
location->GetHref(urlStr);
return [NSString stringWith_nsAString: urlStr];
}
- (void)saveDocument: (NSView*)aFilterView filterList: (NSPopUpButton*)aFilterList
{
nsCOMPtr<nsIWebBrowserFocus> wbf(do_QueryInterface(_webBrowser));
nsCOMPtr<nsIDOMWindow> domWindow;
wbf->GetFocusedWindow(getter_AddRefs(domWindow));
if (!domWindow)
_webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow)
return;
nsCOMPtr<nsIDOMDocument> domDocument;
domWindow->GetDocument(getter_AddRefs(domDocument));
if (!domDocument)
return;
nsCOMPtr<nsIDOMNSDocument> nsDoc(do_QueryInterface(domDocument));
if (!nsDoc)
return;
nsCOMPtr<nsIDOMLocation> location;
nsDoc->GetLocation(getter_AddRefs(location));
if (!location)
return;
nsAutoString urlStr;
location->GetHref(urlStr);
nsCAutoString urlCStr; urlCStr.AssignWithConversion(urlStr);
nsCOMPtr<nsIURI> url;
nsresult rv = NS_NewURI(getter_AddRefs(url), urlCStr.get());
if (NS_FAILED(rv))
return;
[self saveInternal: url.get()
withDocument: domDocument
suggestedFilename: ""
bypassCache: NO
filterView: aFilterView
filterList: aFilterList];
}
-(void)doCommand:(const char*)commandName
{
nsCOMPtr<nsICommandManager> commandMgr(do_GetInterface(_webBrowser));
if (commandMgr) {
nsCOMPtr<nsICommandParams> commandParams = do_CreateInstance("@mozilla.org/embedcomp/command-params;1");
if (commandParams) {
nsresult rv;
nsAutoString commandNameStr;
commandNameStr.AssignWithConversion(commandName);
rv = commandParams->SetStringValue(NS_LITERAL_STRING("cmd_name"), commandNameStr);
rv = commandMgr->DoCommand(commandParams);
#if DEBUG
if (NS_FAILED(rv))
NSLog(@"DoCommand failed");
#endif
}
else {
#if DEBUG
NSLog(@"Failed to make command params");
#endif
}
}
else {
#if DEBUG
NSLog(@"No command manager");
#endif
}
}
-(BOOL)isCommandEnabled:(const char*)commandName
{
PRBool isEnabled = PR_FALSE;
nsCOMPtr<nsICommandManager> commandMgr(do_GetInterface(_webBrowser));
if (commandMgr) {
nsAutoString commandNameStr;
commandNameStr.AssignWithConversion(commandName);
nsresult rv = commandMgr->IsCommandEnabled(commandNameStr, &isEnabled);
#if DEBUG
if (NS_FAILED(rv))
NSLog(@"IsCommandEnabled failed");
#endif
}
else {
#if DEBUG
NSLog(@"No command manager");
#endif
}
return (isEnabled) ? YES : NO;
}
-(IBAction)cut:(id)aSender
{
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->CutSelection();
}
-(BOOL)canCut
{
PRBool canCut = PR_FALSE;
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->CanCutSelection(&canCut);
return canCut;
}
-(IBAction)copy:(id)aSender
{
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->CopySelection();
}
-(BOOL)canCopy
{
PRBool canCut = PR_FALSE;
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->CanCopySelection(&canCut);
return canCut;
}
-(IBAction)paste:(id)aSender
{
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->Paste();
}
-(BOOL)canPaste
{
PRBool canCut = PR_FALSE;
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->CanPaste(&canCut);
return canCut;
}
-(IBAction)delete:(id)aSender
{
[self doCommand: "cmd_delete"];
}
-(BOOL)canDelete
{
return [self isCommandEnabled: "cmd_delete"];
}
-(IBAction)selectAll:(id)aSender
{
nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(_webBrowser));
clipboard->SelectAll();
}
-(IBAction)undo:(id)aSender
{
[self doCommand: "cmd_undo"];
}
-(IBAction)redo:(id)aSender
{
[self doCommand: "cmd_redo"];
}
- (BOOL)canUndo
{
return [self isCommandEnabled: "cmd_undo"];
}
- (BOOL)canRedo
{
return [self isCommandEnabled: "cmd_redo"];
}
-(NSString*)getCurrentURLSpec
{
NSString* empty = @"";
nsCOMPtr<nsIDOMWindow> domWindow;
_webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow)
return empty;
nsCOMPtr<nsIDOMDocument> domDocument;
domWindow->GetDocument(getter_AddRefs(domDocument));
if (!domDocument)
return empty;
nsCOMPtr<nsIDOMNSDocument> nsDoc(do_QueryInterface(domDocument));
if (!nsDoc)
return empty;
nsCOMPtr<nsIDOMLocation> location;
nsDoc->GetLocation(getter_AddRefs(location));
if (!location)
return empty;
nsAutoString urlStr;
location->GetHref(urlStr);
return [NSString stringWith_nsAString: urlStr];
}
- (void)setActive: (BOOL)aIsActive
{
nsCOMPtr<nsIWebBrowserFocus> wbf(do_QueryInterface(_webBrowser));
if (aIsActive)
wbf->Activate();
else
wbf->Deactivate();
}
-(NSMenu*)getContextMenu
{
if ([[self superview] conformsToProtocol:@protocol(NSBrowserContainer)])
{
id<NSBrowserContainer> browserContainer = [self superview];
return [browserContainer getContextMenu];
}
return nil;
}
-(NSWindow*)getNativeWindow
{
NSWindow* window = [self window];
if (window)
return window; // We're visible. Just hand the window back.
// We're invisible. It's likely that we're in a Cocoa tab view.
// First see if we have a cached window.
if (mWindow)
return mWindow;
// Finally, see if our parent responds to the getNativeWindow selector,
// and if they do, let them handle it.
if ([[self superview] conformsToProtocol:@protocol(NSBrowserContainer)])
{
id<NSBrowserContainer> browserContainer = [self superview];
return [browserContainer getNativeWindow];
}
return nil;
}
//
// -findEventSink:forPoint:inWindow:
//
// Given a point in window coordinates, find the Gecko event sink of the ChildView
// the point is over. This involves first converting the point to this view's
// coordinate system and using hitTest: to get the subview. Then we get
// that view's widget and QI it to an event sink
//
- (void) findEventSink:(nsIEventSink**)outSink forPoint:(NSPoint)inPoint inWindow:(NSWindow*)inWind
{
NSPoint localPoint = [self convertPoint:inPoint fromView:[inWind contentView]];
NSView<mozView>* hitView = [self hitTest:localPoint];
if ( [hitView conformsToProtocol:@protocol(mozView)] ) {
nsCOMPtr<nsIEventSink> sink (do_QueryInterface([hitView widget]));
*outSink = sink.get();
NS_IF_ADDREF(*outSink);
}
}
#pragma mark -
- (BOOL)shouldAcceptDrag:(id <NSDraggingInfo>)sender
{
if ([[self superview] conformsToProtocol:@protocol(NSBrowserContainer)])
{
id<NSBrowserContainer> browserContainer = [self superview];
return [browserContainer shouldAcceptDragFromSource:[sender draggingSource]];
}
return YES;
}
- (unsigned int)draggingEntered:(id <NSDraggingInfo>)sender
{
if (![self shouldAcceptDrag:sender])
return NSDragOperationNone;
// NSLog(@"draggingEntered");
nsCOMPtr<nsIDragHelperService> helper(do_GetService("@mozilla.org/widget/draghelperservice;1"));
mDragHelper = helper.get();
NS_IF_ADDREF(mDragHelper);
NS_ASSERTION ( mDragHelper, "Couldn't get a drag service, we're in big trouble" );
if ( mDragHelper ) {
mLastTrackedLocation = [sender draggingLocation];
mLastTrackedWindow = [sender draggingDestinationWindow];
nsCOMPtr<nsIEventSink> sink;
[self findEventSink:getter_AddRefs(sink) forPoint:mLastTrackedLocation inWindow:mLastTrackedWindow];
if (sink)
mDragHelper->Enter ( [sender draggingSequenceNumber], sink );
}
return NSDragOperationCopy;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{
// NSLog(@"draggingExited");
if ( mDragHelper ) {
nsCOMPtr<nsIEventSink> sink;
[self findEventSink:getter_AddRefs(sink)
forPoint:mLastTrackedLocation /* [sender draggingLocation] */
inWindow:mLastTrackedWindow /* [sender draggingDestinationWindow] */
];
if (sink)
mDragHelper->Leave( [sender draggingSequenceNumber], sink );
NS_RELEASE(mDragHelper);
}
}
- (unsigned int)draggingUpdated:(id <NSDraggingInfo>)sender
{
if (![self shouldAcceptDrag:sender])
return NSDragOperationNone;
// NSLog(@"draggingUpdated");
PRBool dropAllowed = PR_FALSE;
if ( mDragHelper ) {
mLastTrackedLocation = [sender draggingLocation];
mLastTrackedWindow = [sender draggingDestinationWindow];
nsCOMPtr<nsIEventSink> sink;
[self findEventSink:getter_AddRefs(sink) forPoint:mLastTrackedLocation inWindow:mLastTrackedWindow];
if (sink)
mDragHelper->Tracking([sender draggingSequenceNumber], sink, &dropAllowed);
}
return dropAllowed ? NSDragOperationCopy : NSDragOperationNone;
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
return YES;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
if (![self shouldAcceptDrag:sender])
return NO;
PRBool dragAccepted = PR_FALSE;
if ( mDragHelper ) {
nsCOMPtr<nsIEventSink> sink;
[self findEventSink:getter_AddRefs(sink) forPoint:[sender draggingLocation]
inWindow:[sender draggingDestinationWindow]];
if (sink)
mDragHelper->Drop([sender draggingSequenceNumber], sink, &dragAccepted);
}
return dragAccepted ? YES : NO;
}
#pragma mark -
-(BOOL)validateMenuItem: (NSMenuItem*)aMenuItem
{
// update first responder items based on the selection
SEL action = [aMenuItem action];
if (action == @selector(cut:))
return [self canCut];
else if (action == @selector(copy:))
return [self canCopy];
else if (action == @selector(paste:))
return [self canPaste];
else if (action == @selector(delete:))
return [self canDelete];
else if (action == @selector(undo:))
return [self canUndo];
else if (action == @selector(redo:))
return [self canRedo];
else if (action == @selector(selectAll:))
return YES;
return NO;
}
@end

View File

@ -1,118 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
#import "CHBrowserView.h"
@class BrowserWindowController;
@class ToolTip;
@interface CHBrowserWrapper : NSView <NSBrowserListener, NSBrowserContainer>
{
NSTextField* mUrlbar;
NSTextField* mStatus;
NSProgressIndicator* mProgress;
NSView* mProgressSuper;
BrowserWindowController* mWindowController;
NSTabViewItem* mTabItem;
NSWindow* mWindow;
NSImage* mSiteIconImage; // current proxy icon image, which may be a site icon (favicon).
NSString* mSiteIconURI; // uri from which we loaded the site icon
// the secure state of this browser. We need to hold it so that we can set
// the global lock icon whenever we become the primary. Value is one of
// security enums in nsIWebProgressListener.
unsigned long mSecureState;
// the title associated with this tab's url. We need to hold it so that we
// can set the window title whenever we become the primary.
NSString* mTitle;
CHBrowserView* mBrowserView;
NSString* mDefaultStatusString;
NSString* mLoadingStatusString;
ToolTip* mToolTip;
BOOL mIsPrimary;
BOOL mIsBusy;
BOOL mOffline;
BOOL mListenersAttached; // We hook up our click and context menu listeners lazily.
// If we never become the primary view, we don't bother creating the listeners.
BOOL mIsBookmarksImport; // This view was created for the purpose of importing bookmarks. Upon
// completion, we need to do the import and then destroy ourselves.
BOOL mActivateOnLoad; // If set, activate the browser view when loading starts.
}
- (id)initWithTab:(NSTabViewItem*)aTab andWindow:(NSWindow*)aWindow;
- (IBAction)load:(id)sender;
- (void)awakeFromNib;
- (void)setFrame:(NSRect)frameRect;
- (CHBrowserView*)getBrowserView;
- (BOOL)isBusy;
- (void)windowClosed;
- (NSString*)getCurrentURLSpec;
- (void)loadURI:(NSString *)urlSpec referrer:(NSString*)referrer flags:(unsigned int)flags activate:(BOOL)activate;
- (void)makePrimaryBrowserView: (id)aUrlbar status: (id)aStatus
progress: (id)aProgress windowController: (BrowserWindowController*)aWindowController;
- (void)disconnectView;
- (void)setTab: (NSTabViewItem*)tab;
- (NSWindow*)getNativeWindow;
- (NSMenu*)getContextMenu;
- (void)setIsBookmarksImport:(BOOL)aIsImport;
// NSBrowserListener messages
- (void)onLoadingStarted;
- (void)onLoadingCompleted:(BOOL)succeeded;
- (void)onProgressChange:(int)currentBytes outOf:(int)maxBytes;
- (void)onLocationChange:(NSString*)urlSpec;
- (void)onStatusChange:(NSString*)aMessage;
- (void)onSecurityStateChange:(unsigned long)newState;
- (void)onShowTooltip:(NSPoint)where withText:(NSString*)text;
- (void)onHideTooltip;
// NSBrowserContainer messages
- (void)setStatus:(NSString *)statusString ofType:(NSStatusType)type;
- (NSString *)title;
- (void)setTitle:(NSString *)title;
- (void)sizeBrowserTo:(NSSize)dimensions;
- (CHBrowserView*)createBrowserWindow:(unsigned int)mask;
@end

View File

@ -1,692 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "CHPreferenceManager.h"
#import "CHBrowserWrapper.h"
#import "BrowserWindowController.h"
#import "BookmarksService.h"
#import "SiteIconProvider.h"
#import "BrowserTabViewItem.h"
#import "ToolTip.h"
#import "CHPageProxyIcon.h"
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsIIOService.h"
#include "ContentClickListener.h"
#include "nsIDOMWindow.h"
#include "nsIWebBrowser.h"
#include "nsIDOMDocument.h"
#include "nsIDOMHTMLDocument.h"
#include "nsIChromeEventHandler.h"
#include "nsPIDOMWindow.h"
#include "nsIDOMEventReceiver.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsCocoaBrowserService.h"
#include "nsIWebProgressListener.h"
#include <QuickDraw.h>
#define DOCUMENT_DONE_STRING @"Document: Done"
static const char* ioServiceContractID = "@mozilla.org/network/io-service;1";
const NSString* kOfflineNotificationName = @"offlineModeChanged";
@interface CHBrowserWrapper(Private)
- (void)setPendingActive:(BOOL)active;
- (void)registerNotificationListener;
- (void)setSiteIconImage:(NSImage*)inSiteIcon;
- (void)setSiteIconURI:(NSString*)inSiteIconURI;
- (void)updateSiteIconImage:(NSImage*)inSiteIcon withURI:(NSString *)inSiteIconURI;
@end
@implementation CHBrowserWrapper
- (id)initWithTab:(NSTabViewItem*)aTab andWindow:(NSWindow*)aWindow
{
mTabItem = aTab;
mWindow = aWindow;
mIsBookmarksImport = NO;
return [self initWithFrame: NSZeroRect];
}
//
// initWithFrame: (designated initializer)
//
// Create a Gecko browser view and hook everything up to the UI
//
- (id)initWithFrame:(NSRect)frameRect
{
if ( (self = [super initWithFrame: frameRect]) ) {
mBrowserView = [[[CHBrowserView alloc] initWithFrame:[self bounds] andWindow: [self getNativeWindow]] autorelease];
[self addSubview: mBrowserView];
[mBrowserView setContainer:self];
[mBrowserView addListener:self];
mIsBusy = NO;
mListenersAttached = NO;
mSecureState = nsIWebProgressListener::STATE_IS_INSECURE;
mToolTip = [[ToolTip alloc] init];
//[self setSiteIconImage:[NSImage imageNamed:@"globe_ico"]];
//[self setSiteIconURI: [NSString string]];
[self registerNotificationListener];
}
return self;
}
-(void)dealloc
{
#if DEBUG
NSLog(@"The browser wrapper died.");
#endif
[[NSNotificationCenter defaultCenter] removeObserver: self];
[mSiteIconImage release];
[mSiteIconURI release];
[mDefaultStatusString release];
[mLoadingStatusString release];
[mToolTip release];
[super dealloc];
}
-(void)windowClosed
{
// Break the cycle.
[mBrowserView destroyWebBrowser];
[mBrowserView setContainer: nil];
[mBrowserView removeListener: self];
}
- (IBAction)load:(id)sender
{
[mBrowserView loadURI:[mUrlbar stringValue] referrer:nil flags:NSLoadFlagsNone];
}
-(void)disconnectView
{
mUrlbar = nil;
mStatus = nil;
mProgress = nil;
mProgressSuper = nil;
mIsPrimary = NO;
[[NSNotificationCenter defaultCenter] removeObserver:self name:kOfflineNotificationName object:nil];
[mBrowserView setActive: NO];
}
-(void)setTab: (NSTabViewItem*)tab
{
mTabItem = tab;
}
-(void)makePrimaryBrowserView: (id)aUrlbar status: (id)aStatus
progress: (id)aProgress windowController: (BrowserWindowController*)aWindowController
{
mUrlbar = aUrlbar;
mStatus = aStatus;
mProgress = aProgress;
mProgressSuper = [aProgress superview];
mWindowController = aWindowController;
if (!mIsBusy)
[mProgress removeFromSuperview];
mDefaultStatusString = NULL;
mLoadingStatusString = DOCUMENT_DONE_STRING;
[mStatus setStringValue:mLoadingStatusString];
mIsPrimary = YES;
// update the global lock icon to the current state of this browser. We need
// to do this after we set |mIsPrimary|.
[self onSecurityStateChange:mSecureState];
// update the window's title.
[self setTitle:mTitle];
if ([[self window] isKeyWindow])
[mBrowserView setActive: YES];
nsCOMPtr<nsIIOService> ioService(do_GetService(ioServiceContractID));
if (!ioService)
return;
PRBool offline = PR_FALSE;
ioService->GetOffline(&offline);
mOffline = offline;
if (mWindowController) // Only register if we're the content area.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(offlineModeChanged:)
name:kOfflineNotificationName
object:nil];
// Update the URL bar.
[mWindowController updateLocationFields:[self getCurrentURLSpec]];
[mWindowController updateSiteIcons:mSiteIconImage];
if (mWindowController && !mListenersAttached) {
mListenersAttached = YES;
// We need to hook up our click and context menu listeners.
ContentClickListener* clickListener = new ContentClickListener(mWindowController);
if (!clickListener)
return;
nsCOMPtr<nsIDOMWindow> contentWindow = getter_AddRefs([[self getBrowserView] getContentWindow]);
nsCOMPtr<nsPIDOMWindow> piWindow(do_QueryInterface(contentWindow));
nsCOMPtr<nsIChromeEventHandler> chromeHandler;
piWindow->GetChromeEventHandler(getter_AddRefs(chromeHandler));
nsCOMPtr<nsIDOMEventReceiver> rec(do_QueryInterface(chromeHandler));
rec->AddEventListenerByIID(clickListener, NS_GET_IID(nsIDOMMouseListener));
}
}
-(NSString*)getCurrentURLSpec
{
return [mBrowserView getCurrentURLSpec];
}
- (void)awakeFromNib
{
}
- (void)setFrame:(NSRect)frameRect
{
[super setFrame:frameRect];
// Only resize our browser view if we are visible. If we're hidden, the frame
// will get reset when we get placed back into the view hierarchy anyway. This
// enhancement keeps resizing in a window with many tabs from being slow.
if ([self window]) {
NSRect bounds = [self bounds];
[mBrowserView setFrame:bounds];
}
}
-(BOOL)isBusy
{
return mIsBusy;
}
- (void)loadURI:(NSString *)urlSpec referrer:(NSString*)referrer flags:(unsigned int)flags activate:(BOOL)activate
{
mActivateOnLoad = activate;
[mBrowserView loadURI:urlSpec referrer:referrer flags:flags];
}
- (void)onLoadingStarted
{
if (mDefaultStatusString) {
[mDefaultStatusString release];
mDefaultStatusString = NULL;
}
[mProgressSuper addSubview:mProgress];
[mProgress setIndeterminate:YES];
[mProgress startAnimation:self];
mLoadingStatusString = NSLocalizedString(@"TabLoading", @"");
[mStatus setStringValue:mLoadingStatusString];
mIsBusy = YES;
[mTabItem setLabel: NSLocalizedString(@"TabLoading", @"")];
if (mWindowController) {
[mWindowController updateToolbarItems];
[mWindowController startThrobber];
}
}
- (void)onLoadingCompleted:(BOOL)succeeded
{
if (mActivateOnLoad) {
[mBrowserView setActive:YES];
mActivateOnLoad = NO;
}
[mProgress setIndeterminate:YES];
[mProgress stopAnimation:self];
[mProgress removeFromSuperview];
mLoadingStatusString = DOCUMENT_DONE_STRING;
if (mDefaultStatusString) {
[mStatus setStringValue:mDefaultStatusString];
}
else {
[mStatus setStringValue:mLoadingStatusString];
}
mIsBusy = NO;
if (mIsBookmarksImport) {
nsCOMPtr<nsIDOMWindow> domWindow;
nsCOMPtr<nsIWebBrowser> webBrowser = getter_AddRefs([mBrowserView getWebBrowser]);
webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (domWindow) {
nsCOMPtr<nsIDOMDocument> domDocument;
domWindow->GetDocument(getter_AddRefs(domDocument));
nsCOMPtr<nsIDOMHTMLDocument> htmlDoc(do_QueryInterface(domDocument));
if (htmlDoc)
BookmarksService::ImportBookmarks(htmlDoc);
}
[self windowClosed];
[self removeFromSuperview];
}
if (mWindowController) {
[mWindowController updateToolbarItems];
[mWindowController stopThrobber];
}
}
- (void)onProgressChange:(int)currentBytes outOf:(int)maxBytes
{
if (maxBytes > 0) {
BOOL isIndeterminate = [mProgress isIndeterminate];
if (isIndeterminate) {
[mProgress setIndeterminate:NO];
}
double val = ((double)currentBytes / (double)maxBytes) * 100.0;
[mProgress setDoubleValue:val];
}
}
- (void)onLocationChange:(NSString*)urlSpec
{
BOOL useSiteIcons = [[CHPreferenceManager sharedInstance] getBooleanPref:"browser.chrome.site_icons" withSuccess:NULL];
BOOL siteIconLoadInitiated = NO;
SiteIconProvider* faviconProvider = [SiteIconProvider sharedFavoriteIconProvider];
NSString* faviconURI = [SiteIconProvider faviconLocationStringFromURI:urlSpec];
if (useSiteIcons && [faviconURI length] > 0)
{
// if the favicon uri has changed, fire off favicon load. When it completes, our
// imageLoadedNotification selector gets called.
if (![faviconURI isEqualToString:mSiteIconURI])
siteIconLoadInitiated = [faviconProvider loadFavoriteIcon:self forURI:urlSpec withUserData:nil allowNetwork:YES];
}
else
{
if ([urlSpec isEqualToString:@"about:blank"])
faviconURI = urlSpec;
else
faviconURI = @"";
}
if (!siteIconLoadInitiated)
[self updateSiteIconImage:nil withURI:faviconURI];
if (mIsPrimary)
[mWindowController updateLocationFields:urlSpec];
}
- (void)onStatusChange:(NSString*)aStatusString
{
[mStatus setStringValue: aStatusString];
}
//
// onSecurityStateChange:
//
// Update the lock to the appropriate icon to match what necko is telling us, but
// only if we own the UI. If we're not the primary browser, we have no business
// mucking with the lock icon.
//
- (void)onSecurityStateChange:(unsigned long)newState
{
mSecureState = newState;
if ( mIsPrimary )
[mWindowController updateLock:newState];
}
- (void)setStatus:(NSString *)statusString ofType:(NSStatusType)type
{
if (type == NSStatusTypeScriptDefault) {
if (mDefaultStatusString) {
[mDefaultStatusString release];
}
mDefaultStatusString = statusString;
if (mDefaultStatusString) {
[mDefaultStatusString retain];
}
}
else if (!statusString) {
if (mDefaultStatusString) {
[mStatus setStringValue:mDefaultStatusString];
}
else {
[mStatus setStringValue:mLoadingStatusString];
}
}
else {
[mStatus setStringValue:statusString];
}
}
- (NSString *)title
{
return mTitle;
}
- (void)setTitle:(NSString *)title
{
[mTitle autorelease];
// We must be the primary content area to actually set the title, but we
// still want to hold onto the title in case we become the primary later.
NSString* newTitle = nil;
if (mOffline) {
if (title && ![title isEqualToString:@""])
newTitle = [title stringByAppendingString: @" [Working Offline]"]; // XXX localize me
else
newTitle = [NSString stringWithString:@"Untitled [Working Offline]"];
mTitle = [newTitle retain];
}
else {
if (!title || [title isEqualToString:@""])
title = [NSString stringWithString:NSLocalizedString(@"UntitledPageTitle", @"")];
mTitle = [title retain];
}
if ( mIsPrimary && mWindowController )
[[mWindowController window] setTitle:[mTitle stringByTruncatingTo:80 at:kTruncateAtEnd]];
// Always set the tab.
if (title && ![title isEqualToString:@""])
[mTabItem setLabel:title]; // tab titles get truncated when setting them to tabs
else
[mTabItem setLabel:NSLocalizedString(@"UntitledPageTitle", @"")];
}
- (BOOL)isFlipped
{
return YES;
}
//
// onShowTooltip:where:withText
//
// Unfortunately, we can't use cocoa's apis here because they rely on setting a region
// and waiting. We already have waited and we just want to display the tooltip, so we
// drop down to the Carbon help manager routines.
//
// |where| is relative to the browser view in QD coordinates (top left is (0,0))
// and must be converted to global QD coordinates for the carbon help manager.
//
- (void)onShowTooltip:(NSPoint)where withText:(NSString*)text
{
NSPoint point = [[self window] convertBaseToScreen:[self convertPoint: where toView:nil]];
[mToolTip showToolTipAtPoint: point withString: text];
}
- (void)onHideTooltip
{
[mToolTip closeToolTip];
}
// Called when a context menu should be shown.
- (void)onShowContextMenu:(int)flags domEvent:(nsIDOMEvent*)aEvent domNode:(nsIDOMNode*)aNode
{
[mWindowController onShowContextMenu: flags domEvent: aEvent domNode: aNode];
}
-(NSMenu*)getContextMenu
{
return [mWindowController getContextMenu];
}
-(NSWindow*)getNativeWindow
{
NSWindow* window = [self window];
if (window)
return window;
if (mWindow)
return mWindow;
return nil;
}
- (BOOL)shouldAcceptDragFromSource:(id)dragSource
{
if ((dragSource == self) || (dragSource == mTabItem) || (dragSource == [mWindowController proxyIconView]))
return NO;
if ([mTabItem isMemberOfClass:[BrowserTabViewItem class]] && (dragSource == [(BrowserTabViewItem*)mTabItem tabItemContentsView]))
return NO;
return YES;
}
-(void)setIsBookmarksImport:(BOOL)aIsImport
{
mIsBookmarksImport = aIsImport;
}
- (void)offlineModeChanged: (NSNotification*)aNotification
{
nsCOMPtr<nsIIOService> ioService(do_GetService(ioServiceContractID));
if (!ioService)
return;
PRBool offline = PR_FALSE;
ioService->GetOffline(&offline);
mOffline = offline;
if (mOffline) {
NSString* newTitle = [[[mWindowController window] title] stringByAppendingString: @" [Working Offline]"];
[[mWindowController window] setTitle: newTitle];
}
else {
NSArray* titleItems = [[[mWindowController window] title] componentsSeparatedByString:@" [Working Offline]"];
[[mWindowController window] setTitle: [titleItems objectAtIndex: 0]];
}
}
//
// sizeBrowserTo
//
// Sizes window so that browser has dimensions given by |dimensions|
//
- (void)sizeBrowserTo:(NSSize)dimensions
{
NSRect bounds = [self bounds];
float dx = dimensions.width - bounds.size.width;
float dy = dimensions.height - bounds.size.height;
NSRect frame = [[self window] frame];
NSPoint topLeft = NSMakePoint(NSMinX(frame), NSMaxY(frame));
frame.size.width += dx;
frame.size.height += dy;
// if we just call setFrame, it will change the top-left corner of the
// window as it pulls the extra space from the top and right sides of the window,
// which is not at all what the website desired. We must preserve
// topleft of the window and reset it after we resize.
[[self window] setFrame:frame display:YES];
[[self window] setFrameTopLeftPoint:topLeft];
}
- (CHBrowserView*)createBrowserWindow:(unsigned int)aMask
{
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return NS_OK; // Something bad happened if we can't get prefs.
PRBool showBlocker;
pref->GetBoolPref("browser.popups.showPopupBlocker", &showBlocker);
if (showBlocker) {
nsCOMPtr<nsIDOMWindow> domWindow = getter_AddRefs([mBrowserView getContentWindow]);
nsCOMPtr<nsPIDOMWindow> piWindow(do_QueryInterface(domWindow));
PRBool isUnrequested;
piWindow->IsLoadingOrRunningTimeout(&isUnrequested);
if (isUnrequested) {
// A popup is being opened while the page is currently loading. Offer to block the
// popup.
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
BOOL confirm = [controller confirm: [self window] title: @"Unrequested Popup Detected"
text: [NSString stringWithFormat: NSLocalizedString(@"PopupBlockMsg", @""), NSLocalizedStringFromTable(@"CFBundleName", @"InfoPlist", nil)]];
// This is a one-time dialog.
pref->SetBoolPref("browser.popups.showPopupBlocker", PR_FALSE);
if (confirm) {
pref->SetBoolPref("dom.disable_open_during_load", PR_TRUE);
pref->SetIntPref("dom.disable_open_click_delay", 1000);
}
nsCOMPtr<nsIPrefService> prefService(do_QueryInterface(pref));
prefService->SavePrefFile(nsnull);
if (confirm)
return nil;
}
}
BrowserWindowController* controller = [[BrowserWindowController alloc] initWithWindowNibName: @"BrowserWindow"];
[controller setChromeMask: aMask];
[controller disableAutosave]; // The Web page opened this window, so we don't ever use its settings.
[controller disableLoadPage]; // don't load about:blank initially since this is a script-opened window
[controller enterModalSession];
[[controller getBrowserWrapper] setPendingActive: YES];
return [[controller getBrowserWrapper] getBrowserView];
}
- (CHBrowserView*)getBrowserView
{
return mBrowserView;
}
- (void)setPendingActive:(BOOL)active
{
mActivateOnLoad = active;
}
- (void)setSiteIconImage:(NSImage*)inSiteIcon
{
[mSiteIconImage autorelease];
mSiteIconImage = [inSiteIcon retain];
}
- (void)setSiteIconURI:(NSString*)inSiteIconURI
{
[mSiteIconURI autorelease];
mSiteIconURI = [inSiteIconURI retain];
}
// A nil inSiteIcon image indicates that we should use the default icon
// If inSiteIconURI is "about:blank", we don't show any icon
- (void)updateSiteIconImage:(NSImage*)inSiteIcon withURI:(NSString *)inSiteIconURI
{
BOOL resetTabIcon = NO;
BOOL tabIconDraggable = YES;
if (![mSiteIconURI isEqualToString:inSiteIconURI])
{
if (!inSiteIcon)
{
if ([inSiteIconURI isEqualToString:@"about:blank"]) {
inSiteIcon = [NSImage imageNamed:@"smallDocument"];
tabIconDraggable = NO;
} else
inSiteIcon = [NSImage imageNamed:@"globe_ico"];
}
[self setSiteIconImage: inSiteIcon];
[self setSiteIconURI: inSiteIconURI];
// update the proxy icon
if (mIsPrimary)
[mWindowController updateSiteIcons:mSiteIconImage];
resetTabIcon = YES;
}
// update the tab icon
if ([mTabItem isMemberOfClass:[BrowserTabViewItem class]])
{
BrowserTabViewItem* tabItem = (BrowserTabViewItem*)mTabItem;
if (resetTabIcon || ![tabItem tabIcon])
[tabItem setTabIcon:mSiteIconImage isDraggable:tabIconDraggable];
}
}
- (void)registerNotificationListener
{
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(imageLoadedNotification:)
name: SiteIconLoadNotificationName
object: self];
}
// called when [[SiteIconProvider sharedFavoriteIconProvider] loadFavoriteIcon] completes
- (void)imageLoadedNotification:(NSNotification*)notification
{
NSDictionary* userInfo = [notification userInfo];
if (userInfo)
{
NSImage* iconImage = [userInfo objectForKey:SiteIconLoadImageKey];
NSString* siteIconURI = [userInfo objectForKey:SiteIconLoadURIKey];
// NSLog(@"CHBrowserWrapper imageLoadedNotification got image %@ and uri %@", iconImage, proxyImageURI);
if (iconImage == nil)
siteIconURI = @""; // go back to default image
[self updateSiteIconImage:iconImage withURI:siteIconURI];
}
}
@end

View File

@ -1,50 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
* Max Horn <max@quendi.de> (Context menu & tooltip code)
*/
#import <AppKit/AppKit.h>
@interface CHExtendedOutlineView : NSOutlineView {
SEL mDeleteAction;
NSRect mOldFrameRect;
int mOldRows;
BOOL mDelegateTooltipStringForItem;
}
-(void)keyDown:(NSEvent*)aEvent;
-(void)setDeleteAction: (SEL)deleteAction;
-(SEL)deleteAction;
-(void)setDelegate:(id)anObject;
@end
@interface NSObject (CHOutlineViewDataSourceToolTips)
- (NSString *)outlineView:(NSOutlineView *)outlineView tooltipStringForItem:(id)item;
@end
@interface NSObject (CHOutlineViewContextMenus)
- (NSMenu *)outlineView:(NSOutlineView *)outlineView contextMenuForItem:(id)item;
@end

View File

@ -1,236 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
* Max Horn <max@quendi.de> (Context menu & tooltip code)
*/
#import "CHExtendedOutlineView.h"
@interface CHExtendedOutlineView (Private)
- (void)_updateToolTipRect;
@end
@implementation CHExtendedOutlineView
- (id)initWithFrame:(NSRect)frame
{
if ( (self = [super initWithFrame:frame]) ) {
mDeleteAction = 0;
// FIXME - this method is *never* called for items that are archived in a nib!
// Luckily, object memory is zeroed, so mDeleteAction will be 0 anyway.
// I recommend that this method just be removed.
}
return self;
}
- (void)awakeFromNib {
// Setup the initial NSToolTipRects
[self _updateToolTipRect];
}
-(void)setDeleteAction: (SEL)aDeleteAction
{
mDeleteAction = aDeleteAction;
}
-(SEL)deleteAction
{
return mDeleteAction;
}
-(void)setDelegate:(id)anObject
{
[super setDelegate:anObject];
mDelegateTooltipStringForItem = [anObject respondsToSelector:@selector(outlineView:tooltipStringForItem:)];
}
-(void)keyDown:(NSEvent*)aEvent
{
// check each char in the event array. it should be just 1 char, but
// just in case we use a loop.
int len = [[aEvent characters] length];
for ( int i = 0; i < len; ++i ) {
unichar c = [[aEvent characters] characterAtIndex:i];
// Check for a certain set of special keys.
if (c == NSDeleteCharacter || c == NSBackspaceCharacter) {
// delete the bookmark
if (mDeleteAction)
[NSApp sendAction: mDeleteAction to: [self target] from: self];
return;
}
else if (c == NSCarriageReturnCharacter) {
// Start editing
if ([self numberOfSelectedRows] == 1) {
[self editColumn:0 row:[self selectedRow] withEvent:aEvent select:YES];
return;
}
}
else if (c == NSLeftArrowFunctionKey || c == NSRightArrowFunctionKey)
{
BOOL expand = (c == NSRightArrowFunctionKey);
if ([self numberOfSelectedRows] == 1) {
int index = [self selectedRow];
if (index == -1)
return;
id item = [self itemAtRow: index];
if (!item)
return;
if (![self isExpandable: item])
return;
if (![self isItemExpanded: item] && expand)
[self expandItem: item];
else if ([self isItemExpanded: item] && !expand)
[self collapseItem: item];
}
}
} // foreach character
return [super keyDown: aEvent];
}
/*
* Intercept changes to the window frame so we can update our tooltip rects
*/
- (void)setFrameOrigin:(NSPoint)newOrigin;
{
[super setFrameOrigin:newOrigin];
[self _updateToolTipRect];
}
- (void)setFrameSize:(NSSize)newSize;
{
[super setFrameSize:newSize];
[self _updateToolTipRect];
}
- (void)setFrame:(NSRect)frameRect
{
[super setFrame:frameRect];
[self _updateToolTipRect];
}
/*
* Implement the informal NSToolTipOwner protocol to allow tooltips
* on a per-item level.
*/
- (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
{
NSString *result = nil;
int rowIndex = [self rowAtPoint:point];
if (rowIndex >= 0) {
id delegate = [self delegate];
id item = [self itemAtRow:rowIndex];
if (item && mDelegateTooltipStringForItem)
result = [delegate outlineView:self tooltipStringForItem:item];
}
return result;
}
/*
* Return a context menu depending on which item was clicked.
*/
- (NSMenu *)menuForEvent:(NSEvent *)theEvent
{
id item;
int rowIndex;
NSPoint point;
point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
rowIndex = [self rowAtPoint:point];
if (rowIndex >= 0) {
// There seems to be a bug in AppKit; selectRow is supposed to
// abort editing, but it doesn't, thus we do it manually.
[self abortEditing];
item = [self itemAtRow:rowIndex];
if (item) {
id delegate = [self delegate];
// If the item was not selected, select it now
if (![self isRowSelected:rowIndex]) {
if (![delegate respondsToSelector:@selector(outlineView:shouldSelectItem:)]
|| [delegate outlineView:self shouldSelectItem:item])
[self selectRow:rowIndex byExtendingSelection:NO];
}
if ([delegate respondsToSelector:@selector(outlineView:contextMenuForItem:)])
return [delegate outlineView:self contextMenuForItem:item];
}
}
// Just return the default context menu
return [self menu];
}
@end
@implementation CHExtendedOutlineView (Private)
/*
* Set up tooltip rects for every row, but only if the frame size or
* the number of rows changed since the last invocation.
*/
- (void)_updateToolTipRect
{
static NSRect oldFrameRect;
static int oldRows = 0;
NSRect frameRect;
int rows;
// Only set tooltip rects if the delegate implements outlineView:tooltipStringForItem:
if (!mDelegateTooltipStringForItem)
return;
frameRect = [self frame];
rows = [self numberOfRows];
// Check if rows or frame changed
if (rows != oldRows || !NSEqualRects(oldFrameRect, frameRect))
{
int i;
NSRect rect;
// Remove all old NSToolTipRects
[self removeAllToolTips];
// Add a NSToolTipRect for each row
for (i = 0; i < rows; ++i)
{
rect = [self rectOfRow:i];
[self addToolTipRect:rect owner:self userData:NULL];
}
}
// Save the current values
oldRows = rows;
oldFrameRect = frameRect;
}
@end

View File

@ -1,38 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Mike Pinkerton <pinkerton@netscape.com> (Original Author)
*/
#import <Cocoa/Cocoa.h>
//
// protocol CHFind
//
// Any window who wants to be able to work with the Find dialog should implement
// this protocol.
//
@protocol CHFind
- (BOOL)findInPageWithPattern:(NSString*)text caseSensitive:(BOOL)inCaseSensitive
wrap:(BOOL)inWrap backwards:(BOOL)inBackwards;
@end

View File

@ -1,179 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __GeckoUtils_h__
#define __GeckoUtils_h__
#include "nsIDOMHTMLAnchorElement.h"
#include "nsIDOMHTMLAreaElement.h"
#include "nsIDOMHTMLLinkElement.h"
#include "nsIDOMHTMLImageElement.h"
#include "nsIDOMCharacterData.h"
class CHGeckoUtils
{
public:
static void GatherTextUnder(nsIDOMNode* aNode, nsString& aResult) {
nsAutoString text;
nsCOMPtr<nsIDOMNode> node;
aNode->GetFirstChild(getter_AddRefs(node));
PRUint32 depth = 1;
while (node && depth) {
nsCOMPtr<nsIDOMCharacterData> charData(do_QueryInterface(node));
PRUint16 nodeType;
node->GetNodeType(&nodeType);
if (charData && nodeType == nsIDOMNode::TEXT_NODE) {
// Add this text to our collection.
text += NS_LITERAL_STRING(" ");
nsAutoString data;
charData->GetData(data);
text += data;
}
else {
nsCOMPtr<nsIDOMHTMLImageElement> img(do_QueryInterface(node));
if (img) {
nsAutoString altText;
img->GetAlt(altText);
if (!altText.IsEmpty()) {
text = altText;
break;
}
}
}
// Find the next node to test.
PRBool hasChildNodes;
node->HasChildNodes(&hasChildNodes);
if (hasChildNodes) {
nsCOMPtr<nsIDOMNode> temp = node;
temp->GetFirstChild(getter_AddRefs(node));
depth++;
}
else {
nsCOMPtr<nsIDOMNode> nextSibling;
node->GetNextSibling(getter_AddRefs(nextSibling));
if (nextSibling)
node = nextSibling;
else {
nsCOMPtr<nsIDOMNode> parentNode;
node->GetParentNode(getter_AddRefs(parentNode));
if (!parentNode)
node = nsnull;
else {
nsCOMPtr<nsIDOMNode> nextSibling;
parentNode->GetNextSibling(getter_AddRefs(nextSibling));
node = nextSibling;
depth--;
}
}
}
}
text.CompressWhitespace();
aResult = text;
};
static void GetEnclosingLinkElementAndHref(nsIDOMNode* aNode, nsIDOMElement** aLinkContent, nsString& aHref)
{
nsCOMPtr<nsIDOMElement> content(do_QueryInterface(aNode));
nsAutoString localName;
if (content)
content->GetLocalName(localName);
nsCOMPtr<nsIDOMElement> linkContent;
ToLowerCase(localName);
nsAutoString href;
if (localName.Equals(NS_LITERAL_STRING("a")) ||
localName.Equals(NS_LITERAL_STRING("area")) ||
localName.Equals(NS_LITERAL_STRING("link"))) {
PRBool hasAttr;
content->HasAttribute(NS_LITERAL_STRING("href"), &hasAttr);
if (hasAttr) {
linkContent = content;
nsCOMPtr<nsIDOMHTMLAnchorElement> anchor(do_QueryInterface(linkContent));
if (anchor)
anchor->GetHref(href);
else {
nsCOMPtr<nsIDOMHTMLAreaElement> area(do_QueryInterface(linkContent));
if (area)
area->GetHref(href);
else {
nsCOMPtr<nsIDOMHTMLLinkElement> link(do_QueryInterface(linkContent));
if (link)
link->GetHref(href);
}
}
}
}
else {
nsCOMPtr<nsIDOMNode> curr = aNode;
nsCOMPtr<nsIDOMNode> temp = curr;
temp->GetParentNode(getter_AddRefs(curr));
while (curr) {
content = do_QueryInterface(curr);
if (!content)
break;
content->GetLocalName(localName);
ToLowerCase(localName);
if (localName.Equals(NS_LITERAL_STRING("a"))) {
PRBool hasAttr;
content->HasAttribute(NS_LITERAL_STRING("href"), &hasAttr);
if (hasAttr) {
linkContent = content;
nsCOMPtr<nsIDOMHTMLAnchorElement> anchor(do_QueryInterface(linkContent));
if (anchor)
anchor->GetHref(href);
}
else
linkContent = nsnull; // Links can't be nested.
break;
}
temp = curr;
temp->GetParentNode(getter_AddRefs(curr));
}
}
*aLinkContent = linkContent;
NS_IF_ADDREF(*aLinkContent);
aHref = href;
}
};
#endif

View File

@ -1,30 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import <Foundation/Foundation.h>
@interface CHGetURLCommand : NSScriptCommand {}
- (id)performDefaultImplementation;
@end

View File

@ -1,37 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import "CHGetURLCommand.h"
#import <AppKit/AppKit.h>
#import "MainController.h"
@implementation CHGetURLCommand
- (id)performDefaultImplementation
{
[(MainController*)[NSApp delegate] openNewWindowOrTabWithURL:[self directParameter] andReferrer:nil];
return nil;
}
@end

View File

@ -1,36 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import <Appkit/Appkit.h>
@interface CHGoMenu : NSMenu {
}
- (void) emptyHistoryItems;
- (void) addHistoryItems;
// NSMenu
- (void) update;
@end

View File

@ -1,144 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import "NSString+Utils.h"
#import "CHGoMenu.h"
#import "MainController.h"
#import "BrowserWindowController.h"
#import "CHBrowserWrapper.h"
#import "CHBrowserView.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsIWebBrowser.h"
#include "nsISHistory.h"
#include "nsIWebNavigation.h"
#include "nsIHistoryEntry.h"
#include "nsCRT.h"
// the tag of the separator after which to insert history menu items
static const int kDividerTag = 4000;
// the maximum number of history entry menuitems to display
static const int kMaxItems = 15;
// the maximum number of characters in a menu title before cropping it
static const unsigned int kMaxTitleLength = 80;
@implementation CHGoMenu
- (void) update
{
[self emptyHistoryItems];
[self addHistoryItems];
[super update];
}
- (nsIWebNavigation*) currentWebNavigation
{
// get controller for current window
BrowserWindowController *controller = [(MainController *)[NSApp delegate] getMainWindowBrowserController];
if (!controller) return nsnull;
// get web navigation for current browser
CHBrowserWrapper* wrapper = [controller getBrowserWrapper];
if (!wrapper) return nsnull;
CHBrowserView* view = [wrapper getBrowserView];
if (!view) return nsnull;
nsCOMPtr<nsIWebBrowser> webBrowser = [view getWebBrowser];
if (!webBrowser) return nsnull;
nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(webBrowser));
return webNav.get();
}
- (void) historyItemAction:(id)sender
{
// get web navigation for current browser
nsCOMPtr<nsIWebNavigation> webNav = [self currentWebNavigation];
if (!webNav) return;
// browse to the history entry for the menuitem that was selected
PRInt32 historyIndex = ([sender tag] - 1) - kDividerTag;
webNav->GotoIndex(historyIndex);
}
- (void) emptyHistoryItems
{
// remove every history item after the insertion point
int insertionIndex = [self indexOfItemWithTag:kDividerTag];
for (int i = [self numberOfItems]-1; i > insertionIndex ; --i) {
[self removeItemAtIndex:i];
}
}
- (void) addHistoryItems
{
// get session history for current browser
nsCOMPtr<nsIWebNavigation> webNav = [self currentWebNavigation];
if (!webNav) return;
nsCOMPtr<nsISHistory> sessionHistory;
webNav->GetSessionHistory(getter_AddRefs(sessionHistory));
PRInt32 count;
sessionHistory->GetCount(&count);
PRInt32 currentIndex;
sessionHistory->GetIndex(&currentIndex);
// determine the range of items to display
int rangeStart, rangeEnd;
int above = kMaxItems/2;
int below = (kMaxItems-above)-1;
if (count <= kMaxItems) {
// if the whole history fits within our menu, fit range to show all
rangeStart = count-1;
rangeEnd = 0;
} else {
// if the whole history is too large for menu, try to put current index as close to
// the middle of the list as possible, so the user can see both back and forward in session
rangeStart = currentIndex + above;
rangeEnd = currentIndex - below;
if (rangeStart >= count-1) {
rangeEnd -= (rangeStart-count)+1; // shift overflow to the end
rangeStart = count-1;
} else if (rangeEnd < 0) {
rangeStart -= rangeEnd; // shift overflow to the start
rangeEnd = 0;
}
}
// create a new menu item for each history entry (up to MAX_MENUITEM entries)
for (PRInt32 i = rangeStart; i >= rangeEnd; --i) {
nsCOMPtr<nsIHistoryEntry> entry;
sessionHistory->GetEntryAtIndex(i, PR_FALSE, getter_AddRefs(entry));
nsXPIDLString textStr;
entry->GetTitle(getter_Copies(textStr));
NSString* title = [[NSString stringWith_nsAString: textStr] stringByTruncatingTo:kMaxTitleLength at:kTruncateAtMiddle];
NSMenuItem *newItem = [self addItemWithTitle:title action:@selector(historyItemAction:) keyEquivalent:@""];
[newItem setTarget:self];
[newItem setTag:kDividerTag+1+i];
if (currentIndex == i)
[newItem setState:NSOnState];
}
}
@end

View File

@ -1,24 +0,0 @@
//
// CHHistoryDataSource.h
// Chimera
//
// Created by Ben Goodger on Sun Apr 28 2002.
// Copyright (c) 2001 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CHRDFOutlineViewDataSource.h"
@class BrowserWindowController;
@interface CHHistoryDataSource : CHRDFOutlineViewDataSource
{
IBOutlet BrowserWindowController* mBrowserWindowController;
}
-(IBAction)openHistoryItem: (id)aSender;
@end

View File

@ -1,160 +0,0 @@
//
// CHHistoryDataSource.mm
// Chimera
//
// Created by Ben Goodger on Sun Apr 28 2002.
// Copyright (c) 2001 __MyCompanyName__. All rights reserved.
//
#import "NSString+Utils.h"
#import "BrowserWindowController.h"
#import "CHHistoryDataSource.h"
#import "CHBrowserView.h"
#include "nsIRDFService.h"
#include "nsIRDFDataSource.h"
#include "nsIRDFResource.h"
#include "nsXPIDLString.h"
#include "nsString.h"
#include "nsComponentManagerUtils.h"
@implementation CHHistoryDataSource
- (void) ensureDataSourceLoaded
{
[super ensureDataSourceLoaded];
if (!mDataSource)
{
// Get the Global History DataSource
mRDFService->GetDataSource("rdf:history", &mDataSource);
// Get the Date Folder Root
mRDFService->GetResource("NC:HistoryByDate", &mRootResource);
[mOutlineView setTarget: self];
[mOutlineView setDoubleAction: @selector(openHistoryItem:)];
[mOutlineView reloadData];
}
}
- (id) outlineView: (NSOutlineView*) aOutlineView objectValueForTableColumn: (NSTableColumn*) aTableColumn
byItem: (id) aItem
{
NSMutableAttributedString *cellValue = [[NSMutableAttributedString alloc] init];
if (!mDataSource || !aItem)
return nil;
// The table column's identifier is the RDF Resource URI of the property being displayed in
// that column, e.g. "http://home.netscape.com/NC-rdf#Name"
NSString* columnPropertyURI = [aTableColumn identifier];
nsCOMPtr<nsIRDFResource> propertyResource;
mRDFService->GetResource([columnPropertyURI UTF8String], getter_AddRefs(propertyResource));
nsCOMPtr<nsIRDFResource> resource = dont_AddRef([aItem resource]);
nsCOMPtr<nsIRDFNode> valueNode;
mDataSource->GetTarget(resource, propertyResource, PR_TRUE, getter_AddRefs(valueNode));
if (!valueNode) {
#if DEBUG
NSLog(@"ValueNode is null in objectValueForTableColumn");
#endif
return nil;
}
nsCOMPtr<nsIRDFLiteral> valueLiteral(do_QueryInterface(valueNode));
if (!valueLiteral)
return nil;
nsXPIDLString literalValue;
valueLiteral->GetValue(getter_Copies(literalValue));
//Set cell's textual contents
[cellValue replaceCharactersInRange:NSMakeRange(0, [cellValue length]) withString:[NSString stringWith_nsAString:literalValue]];
if ([columnPropertyURI isEqualToString: @"http://home.netscape.com/NC-rdf#Name"])
{
NSMutableAttributedString *attachmentAttrString = nil;
NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:nil];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];
NSCell *attachmentAttrStringCell;
//Create an attributed string to hold the empty attachment, then release the components.
attachmentAttrString = [[NSMutableAttributedString attributedStringWithAttachment:textAttachment] retain];
[textAttachment release];
[fileWrapper release];
//Get the cell of the text attachment.
attachmentAttrStringCell = (NSCell *)[(NSTextAttachment *)[attachmentAttrString attribute:
NSAttachmentAttributeName atIndex:0 effectiveRange:nil] attachmentCell];
if ([self outlineView:mOutlineView isItemExpandable:aItem]) {
[attachmentAttrStringCell setImage:[NSImage imageNamed:@"folder"]];
}
else
[attachmentAttrStringCell setImage:[NSImage imageNamed:@"smallbookmark"]];
//Insert the image
[cellValue replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attachmentAttrString];
//Tweak the baseline to vertically center the text.
[cellValue addAttribute:NSBaselineOffsetAttributeName
value:[NSNumber numberWithFloat:-5.0]
range:NSMakeRange(0, 1)];
}
return cellValue;
}
-(IBAction)openHistoryItem: (id)aSender
{
int index = [mOutlineView selectedRow];
if (index == -1)
return;
id item = [mOutlineView itemAtRow: index];
if (!item)
return;
// expand if collapsed and double click
if ([mOutlineView isExpandable: item]) {
if ([mOutlineView isItemExpanded: item])
[mOutlineView collapseItem: item];
else
[mOutlineView expandItem: item];
return;
}
// get uri
nsCOMPtr<nsIRDFResource> propertyResource;
mRDFService->GetResource("http://home.netscape.com/NC-rdf#URL", getter_AddRefs(propertyResource));
nsCOMPtr<nsIRDFResource> resource = dont_AddRef([item resource]);
nsCOMPtr<nsIRDFNode> valueNode;
mDataSource->GetTarget(resource, propertyResource, PR_TRUE, getter_AddRefs(valueNode));
if (!valueNode) {
#if DEBUG
NSLog(@"ValueNode is null in openHistoryItem");
#endif
return;
}
nsCOMPtr<nsIRDFLiteral> valueLiteral(do_QueryInterface(valueNode));
if (!valueLiteral)
return;
nsXPIDLString literalValue;
valueLiteral->GetValue(getter_Copies(literalValue));
NSString* url = [NSString stringWith_nsAString: literalValue];
[[mBrowserWindowController getBrowserWrapper] loadURI: url referrer: nil flags: NSLoadFlagsNone activate:YES];
}
@end

View File

@ -1,58 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
* Portions are Copyright (C) 2002 nibfile.com
*
* Contributor(s):
* Matt Judy <matt@nibfile.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
@interface CHIconTabViewItem : NSTabViewItem
{
NSImage *mTabIcon;
NSDictionary *mLabelAttributes;
NSString *mLabelString;
NSMutableString *mTruncLabelString;
int mLabelStringWidth;
}
// The designated initializer
-(id)initWithIdentifier:(id)identifier withTabIcon:(NSImage *)tabIcon;
-(NSImage *)tabIcon;
-(void)setTabIcon:(NSImage *)newIcon;
@end

View File

@ -1,202 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
* Portions are Copyright (C) 2002 nibfile.com.
*
* Contributor(s):
* Matt Judy <matt@nibfile.com> (Original Author)
* David Haas <haasd@cae.wisc.edu>
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "CHIconTabViewItem.h"
#import "NSString+Utils.h"
//
// NSParagraphStyle has a line break mode which will automatically
// append ellipses to the end of a string. Unfortunately, as of
// OS X 10.1.5, the header says it doesn't work yet.
//
#define BROKEN_NSLineBreakByTruncatingMiddle
static const int kMinTabsForSpacing = 4; // with 1-4 tabs, each tab is 1/4 the tab view width
@interface CHIconTabViewItem(Private)
- (void)setupLabelAttributes;
@end;
@implementation CHIconTabViewItem
-(id)initWithIdentifier:(id)identifier withTabIcon:(NSImage *)tabIcon
{
if ( (self = [super initWithIdentifier:identifier]) ) {
[self setTabIcon:tabIcon];
[self setupLabelAttributes];
mLabelString = @"";
mLabelStringWidth = -1;
}
return self;
}
-(id)initWithIdentifier:(id)identifier
{
return [self initWithIdentifier:identifier withTabIcon:nil];
}
-(void)dealloc
{
[mTabIcon release];
[mLabelAttributes release];
[mTruncLabelString release];
[super dealloc];
}
- (void)setupLabelAttributes
{
NSMutableParagraphStyle *labelParagraphStyle = [[NSMutableParagraphStyle alloc] init];
[labelParagraphStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
#ifdef BROKEN_NSLineBreakByTruncatingMiddle
[labelParagraphStyle setLineBreakMode:NSLineBreakByClipping];
#else
[labelParagraphStyle setLineBreakMode:NSLineBreakByTruncatingMiddle];
#endif
[labelParagraphStyle setAlignment:NSNaturalTextAlignment];
NSFont *labelFont = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
mLabelAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:
labelFont, NSFontAttributeName,
labelParagraphStyle, NSParagraphStyleAttributeName,
nil];
[labelParagraphStyle release];
}
- (NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel
{
int numTabs;
float theWidth = 0;
//if we've got text, size for # of tabs & amount of text.
// Accounts for icon size, if one present.
if ([mLabelString length] > 0) {
numTabs = [[self tabView] numberOfTabViewItems];
if (numTabs < kMinTabsForSpacing)
numTabs = kMinTabsForSpacing;
theWidth = NSWidth([[self tabView] frame]) / numTabs - 16.0; // 16 works - don't know why. Maybe 8px on each side of the label?
if (shouldTruncateLabel) {
//I have really no clue what this is for.
//it only gets set YES when the tabs have
//reached the edge of the screen area.
//I don't see any difference in behavior between putting
//in -10 or -600 here. But -1 instead of -10 makes the
//tabs go off screen.
theWidth -= 16.0;
}
}
// If we don't have text, but DO have an icon, we'll have size 15.
else if ([self tabIcon])
theWidth = 15.0;
return NSMakeSize(theWidth, 15.0); // ugh, hard-coded height.
// This doesn't seem to affect, the height, only the rect pass to
// drawLabel.
}
-(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect
{
if ([self tabIcon]) {
NSPoint drawPoint = NSMakePoint( (tabRect.origin.x), (tabRect.origin.y + 15.0) );
[[self tabIcon] compositeToPoint:drawPoint operation:NSCompositeSourceOver];
tabRect = NSMakeRect(NSMinX(tabRect) + 18.0,
NSMinY(tabRect),
NSWidth(tabRect) - 18.0,
NSHeight(tabRect));
}
// Check if we have to rebuild the cached label string - either because the
// size changed, or the label changed, or because we never set the label before.
int width = NSWidth(tabRect);
if (mLabelStringWidth != width || !mTruncLabelString) {
[mTruncLabelString release];
mTruncLabelString = [[NSMutableString alloc] initWithString:mLabelString];
mLabelStringWidth = width;
#ifdef BROKEN_NSLineBreakByTruncatingMiddle
// Do our own truncating until Apple implements LineBreakByTruncatingTail/Middle.
// Then we can remove this code.
[mTruncLabelString truncateToWidth:width at:kTruncateAtEnd withAttributes:mLabelAttributes];
#endif
}
[mTruncLabelString drawInRect:tabRect withAttributes:mLabelAttributes];
}
-(NSImage *)tabIcon
{
return mTabIcon;
}
-(void)setTabIcon:(NSImage *)newIcon
{
[mTabIcon autorelease];
mTabIcon = [newIcon copy];
}
- (void)setLabel:(NSString *)label
{
// We use our complete own label storage, since for some reasons NSTabViewItem
// will start to slow us down a *lot* if the label becomes very long
// (even though we don't use the original drawing/size code at all).
if (![label isEqual:mLabelString]) {
[mLabelString release];
mLabelString = [label copy];
mLabelStringWidth = -1;
// we need to call setLabel on super to make some stuff happen, but the string
// doesn't matter.
[super setLabel:@"foo"];
}
}
- (NSString *)label
{
return mLabelString;
}
@end

View File

@ -1,7 +0,0 @@
#import <AppKit/NSImage.h>
@interface NSImage (CHImageAdditions)
- (void) drawFlippedInRect:(NSRect) rect operation:(NSCompositingOperation) op fraction:(float) delta;
- (void) drawFlippedInRect:(NSRect) rect operation:(NSCompositingOperation) op;
- (void)applyBadge:(NSImage*)badge withAlpha:(float)alpha scale:(float)scale;
@end

View File

@ -1,36 +0,0 @@
#import "CHImageAdditions.h"
#import <Cocoa/Cocoa.h>
@implementation NSImage (CHImageAdditions)
- (void) drawFlippedInRect:(NSRect) rect operation:(NSCompositingOperation) op fraction:(float) delta {
CGContextRef context;
context = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState( context ); {
CGContextTranslateCTM( context, 0, NSMaxY( rect ) );
CGContextScaleCTM( context, 1, -1 );
rect.origin.y = 0;
[self drawInRect:rect fromRect:NSZeroRect operation:op fraction:delta];
} CGContextRestoreGState( context );
}
- (void) drawFlippedInRect:(NSRect) rect operation:(NSCompositingOperation) op {
[self drawFlippedInRect:rect operation:op fraction:1.0];
}
- (void)applyBadge:(NSImage*)badge withAlpha:(float)alpha scale:(float)scale
{
if (!badge)
return;
[badge setScalesWhenResized:YES];
[badge setSize:NSMakeSize([self size].width * scale,[self size].height * scale)];
[self lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[badge dissolveToPoint:NSMakePoint([self size].width - [badge size].width,0) fraction:alpha];
[self unlockFocus];
}
@end

View File

@ -1,30 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*/
#import <AppKit/AppKit.h>
@interface CHLocationBar : NSView {
}
@end

View File

@ -1,55 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@apple.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "CHLocationBar.h"
@implementation CHLocationBar
- (void)drawRect:(NSRect)aRect {
// Frame the border.
//NSDrawLightBezel([self bounds], aRect);
[[NSColor colorWithCalibratedWhite: 0.98 alpha: 1.0] set];
NSRectFill(aRect);
[[NSColor colorWithCalibratedWhite: 0.90 alpha: 1.0] set];
NSFrameRectWithWidth([self bounds], 2.0);
}
@end

View File

@ -1,31 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import <Cocoa/Cocoa.h>
@interface CHPageProxyIcon : NSImageView
{
}
@end

View File

@ -1,93 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 2002 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Joe Hewitt <hewitt@netscape.com> (Original Author)
*/
#import "NSString+Utils.h"
#import "CHPageProxyIcon.h"
#import "BookmarksService.h"
#import "MainController.h"
#include "nsCRT.h"
#include "nsNetUtil.h"
#include "nsString.h"
@implementation CHPageProxyIcon
- (void)awakeFromNib
{
}
- (void)dealloc
{
[super dealloc];
}
- (void) resetCursorRects
{
NSCursor* cursor;
// XXX provide image for drag-hand cursor
cursor = [NSCursor arrowCursor];
[self addCursorRect:NSMakeRect(0,0,[self frame].size.width,[self frame].size.height) cursor:cursor];
[cursor setOnMouseEntered:YES];
}
- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)flag
{
return NSDragOperationGeneric;
}
- (void)mouseDown:(NSEvent *)theEvent
{
// need to implement this or else mouseDragged isn't called
}
- (void) mouseDragged: (NSEvent*) event
{
nsAutoString hrefStr, titleStr;
BookmarksService::GetTitleAndHrefForBrowserView(
[[[[self window] windowController] getBrowserWrapper] getBrowserView], titleStr, hrefStr);
NSString *url = [NSString stringWith_nsAString: hrefStr];
NSString *title = [NSString stringWith_nsAString: titleStr];
NSString *cleanedTitle = [title stringByReplacingCharactersInSet:[NSCharacterSet controlCharacterSet] withString:@" "];
NSArray *dataVals = [NSArray arrayWithObjects: url, cleanedTitle, nil];
NSArray *dataKeys = [NSArray arrayWithObjects: @"url", @"title", nil];
NSDictionary *data = [NSDictionary dictionaryWithObjects:dataVals forKeys:dataKeys];
NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObjects:@"MozURLType", NSURLPboardType, NSStringPboardType, nil] owner:self];
[pboard setPropertyList:data forType: @"MozURLType"];
[[NSURL URLWithString:url] writeToPasteboard: pboard];
[pboard setString:url forType: NSStringPboardType];
[self dragImage: [MainController createImageForDragging:[self image] title:title]
at: NSMakePoint(0,0) offset: NSMakeSize(0,0)
event: event pasteboard: pboard source: self slideBack: YES];
}
@end

View File

@ -1,66 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <AppKit/AppKit.h>
#import <Carbon/Carbon.h>
class nsIPref;
@interface CHPreferenceManager : NSObject
{
NSUserDefaults* mDefaults;
ICInstance mInternetConfig;
nsIPref* mPrefs;
}
+ (CHPreferenceManager *)sharedInstance;
- (id) init;
- (void) dealloc;
- (BOOL) initInternetConfig;
- (BOOL) initMozillaPrefs;
- (void) syncMozillaPrefs;
- (NSString *) getICStringPref:(ConstStr255Param) prefKey;
- (NSString *) homePage:(BOOL) checkStartupPagePref;
- (NSString*)getStringPref: (const char*)prefName withSuccess:(BOOL*)outSuccess;
- (NSColor*)getColorPref: (const char*)prefName withSuccess:(BOOL*)outSuccess;
- (BOOL)getBooleanPref: (const char*)prefName withSuccess:(BOOL*)outSuccess;
- (int)getIntPref: (const char*)prefName withSuccess:(BOOL*)outSuccess;
@end

View File

@ -1,481 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Cocoa/Cocoa.h>
#import <Cocoa/Cocoa.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "CHPreferenceManager.h"
#import "CHUserDefaults.h"
#include "nsIServiceManager.h"
#include "nsIProfile.h"
#include "nsIPref.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsString.h"
#include "nsEmbedAPI.h"
#include "AppDirServiceProvider.h"
#ifdef _BUILD_STATIC_BIN
#include "nsStaticComponent.h"
nsresult PR_CALLBACK
app_getModuleInfo(nsStaticModuleInfo **info, PRUint32 *count);
#endif
@implementation CHPreferenceManager
+ (CHPreferenceManager *) sharedInstance {
static CHPreferenceManager *sSharedInstance = nil;
return ( sSharedInstance ? sSharedInstance : (sSharedInstance = [[[CHPreferenceManager alloc] init] autorelease] ));
}
- (id) init
{
if ((self = [super init])) {
if ([self initInternetConfig] == NO) {
// XXXw. throw here
NSLog (@"Failed to initialize Internet Config");
}
if ([self initMozillaPrefs] == NO) {
// XXXw. throw here too
NSLog (@"Failed to initialize mozilla prefs");
}
mDefaults = [NSUserDefaults standardUserDefaults];
}
return self;
}
- (void) dealloc
{
::ICStop(mInternetConfig);
NS_IF_RELEASE(mPrefs);
nsresult rv;
nsCOMPtr<nsIPrefService> pref(do_GetService(NS_PREF_CONTRACTID, &rv));
if (NS_SUCCEEDED(rv)) {
//NSLog(@"Saving prefs file");
pref->SavePrefFile(nsnull);
}
[super dealloc];
}
- (BOOL) initInternetConfig
{
OSStatus error;
error = ::ICStart(&mInternetConfig, 'CHIM');
if (error != noErr) {
// XXX throw here?
NSLog(@"Error initializing IC");
return NO;
}
return YES;
}
- (BOOL) initMozillaPrefs
{
#ifdef _BUILD_STATIC_BIN
// Initialize XPCOM's module info table
NSGetStaticModuleInfo = app_getModuleInfo;
#endif
nsresult rv;
NSString *path = [[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent];
const char *binDirPath = [path fileSystemRepresentation];
nsCOMPtr<nsILocalFile> binDir;
rv = NS_NewNativeLocalFile(nsDependentCString(binDirPath), PR_TRUE, getter_AddRefs(binDir));
if (NS_FAILED(rv))
return NO;
// This shouldn't be needed since we are initing XPCOM with this
// directory but causes a (harmless) warning if not defined.
setenv("MOZILLA_FIVE_HOME", binDirPath, 1);
// get the 'mozProfileDirName' key from our Info.plist file
NSString *dirString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"mozProfileDirName"];
const char* profileDirName;
if (dirString)
profileDirName = [dirString cString];
else {
NSLog(@"mozProfileDirName key missing from Info.plist file. Using default profile directory");
profileDirName = "Chimera";
}
// Supply our own directory service provider so we can control where
// the registry and profiles are located.
AppDirServiceProvider *provider = new AppDirServiceProvider(nsDependentCString(profileDirName));
NS_ASSERTION(provider, "Failed to create AppDirServiceProvider");
rv = NS_InitEmbedding(binDir, provider);
if (NS_FAILED(rv)) {
NSLog(@"Embedding init failed.");
return NO;
}
nsCOMPtr<nsIProfile> profileService(do_GetService(NS_PROFILE_CONTRACTID, &rv));
if (NS_FAILED(rv))
return NO;
nsAutoString newProfileName(NS_LITERAL_STRING("default"));
PRBool profileExists = PR_FALSE;
rv = profileService->ProfileExists(newProfileName.get(), &profileExists);
if (NS_FAILED(rv))
return NO;
if (!profileExists) {
rv = profileService->CreateNewProfile(newProfileName.get(), nsnull, nsnull, PR_FALSE);
if (NS_FAILED(rv))
return NO;
}
rv = profileService->SetCurrentProfile(newProfileName.get());
if (NS_FAILED(rv)) {
if (rv == NS_ERROR_FILE_ACCESS_DENIED) {
NSString *alert = [NSString stringWithFormat: NSLocalizedString(@"AlreadyRunningAlert", @""), NSLocalizedStringFromTable(@"CFBundleName", @"InfoPlist", nil)];
NSString *message = [NSString stringWithFormat: NSLocalizedString(@"AlreadyRunningMsg", @""), NSLocalizedStringFromTable(@"CFBundleName", @"InfoPlist", nil)];
NSString *quit = NSLocalizedString(@"AlreadyRunningButton",@"");
NSRunAlertPanel(alert,message,quit,nil,nil);
[NSApp terminate:self];
}
return NO;
}
nsCOMPtr<nsIPref> prefs(do_GetService(NS_PREF_CONTRACTID));
mPrefs = prefs;
NS_IF_ADDREF(mPrefs);
[self syncMozillaPrefs];
return YES;
}
- (void) syncMozillaPrefs
{
CFArrayRef cfArray;
CFDictionaryRef cfDictionary;
CFNumberRef cfNumber;
CFStringRef cfString;
char strbuf[1024];
int numbuf;
if (!mPrefs) {
NSLog(@"Mozilla prefs not set up successfully");
return;
}
// fix up the cookie prefs. If 'p3p' or 'accept foreign cookies' are on, remap them to
// something that chimera can deal with.
PRInt32 acceptCookies = 0;
static const char* kCookieBehaviorPref = "network.cookie.cookieBehavior";
mPrefs->GetIntPref(kCookieBehaviorPref, &acceptCookies);
if ( acceptCookies == 1 ) { // accept foreign cookies, assume off
acceptCookies = 2;
mPrefs->SetIntPref(kCookieBehaviorPref, acceptCookies);
}
else if ( acceptCookies == 3 ) { // p3p, assume all cookies on
acceptCookies = 0;
mPrefs->SetIntPref(kCookieBehaviorPref, acceptCookies);
}
// get proxies from SystemConfiguration
mPrefs->SetIntPref("network.proxy.type", 0); // 0 == no proxies
mPrefs->ClearUserPref("network.proxy.http");
mPrefs->ClearUserPref("network.proxy.http_port");
mPrefs->ClearUserPref("network.proxy.ssl");
mPrefs->ClearUserPref("network.proxy.ssl_port");
mPrefs->ClearUserPref("network.proxy.ftp");
mPrefs->ClearUserPref("network.proxy.ftp_port");
mPrefs->ClearUserPref("network.proxy.gopher");
mPrefs->ClearUserPref("network.proxy.gopher_port");
mPrefs->ClearUserPref("network.proxy.socks");
mPrefs->ClearUserPref("network.proxy.socks_port");
mPrefs->ClearUserPref("network.proxy.no_proxies_on");
if ((cfDictionary = SCDynamicStoreCopyProxies (NULL)) != NULL) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPEnable, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE && numbuf == 1) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPProxy, (const void **)&cfString) == TRUE) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.http", strbuf);
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPPort, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE) {
mPrefs->SetIntPref("network.proxy.http_port", numbuf);
}
mPrefs->SetIntPref("network.proxy.type", 1);
}
}
}
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPSEnable, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE && numbuf == 1) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPSProxy, (const void **)&cfString) == TRUE) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.ssl", strbuf);
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesHTTPSPort, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE) {
mPrefs->SetIntPref("network.proxy.ssl_port", numbuf);
}
mPrefs->SetIntPref("network.proxy.type", 1);
}
}
}
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesFTPEnable, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE && numbuf == 1) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesFTPProxy, (const void **)&cfString) == TRUE) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.ftp", strbuf);
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesFTPPort, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE) {
mPrefs->SetIntPref("network.proxy.ftp_port", numbuf);
}
mPrefs->SetIntPref("network.proxy.type", 1);
}
}
}
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesGopherEnable, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE && numbuf == 1) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesGopherProxy, (const void **)&cfString) == TRUE) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.gopher", strbuf);
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesGopherPort, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE) {
mPrefs->SetIntPref("network.proxy.gopher_port", numbuf);
}
mPrefs->SetIntPref("network.proxy.type", 1);
}
}
}
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesSOCKSEnable, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE && numbuf == 1) {
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesSOCKSProxy, (const void **)&cfString) == TRUE) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.socks", strbuf);
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesSOCKSPort, (const void **)&cfNumber) == TRUE) {
if (CFNumberGetValue (cfNumber, kCFNumberIntType, &numbuf) == TRUE) {
mPrefs->SetIntPref("network.proxy.socks_port", numbuf);
}
mPrefs->SetIntPref("network.proxy.type", 1);
}
}
}
}
if (CFDictionaryGetValueIfPresent (cfDictionary, kSCPropNetProxiesExceptionsList, (const void **)&cfArray) == TRUE) {
cfString = CFStringCreateByCombiningStrings (NULL, cfArray, CFSTR(", "));
if (CFStringGetLength (cfString) > 0) {
if (CFStringGetCString (cfString, strbuf, sizeof(strbuf)-1, kCFStringEncodingASCII) == TRUE) {
mPrefs->SetCharPref("network.proxy.no_proxies_on", strbuf);
}
}
}
CFRelease (cfDictionary);
}
}
- (NSString*)getStringPref: (const char*)prefName withSuccess:(BOOL*)outSuccess
{
NSString *prefValue = @"";
char *buf = nsnull;
nsresult rv = NS_ERROR_FAILURE;
if (mPrefs)
rv = mPrefs->GetCharPref(prefName, &buf);
if (NS_SUCCEEDED(rv) && buf) {
// prefs are UTF-8
prefValue = [NSString stringWithUTF8String:buf];
free(buf);
if (outSuccess) *outSuccess = YES;
} else {
if (outSuccess) *outSuccess = NO;
}
return prefValue;
}
- (NSColor*)getColorPref: (const char*)prefName withSuccess:(BOOL*)outSuccess
{
// colors are stored in HTML-like #FFFFFF strings
NSString* colorString = [self getStringPref:prefName withSuccess:outSuccess];
NSColor* returnColor = [NSColor blackColor];
if ([colorString hasPrefix:@"#"] && [colorString length] == 7)
{
unsigned int redInt, greenInt, blueInt;
sscanf([colorString cString], "#%02x%02x%02x", &redInt, &greenInt, &blueInt);
float redFloat = ((float)redInt / 255.0);
float greenFloat = ((float)greenInt / 255.0);
float blueFloat = ((float)blueInt / 255.0);
returnColor = [NSColor colorWithCalibratedRed:redFloat green:greenFloat blue:blueFloat alpha:1.0f];
}
return returnColor;
}
- (BOOL)getBooleanPref: (const char*)prefName withSuccess:(BOOL*)outSuccess
{
PRBool boolPref = PR_FALSE;
nsresult rv = NS_ERROR_FAILURE;
if (mPrefs)
rv = mPrefs->GetBoolPref(prefName, &boolPref);
if (outSuccess)
*outSuccess = NS_SUCCEEDED(rv);
return boolPref ? YES : NO;
}
- (int)getIntPref: (const char*)prefName withSuccess:(BOOL*)outSuccess
{
PRInt32 intPref = 0;
nsresult rv = NS_ERROR_FAILURE;
if (mPrefs)
mPrefs->GetIntPref(prefName, &intPref);
if (outSuccess)
*outSuccess = NS_SUCCEEDED(rv);
return intPref;
}
//- (BOOL) getICBoolPref:(ConstStr255Param) prefKey;
//{
// ICAttr dummy;
// OSStatus error;
// SInt32 size;
// Boolean buf;
// error = ICGetPref (internetConfig, prefKey, &dummy, &buf, &size);
// if (error == noErr && buf)
// return YES;
// else
// return NO;
// }
- (NSString *) getICStringPref:(ConstStr255Param) prefKey;
{
NSString *string;
ICAttr dummy;
OSStatus error;
SInt32 size = 256;
char *buf;
do {
if ((buf = malloc ((unsigned int)size)) == NULL) {
NSLog (@"malloc failed in [PreferenceManager getICStringPref]");
return nil;
}
error = ICGetPref (mInternetConfig, prefKey, &dummy, buf, &size);
if (error != noErr && error != icTruncatedErr) {
free (buf);
NSLog (@"[IC error %d in [PreferenceManager getICStringPref]", (int) error);
return nil;
}
size *= 2;
} while (error == icTruncatedErr);
if (*buf == 0) {
NSLog (@"ICGetPref returned empty string");
free (buf);
return nil;
}
CopyPascalStringToC ((ConstStr255Param) buf, buf);
string = [NSString stringWithCString:buf];
free (buf);
return string;
}
- (NSString *) homePage:(BOOL)checkStartupPagePref
{
if (!mPrefs)
return @"about:blank";
PRInt32 mode = 1;
// In some cases, we need to check browser.startup.page to see if
// we want to use the homepage or if the user wants a blank window.
// mode 0 is blank page, mode 1 is home page. 2 is "last page visited"
// but we don't care about that. Default to 1 unless |checkStartupPagePref|
// is true.
nsresult rv = NS_OK;
if ( checkStartupPagePref )
rv = mPrefs->GetIntPref("browser.startup.page", &mode);
if (NS_FAILED(rv) || mode == 1) {
// see which home page to use
PRBool boolPref;
if (NS_SUCCEEDED(mPrefs->GetBoolPref("chimera.use_system_home_page", &boolPref)) && boolPref)
return [self getICStringPref:kICWWWHomePage];
nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(mPrefs);
if (!prefBranch) return @"about:blank";
NSString* homepagePref = nil;
PRInt32 haveUserPref;
if (NS_FAILED(prefBranch->PrefHasUserValue("browser.startup.homepage", &haveUserPref)) || !haveUserPref) {
// no home page pref is set in user prefs.
homepagePref = NSLocalizedStringFromTable( @"HomePageDefault", @"WebsiteDefaults", nil);
// and let's copy this into the homepage pref if it's not bad
if (![homepagePref isEqualToString:@"HomePageDefault"])
mPrefs->SetCharPref("browser.startup.homepage", [homepagePref UTF8String]);
}
else {
homepagePref = [self getStringPref:"browser.startup.homepage" withSuccess:NULL];
}
if (homepagePref && [homepagePref length] > 0 && ![homepagePref isEqualToString:@"HomePageDefault"])
return homepagePref;
}
return @"about:blank";
}
@end

View File

@ -1,93 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ben Goodger <ben@netscape.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import <Foundation/Foundation.h>
#import <Appkit/Appkit.h>
class nsIRDFDataSource;
class nsIRDFContainer;
class nsIRDFContainerUtils;
class nsIRDFResource;
class nsIRDFService;
@interface CHRDFOutlineViewDataSource : NSObject {
nsIRDFDataSource* mDataSource;
nsIRDFContainer* mContainer;
nsIRDFContainerUtils* mContainerUtils;
nsIRDFResource* mRootResource;
nsIRDFService* mRDFService;
IBOutlet id mOutlineView;
NSMutableDictionary* mDictionary;
}
// Initialization Methods
- (void) ensureDataSourceLoaded;
- (nsIRDFDataSource*) dataSource;
- (nsIRDFResource*) rootResource;
- (void) setDataSource: (nsIRDFDataSource*) aDataSource;
- (void) setRootResource: (nsIRDFResource*) aResource;
// Outline View Data Source methods
- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item;
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item;
- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item;
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
- (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item;
- (void)reloadDataForItem:(id)item reloadChildren: (BOOL)aReloadChildren;
// Implementation Methods
- (id) MakeWrapperFor: (nsIRDFResource*) aRDFResource;
@end
// RDF Resource Wrapper to make the Outline View happy
@interface RDFOutlineViewItem : NSObject
{
nsIRDFResource* mResource;
}
- (nsIRDFResource*) resource;
- (void) setResource: (nsIRDFResource*) aResource;
@end

View File

@ -1,325 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ben Goodger <ben@netscape.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "CHRDFOutlineViewDataSource.h"
#include "nsIRDFDataSource.h"
#include "nsIRDFService.h"
#include "nsIRDFLiteral.h"
#include "nsIRDFResource.h"
#include "nsIRDFContainer.h"
#include "nsIRDFContainerUtils.h"
#include "nsRDFCID.h"
#include "nsComponentManagerUtils.h"
#include "nsIServiceManagerUtils.h"
#include "nsXPIDLString.h"
#include "nsString.h"
@implementation CHRDFOutlineViewDataSource
- (void) ensureDataSourceLoaded
{
if (!mContainer)
{
nsCOMPtr<nsIRDFContainer> ctr = do_CreateInstance("@mozilla.org/rdf/container;1");
NS_ADDREF(mContainer = ctr);
nsCOMPtr<nsIRDFContainerUtils> ctrUtils = do_GetService("@mozilla.org/rdf/container-utils;1");
NS_ADDREF(mContainerUtils = ctrUtils);
nsCOMPtr<nsIRDFService> rdfService = do_GetService("@mozilla.org/rdf/rdf-service;1");
NS_ADDREF(mRDFService = rdfService);
mDictionary = [[NSMutableDictionary alloc] initWithCapacity: 30];
mDataSource = nsnull;
mRootResource = nsnull;
}
}
- (void) dealloc
{
NS_IF_RELEASE(mContainer);
NS_IF_RELEASE(mContainerUtils);
NS_IF_RELEASE(mRDFService);
NS_IF_RELEASE(mDataSource);
NS_IF_RELEASE(mRootResource);
[mDictionary release];
[super dealloc];
}
- (nsIRDFDataSource*) dataSource
{
NS_IF_ADDREF(mDataSource);
return mDataSource;
}
- (nsIRDFResource*) rootResource
{
NS_IF_ADDREF(mRootResource);
return mRootResource;
}
- (void) setDataSource: (nsIRDFDataSource*) aDataSource
{
nsIRDFDataSource* oldDataSource = mDataSource;
NS_IF_ADDREF(mDataSource = aDataSource);
NS_IF_RELEASE(oldDataSource);
}
- (void) setRootResource: (nsIRDFResource*) aResource
{
nsIRDFResource* oldResource = mRootResource;
NS_IF_ADDREF(mRootResource = aResource);
NS_IF_RELEASE(oldResource);
}
//
// XXX - For now, we'll just say that none of our items are editable, as we aren't using any
// RDF datasources that are mutable.
//
- (BOOL) outlineView: (NSOutlineView*) aOutlineView shouldEditTableColumn: (NSTableColumn*) aTableColumn
item: (id) aItem
{
return NO;
}
- (BOOL) outlineView: (NSOutlineView*) aOutlineView isItemExpandable: (id) aItem
{
if (!mDataSource)
return NO;
if (!aItem)
return YES; // The root is always open
nsCOMPtr<nsIRDFResource> itemResource = dont_AddRef([aItem resource]);
PRBool isSeq = PR_FALSE;
mContainerUtils->IsSeq(mDataSource, itemResource, &isSeq);
if (isSeq)
return YES;
nsCOMPtr<nsIRDFResource> childProperty;
mRDFService->GetResource("http://home.netscape.com/NC-rdf#child", getter_AddRefs(childProperty));
nsCOMPtr<nsIRDFNode> childNode;
mDataSource->GetTarget(itemResource, childProperty, PR_TRUE, getter_AddRefs(childNode));
return childNode != nsnull;
}
- (id) outlineView: (NSOutlineView*) aOutlineView child: (int) aIndex
ofItem: (id) aItem
{
if (!mDataSource)
return nil;
nsCOMPtr<nsIRDFResource> resource = !aItem ? dont_AddRef([self rootResource]) : dont_AddRef([aItem resource]);
nsCOMPtr<nsIRDFResource> ordinalResource;
mContainerUtils->IndexToOrdinalResource(aIndex + 1, getter_AddRefs(ordinalResource));
nsCOMPtr<nsIRDFNode> childNode;
mDataSource->GetTarget(resource, ordinalResource, PR_TRUE, getter_AddRefs(childNode));
if (childNode) {
// Yay. A regular container. We don't need to count, we can go directly to
// our object.
nsCOMPtr<nsIRDFResource> childResource(do_QueryInterface(childNode));
if (childResource)
return [self MakeWrapperFor:childResource];
}
else
{
// Oh well, not a regular container. We need to count, dagnabbit.
nsCOMPtr<nsIRDFResource> childProperty;
mRDFService->GetResource("http://home.netscape.com/NC-rdf#child", getter_AddRefs(childProperty));
nsCOMPtr<nsISimpleEnumerator> childNodes;
mDataSource->GetTargets(resource, childProperty, PR_TRUE, getter_AddRefs(childNodes));
nsCOMPtr<nsISupports> supp;
PRInt32 count = 0;
PRBool hasMore = PR_FALSE;
while (NS_SUCCEEDED(childNodes->HasMoreElements(&hasMore)) && hasMore)
{
childNodes->GetNext(getter_AddRefs(supp));
if (count == aIndex)
break;
count ++;
}
nsCOMPtr<nsIRDFResource> childResource(do_QueryInterface(supp));
if (childResource) {
return [self MakeWrapperFor:childResource];
}
}
return nil;
}
- (int) outlineView: (NSOutlineView*) aOutlineView numberOfChildrenOfItem: (id) aItem;
{
if (!mDataSource)
return 0;
nsCOMPtr<nsIRDFResource> resource = dont_AddRef(aItem ? [aItem resource] : [self rootResource]);
// XXX just assume NC:child is the only containment arc for now
nsCOMPtr<nsIRDFResource> childProperty;
mRDFService->GetResource("http://home.netscape.com/NC-rdf#child", getter_AddRefs(childProperty));
nsCOMPtr<nsISimpleEnumerator> childNodes;
mDataSource->GetTargets(resource, childProperty, PR_TRUE, getter_AddRefs(childNodes));
PRBool hasMore = PR_FALSE;
PRInt32 count = 0;
while (NS_SUCCEEDED(childNodes->HasMoreElements(&hasMore)) && hasMore)
{
nsCOMPtr<nsISupports> supp;
childNodes->GetNext(getter_AddRefs(supp));
count ++;
}
if (count == 0) {
nsresult rv = mContainer->Init(mDataSource, resource);
if (NS_FAILED(rv))
return 0;
mContainer->GetCount(&count);
}
return count;
}
- (id) outlineView: (NSOutlineView*) aOutlineView objectValueForTableColumn: (NSTableColumn*) aTableColumn
byItem: (id) aItem
{
if (!mDataSource || !aItem)
return nil;
// The table column's identifier is the RDF Resource URI of the property being displayed in
// that column, e.g. "http://home.netscape.com/NC-rdf#Name"
NSString* columnPropertyURI = [aTableColumn identifier];
nsCOMPtr<nsIRDFResource> propertyResource;
mRDFService->GetResource([columnPropertyURI UTF8String], getter_AddRefs(propertyResource));
nsCOMPtr<nsIRDFResource> resource = dont_AddRef([aItem resource]);
nsCOMPtr<nsIRDFNode> valueNode;
mDataSource->GetTarget(resource, propertyResource, PR_TRUE, getter_AddRefs(valueNode));
if (!valueNode) {
#if DEBUG
NSLog(@"ValueNode is null in RDF objectValueForTableColumn");
#endif
return nil;
}
nsCOMPtr<nsIRDFLiteral> valueLiteral(do_QueryInterface(valueNode));
if (!valueLiteral)
return nil;
nsXPIDLString literalValue;
valueLiteral->GetValue(getter_Copies(literalValue));
return [NSString stringWith_nsAString: literalValue];
}
- (void) outlineView: (NSOutlineView*) aOutlineView setObjectValue: (id) aObject
forTableColumn: (NSTableColumn*) aTableColumn
byItem: (id) aItem
{
}
- (void) reloadDataForItem: (id) aItem reloadChildren: (BOOL) aReloadChildren
{
if (!aItem)
[mOutlineView reloadData];
else
[mOutlineView reloadItem: aItem reloadChildren: aReloadChildren];
}
- (id) MakeWrapperFor: (nsIRDFResource*) aRDFResource
{
RDFOutlineViewItem* item = [[[RDFOutlineViewItem alloc] init] autorelease];
[item setResource: aRDFResource];
// keep a copy around
const char* resourceValue;
aRDFResource->GetValueConst(&resourceValue);
[mDictionary setObject:item forKey:[NSString stringWithCString:resourceValue]];
return item;
}
@end
@implementation RDFOutlineViewItem
- (void) dealloc
{
NS_IF_RELEASE(mResource);
[super dealloc];
}
- (nsIRDFResource*) resource
{
NS_IF_ADDREF(mResource);
return mResource;
}
- (void) setResource: (nsIRDFResource*) aResource
{
nsIRDFResource* oldResource = mResource;
NS_IF_ADDREF(mResource = aResource);
NS_IF_RELEASE(oldResource);
}
@end

View File

@ -1,45 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Matt Judy.
*/
#import <Cocoa/Cocoa.h>
@interface CHSplashScreenWindow : NSWindow {
BOOL _fades;
BOOL __didFadeIn;
int _fadeIndex;
NSTimeInterval _fadeDelay;
id _fadeThreadLock;
NSTextField *_statusField;
}
// This method inits the window and displays it, slightly proud of center,
// and at the size of the image it displays.
//
// The splash method should be used in your main controller's init method
// in this fashion: splashWindow = [[SplashScreenWindow alloc] splashImage:nil withFade:NO withStatusRect:someRect];
//
// Passing nil to splashImage will attempt to load [NSImage imageNamed:@"splash"] instead.
// If that fails, the app icon will be displayed.
//
// The window will release itself whenever you send it the close message.
-(id)splashImage:(NSImage *)splashImage withFade:(BOOL)shouldFade withStatusRect:(NSRect)statusRect;
-(NSString *)statusText;
-(void)setStatusText:(NSString *)newText;
@end

View File

@ -1,186 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Mozilla browser.
*
* The Initial Developer of the Original Code is Matt Judy.
*
*/
#import "CHSplashScreenWindow.h"
@interface CHSplashScreenWindow (Private)
-(void)fadeIn;
-(void)fadeInThread;
-(void)fadeOut;
-(void)fadeOutThread;
@end
@implementation CHSplashScreenWindow
-(id)splashImage:(NSImage *)splashImage withFade:(BOOL)shouldFade withStatusRect:(NSRect)statusRect
{
NSRect splashRect;
NSRect statusFieldRect;
NSImageView *contentImageView;
_fadeDelay = (0.5 / 60.0);
if ( ! splashImage ) {
if ( [NSImage imageNamed:@"splash"] ) {
splashImage = [NSImage imageNamed:@"splash"];
} else {
splashImage = [NSImage imageNamed:@"NSApplicationIcon"];
}
}
splashRect = NSMakeRect(0.0, 0.0, [splashImage size].width, [splashImage size].height);
contentImageView = [[[NSImageView alloc] initWithFrame:splashRect] autorelease];
#if USE_STATUS_FIELD
statusFieldRect = NSMakeRect(0.0, 170.0, (splashRect.size.width - 5.0), 16.0);
_statusField = [[[NSTextField alloc] initWithFrame:statusFieldRect];
#endif
if ( (self = [super initWithContentRect:splashRect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO]) ) {
[contentImageView setImage:splashImage];
_fadeThreadLock = nil;
#if USE_STATUS_FIELD
[_statusField setDrawsBackground:NO];
[_statusField setEditable:NO];
[_statusField setSelectable:NO];
[_statusField setBezeled:NO];
[_statusField setBordered:NO];
[_statusField setFont:[NSFont fontWithName:@"Monaco" size:10.0]];
[_statusField setTextColor:[NSColor whiteColor]];
[_statusField setAlignment:NSRightTextAlignment];
[_statusField setStringValue:@"Loading..."];
#endif
[[self contentView] addSubview:contentImageView];
#if USE_STATUS_FIELD
[[self contentView] addSubview:_statusField];
#endif
[self setOpaque:NO];
[self setHasShadow:YES];
[self setReleasedWhenClosed:YES];
[self center];
if ( shouldFade ) {
[self fadeIn];
} else {
[self makeKeyAndOrderFront:self];
}
__didFadeIn = shouldFade;
}
return self;
}
-(NSString *)statusText
{
return [_statusField stringValue];
}
-(void)setStatusText:(NSString *)newText
{
#if USE_STATUS_FIELD
[_statusField setStringValue:newText];
[_statusField display];
#endif
}
-(void)fadeIn
{
[self setAlphaValue:0.0];
[self makeKeyAndOrderFront:self];
if (_fadeThreadLock == nil) {
_fadeThreadLock = [[NSLock allocWithZone:[self zone]] init];
}
[NSThread detachNewThreadSelector:@selector(fadeInThread) toTarget:self withObject:nil];
}
-(void)fadeInThread
{
float fadeLevel = 0.0;
NSAutoreleasePool *threadMainPool = [[NSAutoreleasePool alloc] init];
[_fadeThreadLock lock];
while ( fadeLevel < 1.0 ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
fadeLevel += 0.20;
[self setAlphaValue:fadeLevel];
[self flushWindow];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:_fadeDelay]];
[pool release];
}
[_fadeThreadLock unlock];
[threadMainPool release];
}
-(void)fadeOut
{
if (_fadeThreadLock == nil) {
_fadeThreadLock = [[NSLock allocWithZone:[self zone]] init];
}
[NSThread detachNewThreadSelector:@selector(fadeOutThread) toTarget:self withObject:nil];
}
-(void)fadeOutThread
{
float fadeLevel = 1.0;
NSAutoreleasePool *threadMainPool = [[NSAutoreleasePool alloc] init];
[_fadeThreadLock lock];
while ( fadeLevel > 0.0 ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
fadeLevel -= 0.1;
[self setAlphaValue:fadeLevel];
[self flushWindow];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:_fadeDelay]];
[pool release];
}
[_fadeThreadLock unlock];
[threadMainPool release];
}
-(void)close
{
#if USE_STATUS_FIELD
[_statusField release];
#endif
// if ( __didFadeIn ) {
if ( NO ) { //Fade out is still problematic...
[self fadeOut];
}
[super close];
}
-(void)dealloc
{
[_fadeThreadLock release];
[super dealloc];
}
@end

View File

@ -1,12 +0,0 @@
#import <AppKit/NSToolbar.h>
@interface NSToolbar (CHToolbarCustomizableAdditions)
- (BOOL) alwaysCustomizableByDrag;
- (void) setAlwaysCustomizableByDrag:(BOOL) flag;
- (BOOL) showsContextMenu;
- (void) setShowsContextMenu:(BOOL) flag;
- (unsigned int) indexOfFirstMovableItem;
- (void) setIndexOfFirstMovableItem:(unsigned int) anIndex;
@end

View File

@ -1,28 +0,0 @@
#import "CHToolbarAdditions.h"
#import <Foundation/Foundation.h>
@implementation NSToolbar (CHToolbarCustomizableAdditions)
- (BOOL) alwaysCustomizableByDrag {
return (BOOL) _tbFlags.clickAndDragPerformsCustomization;
}
- (void) setAlwaysCustomizableByDrag:(BOOL) flag {
_tbFlags.clickAndDragPerformsCustomization = (unsigned int) flag & 1;
}
- (BOOL) showsContextMenu {
return (BOOL) ! _tbFlags.showsNoContextMenu;
}
- (void) setShowsContextMenu:(BOOL) flag {
_tbFlags.showsNoContextMenu = (unsigned int) ! flag & 1;
}
- (unsigned int) indexOfFirstMovableItem {
return (unsigned int) _tbFlags.firstMoveableItemIndex;
}
- (void) setIndexOfFirstMovableItem:(unsigned int) anIndex {
_tbFlags.firstMoveableItemIndex = (unsigned int) anIndex & 0x3F;
}
@end

View File

@ -1,55 +0,0 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001, 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
This file contains a list of #defines for our user default entries. They
are collected here, rather than being scattered throughout the code, for
easier documentation.
*/
#define USER_DEFAULTS_AUTOREGISTER_KEY @"autoRegister" /* Boolean */
#define USER_DEFAULTS_URL_KEY @"url" /* String */
#define USER_DEFAULTS_HIDE_PERS_TOOLBAR_KEY @"Hide Personal Toolbar" /* Integer */
#define USER_DEFAULTS_HOMEPAGE_KEY @"HomePage" /* String */
#define USER_DEFAULTS_AUTOCOMPLETE_WHILE_TYPING @"Autocomplete While Typing" /* Boolean */

View File

@ -1,64 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __CocoaPromptService_h__
#define __CocoaPromptService_h__
#include "nsIStringBundle.h"
#include "nsIPromptService.h"
#import <Cocoa/Cocoa.h>
class CocoaPromptService : public nsIPromptService
{
public:
CocoaPromptService();
virtual ~CocoaPromptService();
NS_DECL_ISUPPORTS;
NS_DECL_NSIPROMPTSERVICE;
private:
NSWindow *GetNSWindowForDOMWindow(nsIDOMWindow* window);
NSString *GetCommonDialogLocaleString(const char *s);
NSString *GetButtonStringFromFlags(PRUint32 btnFlags, PRUint32 btnIDAndShift,
const PRUnichar *btnTitle);
nsCOMPtr<nsIStringBundle> mCommonDialogStringBundle;
};
#endif

View File

@ -1,453 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brian Ryner <bryner@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#import "nsCocoaBrowserService.h"
#import "CocoaPromptService.h"
#include "nsCRT.h"
#include "nsIWindowWatcher.h"
#include "nsIWebBrowserChrome.h"
#include "nsIEmbeddingSiteWindow.h"
#include "nsString.h"
#include "nsIServiceManagerUtils.h"
CocoaPromptService::CocoaPromptService()
{
NS_INIT_ISUPPORTS();
}
CocoaPromptService::~CocoaPromptService()
{
}
NS_IMPL_ISUPPORTS1(CocoaPromptService, nsIPromptService);
/* void alert (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text); */
NS_IMETHODIMP
CocoaPromptService::Alert(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSWindow* window = GetNSWindowForDOMWindow(parent);
if (!window)
return NS_ERROR_FAILURE;
[controller alert:window title:titleStr text:textStr];
return NS_OK;
}
/* void alertCheck (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, in wstring checkMsg, inout boolean checkValue); */
NS_IMETHODIMP
CocoaPromptService::AlertCheck(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
const PRUnichar *checkMsg,
PRBool *checkValue)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSWindow* window = GetNSWindowForDOMWindow(parent);
if (checkValue) {
BOOL valueBool = *checkValue ? YES : NO;
[controller alertCheck:window title:titleStr text:textStr checkMsg:msgStr checkValue:&valueBool];
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
else {
[controller alert:window title:titleStr text:textStr];
}
return NS_OK;
}
/* boolean confirm (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text); */
NS_IMETHODIMP
CocoaPromptService::Confirm(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRBool *_retval)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSWindow* window = GetNSWindowForDOMWindow(parent);
*_retval = (PRBool)[controller confirm:window title:titleStr text:textStr];
return NS_OK;
}
/* boolean confirmCheck (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, in wstring checkMsg, inout boolean checkValue); */
NS_IMETHODIMP
CocoaPromptService::ConfirmCheck(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
const PRUnichar *checkMsg,
PRBool *checkValue, PRBool *_retval)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSWindow* window = GetNSWindowForDOMWindow(parent);
if (checkValue) {
BOOL valueBool = *checkValue ? YES : NO;
*_retval = (PRBool)[controller confirmCheck:window title:titleStr text:textStr checkMsg:msgStr checkValue:&valueBool];
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
else {
*_retval = (PRBool)[controller confirm:window title:titleStr text:textStr];
}
return NS_OK;
}
// these constants are used for identifying the buttons and are intentionally overloaded to
// correspond to the number of bits needed for shifting to obtain the flags for a particular
// button (should be defined in nsIPrompt*.idl instead of here)
const PRUint32 kButton0 = 0;
const PRUint32 kButton1 = 8;
const PRUint32 kButton2 = 16;
/* void confirmEx (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, in unsigned long buttonFlags, in wstring button0Title, in wstring button1Title, in wstring button2Title, in wstring checkMsg, inout boolean checkValue, out PRInt32 buttonPressed); */
NS_IMETHODIMP
CocoaPromptService::ConfirmEx(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRUint32 buttonFlags,
const PRUnichar *button0Title,
const PRUnichar *button1Title,
const PRUnichar *button2Title,
const PRUnichar *checkMsg,
PRBool *checkValue, PRInt32 *buttonPressed)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSWindow* window = GetNSWindowForDOMWindow(parent);
NSString* btn1Str = GetButtonStringFromFlags(buttonFlags, kButton0, button0Title);
NSString* btn2Str = GetButtonStringFromFlags(buttonFlags, kButton1, button1Title);
NSString* btn3Str = GetButtonStringFromFlags(buttonFlags, kButton2, button2Title);
if (checkValue) {
BOOL valueBool = *checkValue ? YES : NO;
*buttonPressed = [controller confirmCheckEx:window title:titleStr text:textStr
button1: btn1Str button2: btn2Str button3: btn3Str
checkMsg:msgStr checkValue:&valueBool];
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
else {
*buttonPressed = [controller confirmEx:window title:titleStr text:textStr
button1: btn1Str button2: btn2Str button3: btn3Str];
}
return NS_OK;
}
/* boolean prompt (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, inout wstring value, in wstring checkMsg, inout boolean checkValue); */
NS_IMETHODIMP
CocoaPromptService::Prompt(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRUnichar **value,
const PRUnichar *checkMsg,
PRBool *checkValue,
PRBool *_retval)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSMutableString* valueStr = [NSMutableString stringWithPRUnichars:*value];
BOOL valueBool;
if (checkValue) {
valueBool = *checkValue ? YES : NO;
}
NSWindow* window = GetNSWindowForDOMWindow(parent);
*_retval = (PRBool)[controller prompt:window title:titleStr text:textStr promptText:valueStr checkMsg:msgStr checkValue:&valueBool doCheck:(checkValue != nsnull)];
if (checkValue) {
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
PRUint32 length = [valueStr length];
PRUnichar* retStr = (PRUnichar*)nsMemory::Alloc((length + 1) * sizeof(PRUnichar));
[valueStr getCharacters:retStr];
retStr[length] = PRUnichar(0);
*value = retStr;
return NS_OK;
}
/* boolean promptUsernameAndPassword (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, inout wstring username, inout wstring password, in wstring checkMsg, inout boolean checkValue); */
NS_IMETHODIMP
CocoaPromptService::PromptUsernameAndPassword(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRUnichar **username,
PRUnichar **password,
const PRUnichar *checkMsg,
PRBool *checkValue,
PRBool *_retval)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSMutableString* userNameStr = [NSMutableString stringWithPRUnichars:*username];
NSMutableString* passwordStr = [NSMutableString stringWithPRUnichars:*password];
BOOL valueBool;
if (checkValue) {
valueBool = *checkValue ? YES : NO;
}
NSWindow* window = GetNSWindowForDOMWindow(parent);
*_retval = (PRBool)[controller promptUserNameAndPassword:window title:titleStr text:textStr userNameText:userNameStr passwordText:passwordStr checkMsg:msgStr checkValue:&valueBool doCheck:(checkValue != nsnull)];
if (checkValue) {
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
PRUint32 length = [userNameStr length];
PRUnichar* retStr = (PRUnichar*)nsMemory::Alloc((length + 1) * sizeof(PRUnichar));
[userNameStr getCharacters:retStr];
retStr[length] = PRUnichar(0);
*username = retStr;
length = [passwordStr length];
retStr = (PRUnichar*)nsMemory::Alloc((length + 1) * sizeof(PRUnichar));
[passwordStr getCharacters:retStr];
retStr[length] = PRUnichar(0);
*password = retStr;
return NS_OK;
}
/* boolean promptPassword (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, inout wstring password, in wstring checkMsg, inout boolean checkValue); */
NS_IMETHODIMP
CocoaPromptService::PromptPassword(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRUnichar **password,
const PRUnichar *checkMsg,
PRBool *checkValue,
PRBool *_retval)
{
nsAlertController* controller = nsCocoaBrowserService::GetAlertController();
if (!controller) {
return NS_ERROR_FAILURE;
}
NSString* titleStr = [NSString stringWithPRUnichars:dialogTitle];
NSString* textStr = [NSString stringWithPRUnichars:text];
NSString* msgStr = [NSString stringWithPRUnichars:checkMsg];
NSMutableString* passwordStr = [NSMutableString stringWithPRUnichars:*password];
BOOL valueBool;
if (checkValue) {
valueBool = *checkValue ? YES : NO;
}
NSWindow* window = GetNSWindowForDOMWindow(parent);
*_retval = (PRBool)[controller promptPassword:window title:titleStr text:textStr passwordText:passwordStr checkMsg:msgStr checkValue:&valueBool doCheck:(checkValue != nsnull)];
if (checkValue) {
*checkValue = (valueBool == YES) ? PR_TRUE : PR_FALSE;
}
PRUint32 length = [passwordStr length];
PRUnichar* retStr = (PRUnichar*)nsMemory::Alloc((length + 1) * sizeof(PRUnichar));
[passwordStr getCharacters:retStr];
retStr[length] = PRUnichar(0);
*password = retStr;
return NS_OK;
}
/* boolean select (in nsIDOMWindow parent, in wstring dialogTitle, in wstring text, in PRUint32 count, [array, size_is (count)] in wstring selectList, out long outSelection); */
NS_IMETHODIMP
CocoaPromptService::Select(nsIDOMWindow *parent,
const PRUnichar *dialogTitle,
const PRUnichar *text,
PRUint32 count,
const PRUnichar **selectList,
PRInt32 *outSelection,
PRBool *_retval)
{
#if DEBUG
NSLog(@"Uh-oh. Select has not been implemented.");
#endif
return NS_ERROR_NOT_IMPLEMENTED;
}
NSWindow*
CocoaPromptService::GetNSWindowForDOMWindow(nsIDOMWindow* window)
{
nsCOMPtr<nsIWindowWatcher> watcher(do_GetService("@mozilla.org/embedcomp/window-watcher;1"));
if (!watcher) {
return nsnull;
}
nsCOMPtr<nsIWebBrowserChrome> chrome;
watcher->GetChromeForWindow(window, getter_AddRefs(chrome));
if (!chrome) {
return nsnull;
}
nsCOMPtr<nsIEmbeddingSiteWindow> siteWindow(do_QueryInterface(chrome));
if (!siteWindow) {
return nsnull;
}
NSWindow* nswin;
nsresult rv = siteWindow->GetSiteWindow((void**)&nswin);
if (NS_FAILED(rv))
return nsnull;
return nswin;
}
NSString *
CocoaPromptService::GetCommonDialogLocaleString(const char *key)
{
NSString *returnValue = @"";
nsresult rv;
if (!mCommonDialogStringBundle) {
#define kCommonDialogsStrings "chrome://global/locale/commonDialogs.properties"
nsCOMPtr<nsIStringBundleService> service = do_GetService(NS_STRINGBUNDLE_CONTRACTID);
if ( service )
rv = service->CreateBundle(kCommonDialogsStrings, getter_AddRefs(mCommonDialogStringBundle));
else
rv = NS_ERROR_FAILURE;
if (NS_FAILED(rv)) return returnValue;
}
nsXPIDLString string;
rv = mCommonDialogStringBundle->GetStringFromName(NS_ConvertASCIItoUCS2(key).get(), getter_Copies(string));
if (NS_FAILED(rv)) return returnValue;
returnValue = [NSString stringWithPRUnichars:string];
return returnValue;
}
NSString *
CocoaPromptService::GetButtonStringFromFlags(PRUint32 btnFlags,
PRUint32 btnIDAndShift,
const PRUnichar *btnTitle)
{
NSString *btnStr = nsnull;
switch ((btnFlags >> btnIDAndShift) & 0xff) {
case BUTTON_TITLE_OK:
btnStr = GetCommonDialogLocaleString("OK");
break;
case BUTTON_TITLE_CANCEL:
btnStr = GetCommonDialogLocaleString("Cancel");
break;
case BUTTON_TITLE_YES:
btnStr = GetCommonDialogLocaleString("Yes");
break;
case BUTTON_TITLE_NO:
btnStr = GetCommonDialogLocaleString("No");
break;
case BUTTON_TITLE_SAVE:
btnStr = GetCommonDialogLocaleString("Save");
break;
case BUTTON_TITLE_DONT_SAVE:
btnStr = GetCommonDialogLocaleString("DontSave");
break;
case BUTTON_TITLE_REVERT:
btnStr = GetCommonDialogLocaleString("Revert");
break;
case BUTTON_TITLE_IS_STRING:
btnStr = [NSString stringWithPRUnichars:btnTitle];
}
return btnStr;
}

View File

@ -1,69 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __ContentClickListener_h__
#define __ContentClickListener_h__
#include <Carbon/Carbon.h>
#include <Cocoa/Cocoa.h>
#include "nsIDOMMouseListener.h"
#import "BrowserWindowController.h"
class ContentClickListener : public nsIDOMMouseListener
{
public:
ContentClickListener(id aBrowserController);
virtual ~ContentClickListener();
NS_DECL_ISUPPORTS
// The DOM mouse listener interface. We only care about clicks.
NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) { return NS_OK; };
NS_IMETHOD MouseDown(nsIDOMEvent* aMouseEvent);
NS_IMETHOD MouseUp(nsIDOMEvent* aMouseEvent) { return NS_OK; };
NS_IMETHOD MouseClick(nsIDOMEvent* aMouseEvent);
NS_IMETHOD MouseDblClick(nsIDOMEvent* aMouseEvent) { return NS_OK; };
NS_IMETHOD MouseOver(nsIDOMEvent* aMouseEvent) { return NS_OK; };
NS_IMETHOD MouseOut(nsIDOMEvent* aMouseEvent) { return NS_OK; };
private:
BrowserWindowController* mBrowserController; // Our browser controller (weakly held)
};
#endif

View File

@ -1,311 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* David Hyatt <hyatt@netscape.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "NSString+Utils.h"
#include "nsCOMPtr.h"
#include "ContentClickListener.h"
#include "nsIDOMEventTarget.h"
#include "nsIContent.h"
#include "nsIAtom.h"
#include "nsIDOMElement.h"
#include "nsString.h"
#include "nsUnicharUtils.h"
#include "nsIPrefBranch.h"
#include "nsIDOMMouseEvent.h"
#include "nsEmbedAPI.h"
#include "nsIDOMDocument.h"
#include "nsIDOMDocumentEvent.h"
#include "nsIDOMEventTarget.h"
#include "nsIDOMNSHTMLElement.h"
#include "nsIDOMHTMLSelectElement.h"
#include "nsIDOMHTMLOptionElement.h"
#include "nsIDOMHTMLCollection.h"
#include "nsIDOMWindow.h"
#include "nsIScriptGlobalObject.h"
#include "nsIDocument.h"
#include "nsIPresShell.h"
#include "nsIPresContext.h"
#include "nsIFrame.h"
#include "nsIView.h"
#include "nsIWidget.h"
#include "nsIURI.h"
#include "nsIProtocolHandler.h"
#include "nsNetUtil.h"
// Common helper routines (also used by the context menu code)
#include "CHGeckoUtils.h"
#import "CHBrowserView.h"
static void FindOptionWithContentID(nsIDOMHTMLSelectElement* aSel, PRUint32 aID, nsIDOMHTMLOptionElement** aResult)
{
*aResult = nsnull;
nsCOMPtr<nsIDOMHTMLCollection> options;
aSel->GetOptions(getter_AddRefs(options));
PRUint32 count;
options->GetLength(&count);
for (PRUint32 i = 0; i < count; i++) {
nsCOMPtr<nsIDOMNode> node;
options->Item(i, getter_AddRefs(node));
PRUint32 contentID;
nsCOMPtr<nsIContent> content(do_QueryInterface(node));
content->GetContentID(&contentID);
if (contentID == aID) {
nsCOMPtr<nsIDOMHTMLOptionElement> option(do_QueryInterface(node));
*aResult = option;
NS_ADDREF(*aResult);
break;
}
}
}
@interface CHOptionSelector : NSObject
{
nsIDOMHTMLSelectElement* mSelectElt;
}
-(id)initWithSelect:(nsIDOMHTMLSelectElement*)aSel;
-(IBAction)selectOption:(id)aSender;
@end
@implementation CHOptionSelector
-(id)initWithSelect:(nsIDOMHTMLSelectElement*)aSel
{
if ( (self = [super init]) ) {
mSelectElt = aSel;
}
return self;
}
-(IBAction)selectOption:(id)aSender
{
int tag = [aSender tag];
nsCOMPtr<nsIDOMHTMLOptionElement> optionElt;
FindOptionWithContentID(mSelectElt, tag, getter_AddRefs(optionElt));
optionElt->SetSelected(PR_TRUE);
[self autorelease]; // Free up ourselves.
[[aSender menu] autorelease]; // Free up the menu.
// Fire a DOM event for the title change.
nsCOMPtr<nsIDOMEvent> event;
nsCOMPtr<nsIDOMDocument> domDocument;
mSelectElt->GetOwnerDocument(getter_AddRefs(domDocument));
nsCOMPtr<nsIDOMDocumentEvent> docEvent(do_QueryInterface(domDocument));
docEvent->CreateEvent(NS_LITERAL_STRING("Events"), getter_AddRefs(event));
if (event) {
event->InitEvent(NS_LITERAL_STRING("change"), PR_TRUE, PR_TRUE);
PRBool noDefault;
nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(mSelectElt));
target->DispatchEvent(event, &noDefault);
}
}
@end
NS_IMPL_ISUPPORTS2(ContentClickListener, nsIDOMMouseListener, nsIDOMEventListener);
ContentClickListener::ContentClickListener(id aBrowserController)
:mBrowserController(aBrowserController)
{
NS_INIT_ISUPPORTS();
}
ContentClickListener::~ContentClickListener()
{
}
NS_IMETHODIMP
ContentClickListener::MouseDown(nsIDOMEvent* aEvent)
{
nsCOMPtr<nsIDOMEventTarget> target;
aEvent->GetTarget(getter_AddRefs(target));
if (!target)
return NS_OK;
nsCOMPtr<nsIDOMHTMLSelectElement> sel(do_QueryInterface(target));
if (sel) {
NSMenu* menu = [[NSMenu alloc] init]; // Retain the menu.
nsCOMPtr<nsIDOMHTMLCollection> options;
sel->GetOptions(getter_AddRefs(options));
PRUint32 count;
options->GetLength(&count);
PRInt32 selIndex = 0;
for (PRUint32 i = 0; i < count; i++) {
nsCOMPtr<nsIDOMNode> node;
options->Item(i, getter_AddRefs(node));
PRUint32 contentID;
nsCOMPtr<nsIContent> content(do_QueryInterface(node));
content->GetContentID(&contentID);
nsCOMPtr<nsIDOMHTMLOptionElement> option(do_QueryInterface(node));
nsAutoString text;
option->GetLabel(text);
if (text.IsEmpty())
option->GetText(text);
NSString* title = [[NSString stringWith_nsAString: text] stringByTruncatingTo:75 at:kTruncateAtMiddle];
NSMenuItem* menuItem = [[[NSMenuItem alloc] initWithTitle: title action: NULL keyEquivalent: @""] autorelease];
[menu addItem: menuItem];
[menuItem setTag: contentID];
PRBool selected;
option->GetSelected(&selected);
if (selected) {
[menuItem setState: NSOnState];
selIndex = i;
}
CHOptionSelector* optSelector = [[CHOptionSelector alloc] initWithSelect: sel];
[menuItem setTarget: optSelector];
[menuItem setAction: @selector(selectOption:)];
}
nsCOMPtr<nsIDOMNSHTMLElement> nsSel(do_QueryInterface(sel));
PRInt32 left, top, height;
PRInt32 clientX, clientY;
nsSel->GetOffsetLeft(&left);
nsSel->GetOffsetTop(&top);
nsSel->GetOffsetHeight(&height);
nsCOMPtr<nsIDOMElement> currOffsetParent;
nsSel->GetOffsetParent(getter_AddRefs(currOffsetParent));
while (currOffsetParent) {
nsCOMPtr<nsIDOMNSHTMLElement> currNS(do_QueryInterface(currOffsetParent));
PRInt32 currLeft, currTop;
currNS->GetOffsetLeft(&currLeft);
currNS->GetOffsetTop(&currTop);
left += currLeft;
top += currTop;
currNS->GetOffsetParent(getter_AddRefs(currOffsetParent));
}
nsCOMPtr<nsIDOMMouseEvent> msEvent(do_QueryInterface(aEvent));
msEvent->GetClientX(&clientX);
msEvent->GetClientY(&clientY);
PRInt32 xDelta = clientX - left;
PRInt32 yDelta = top + height - clientY;
nsCOMPtr<nsIDOMWindow> window = getter_AddRefs([[[mBrowserController getBrowserWrapper] getBrowserView] getContentWindow]);
PRInt32 scrollX, scrollY;
window->GetScrollX(&scrollX);
window->GetScrollY(&scrollY);
xDelta += scrollX; // Normal direction.
yDelta -= scrollY; // Remember, y is flipped.
#define XMENUOFFSET 20
#define MENUHEIGHT 20
xDelta += XMENUOFFSET;
yDelta -= MENUHEIGHT*(selIndex+1);
NSEvent* event = [NSApp currentEvent];
NSPoint point = [event locationInWindow];
point.x -= xDelta;
point.y -= yDelta;
NSEvent* mouseEvent = [NSEvent mouseEventWithType: NSLeftMouseDown location: point
modifierFlags: 0 timestamp: [event timestamp]
windowNumber: [event windowNumber] context: [event context]
eventNumber: [event eventNumber] clickCount: [event clickCount] pressure: [event pressure]];
[NSMenu popUpContextMenu: menu withEvent: mouseEvent forView: [[mBrowserController window] contentView]];
}
return NS_OK;
}
NS_IMETHODIMP
ContentClickListener::MouseClick(nsIDOMEvent* aEvent)
{
nsCOMPtr<nsIDOMEventTarget> target;
aEvent->GetTarget(getter_AddRefs(target));
if (!target)
return NS_OK;
nsCOMPtr<nsIDOMNode> content(do_QueryInterface(target));
nsCOMPtr<nsIDOMElement> linkContent;
nsAutoString href;
CHGeckoUtils::GetEnclosingLinkElementAndHref(content, getter_AddRefs(linkContent), href);
// XXXdwh Handle simple XLINKs if we want to be compatible with Mozilla, but who
// really uses these anyway? :)
if (!linkContent || href.IsEmpty())
return NS_OK;
nsCOMPtr<nsIPrefBranch> pref(do_GetService("@mozilla.org/preferences-service;1"));
if (!pref)
return NS_OK; // Something bad happened if we can't get prefs.
PRUint16 button;
nsCOMPtr<nsIDOMMouseEvent> mouseEvent(do_QueryInterface(aEvent));
mouseEvent->GetButton(&button);
PRBool metaKey, shiftKey, altKey;
mouseEvent->GetMetaKey(&metaKey);
mouseEvent->GetShiftKey(&shiftKey);
mouseEvent->GetAltKey(&altKey);
NSString* hrefStr = [NSString stringWith_nsAString: href];
if ((metaKey && button == 0) || button == 1) {
// The command key is down or we got a middle click. Open the link in a new window or tab.
PRBool useTab;
pref->GetBoolPref("browser.tabs.opentabfor.middleclick", &useTab);
PRBool loadInBackground;
pref->GetBoolPref("browser.tabs.loadInBackground", &loadInBackground);
NSString* referrer = [[[mBrowserController getBrowserWrapper] getBrowserView] getFocusedURLString];
if (shiftKey)
loadInBackground = !loadInBackground;
if (useTab && [mBrowserController newTabsAllowed])
[mBrowserController openNewTabWithURL: hrefStr referrer:referrer loadInBackground: loadInBackground];
else
[mBrowserController openNewWindowWithURL: hrefStr referrer:referrer loadInBackground: loadInBackground];
}
else if (altKey) {
// The user wants to save this link.
nsAutoString text;
CHGeckoUtils::GatherTextUnder(content, text);
[mBrowserController saveURL: nil filterList: nil
url: hrefStr suggestedFilename: [NSString stringWith_nsAString: text]];
}
return NS_OK;
}

View File

@ -1,74 +0,0 @@
{\rtf1\mac\ansicpg10000\cocoartf100
{\fonttbl\f0\fswiss\fcharset77 Optima-BoldItalic;\f1\fswiss\fcharset77 Optima-Italic;\f2\fswiss\fcharset77 Optima-Regular;
\f3\fswiss\fcharset77 Optima-Bold;}
{\colortbl;\red255\green255\blue255;}
\pard\tx1440\tx2880\tx4320\tx5760\tx7200\ql\qnatural
\f0\i\b\fs18 \cf0 \
\fs68 Navigator 0.4.0\
\f1\b0\fs24 \
\
\
\
\
\
\
\
\f2\i0 Navigator version 0.4.0\
http://www.mozilla.org\
http://chimera.mozdev.org\
\fs48 \
\
\
\
\
\f0\i\b\fs28 Contributors:\
\f2\i0\b0\fs24 \
\f3\b Patrick Beard\
Kathy Brade\
Conrad Carlen\
Ugo Dantas De Santana\
Simon Fraser\
Ben Goodger\
David Haas\
Joe Hewitt\
Max Horn
\f2\b0 \
\f3\b David Hyatt
\f2\b0 \
\f3\b Matt Judy\
Mike Pinkerton\
Brian Ryner\
Richard Schreyer\
William Dell Wisner\
\
Mozilla Contributors:\
Type \'d2about:credits\'d3 in the Location bar.\
\f2\b0 \
\
\
\
\fs48 \
\f0\i\b\fs28 Special Thanks:\
\f2\i0\b0\fs24 \
\f3\b Apple Computer Software Engineering\
The Chimera Mailing List\
\f1\i\b0\fs36 \
\
\
}

View File

@ -1,47 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nscore.h"
// embedding app's factories for creating instances of interfaces
// related to downloading.
class nsIFactory;
nsresult NewDownloadListenerFactory(nsIFactory* *outFactory);
//nsresult NewHelperAppLauncherDialogFactory(nsIFactory* *outFactory);

View File

@ -1,120 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This file contains implementations of factories for various
// downloading-related interfaces.
#import "DownloadProgressDisplay.h"
#import "ProgressDlgController.h"
#include "nsCOMPtr.h"
#include "nsIFactory.h"
#include "nsDownloadListener.h"
#include "DownloadFactories.h"
// factory for nsIDownload objects
// XXX replace with generic factory stuff
class DownloadListenerFactory : public nsIFactory
{
public:
DownloadListenerFactory();
virtual ~DownloadListenerFactory();
NS_DECL_ISUPPORTS
NS_DECL_NSIFACTORY
protected:
DownloadControllerFactory* mControllerFactory; // factory which creates the Cocoa window controller
};
DownloadListenerFactory::DownloadListenerFactory()
: mControllerFactory(nil)
{
NS_INIT_ISUPPORTS();
mControllerFactory = [[ChimeraDownloadControllerFactory alloc] init];
}
DownloadListenerFactory::~DownloadListenerFactory()
{
[mControllerFactory release];
}
NS_IMPL_ISUPPORTS1(DownloadListenerFactory, nsIFactory);
/* void createInstance (in nsISupports aOuter, in nsIIDRef iid, [iid_is (iid), retval] out nsQIResult result); */
NS_IMETHODIMP
DownloadListenerFactory::CreateInstance(nsISupports *aOuter, const nsIID& aIID, void* *aResult)
{
nsresult rv;
if (aIID.Equals(NS_GET_IID(nsIDownload)))
{
nsDownloadListener* downloadListener = new nsDownloadListener(mControllerFactory);
if (!downloadListener) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(downloadListener);
rv = downloadListener->QueryInterface(aIID, aResult);
NS_RELEASE(downloadListener);
return rv;
}
return NS_ERROR_NO_INTERFACE;
}
/* void lockFactory (in PRBool lock); */
NS_IMETHODIMP
DownloadListenerFactory::LockFactory(PRBool lock)
{
return NS_OK;
}
#pragma mark -
nsresult NewDownloadListenerFactory(nsIFactory* *outFactory)
{
DownloadListenerFactory* newFactory = new DownloadListenerFactory();
if (!newFactory) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(newFactory);
nsresult rv = newFactory->QueryInterface(NS_GET_IID(nsIFactory), (void **)outFactory);
NS_RELEASE(newFactory);
return rv;
}

View File

@ -1,167 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
The classes and protocol in this file allow Cocoa applications to easily
reuse the underlying download implementation, which deals with the complexity
of Gecko's downloading callbacks.
There are three things here:
1. The DownloadProgressDisplay protocol.
This is a formal protocol that needs to be implemented by
a window controller for your progress window. Its methods
will be called by the underlying C++ downloading classes.
2. The Obj-C DownloadControllerFactory class.
This class should be subclassed by an embedder, with an
implementation of 'createDownloadController' that hands back
a new instance of an NSWindowController that implements the
<DownloadProgressDisplay> protocol.
The underlying C++ classes use this factory to create the
progress window controller.
3. The CHDownloader C++ class
This base class exists to hide the complextity of the download
listener classes (which deal with Gecko callbacks) from the
window controller. Embedders don't need to do anything with it.
How these classes fit together:
There are 2 ways in which a download is initiated:
(i) File->Save.
Chimera does a complex dance here in order to get certain
information about the data being downloaded (it needs to
start the download before it can read some optional MIME headers).
CBrowserView creates an nsIWebBrowserPersist (WBP), and then a
nsHeaderSniffer, which implements nsIWebProgressListener and is set to
observer the WBP. When nsHeaderSniffer hears about the start of the
download, it decides on a file name, and what format to save the data
in. It then cancels the current WPB, makes another one, and does
a CreateInstance of an nsIDownload (making one of our nsDownloadListener
-- aka nsDownloder -- objects), and sets that as the nsIWebProgressListener.
The full download procedes from there.
(ii) Click to download (e.g. FTP link)
This is simpler. The backend (necko) does the CreateInstance of the
nsIDownload, and the download progresses.
In both cases, creating the nsDownloadListener and calling its Init() method
calls nsDownloder::CreateDownloadDisplay(). The nsDownloder has as a member
variable a DownloadControllerFactory (see above), which got passed to it
via our XPCOM factory for nsIDownload objects. It then uses that DownloadControllerFactory
to get an instance of the download progress window controller, which then
shows the download progress window.
Simple, eh?
*/
#import <AppKit/AppKit.h>
#include "nsISupports.h"
class CHDownloader;
// a formal protocol for something that implements progress display
// Embedders can make a window controller that conforms to this
// protocol, and reuse nsDownloadListener to get download UI.
@protocol DownloadProgressDisplay
- (void)onStartDownload:(BOOL)isFileSave;
- (void)onEndDownload;
- (void)setProgressTo:(long)aCurProgress ofMax:(long)aMaxProgress;
- (void)setDownloadListener:(CHDownloader*)aDownloader;
- (void)setSourceURL:(NSString*)aSourceURL;
- (void)setDestinationPath:(NSString*)aDestPath;
@end
// subclass this, and have your subclass instantiate and return your window
// controller in createDownloadController
@interface DownloadControllerFactory : NSObject
{
}
- (NSWindowController<DownloadProgressDisplay> *)createDownloadController;
@end
// Pure virtual base class for a generic downloader, that the progress UI can talk to.
// It implements nsISupports so that it can be refcounted. This class insulates the
// UI code from having to know too much about the nsIDownloadListener.
// It is responsible for creating the download UI, via the DownloadControllerFactory
// that it owns.
class CHDownloader : public nsISupports
{
public:
CHDownloader(DownloadControllerFactory* inControllerFactory);
virtual ~CHDownloader();
NS_DECL_ISUPPORTS
virtual void PauseDownload() = 0;
virtual void ResumeDownload() = 0;
virtual void CancelDownload() = 0;
virtual void DownloadDone() = 0;
virtual void DetachDownloadDisplay() = 0; // tell downloader to forget about its display
virtual void CreateDownloadDisplay();
protected:
PRBool IsFileSave() { return mIsFileSave; }
void SetIsFileSave(PRBool inIsFileSave) { mIsFileSave = inIsFileSave; }
protected:
DownloadControllerFactory* mControllerFactory;
id <DownloadProgressDisplay> mDownloadDisplay; // something that implements the DownloadProgressDisplay protocol
PRBool mIsFileSave; // true if we're doing a save, rather than a download
};

View File

@ -1,76 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Chimera code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Fraser <sfraser@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#import "DownloadProgressDisplay.h"
@implementation DownloadControllerFactory
- (NSWindowController<DownloadProgressDisplay> *)createDownloadController
{
// a dummy implementation. You should provide a subclass that
// returns an instance of your progress dialog controller.
return nil;
}
@end
#pragma mark -
// see the header file for comments
CHDownloader::CHDownloader(DownloadControllerFactory* inControllerFactory)
: mControllerFactory(inControllerFactory)
, mDownloadDisplay(nil)
, mIsFileSave(PR_FALSE)
{
NS_INIT_ISUPPORTS();
[mControllerFactory retain];
}
CHDownloader::~CHDownloader()
{
[mControllerFactory release];
}
NS_IMPL_ISUPPORTS1(CHDownloader, nsISupports);
void
CHDownloader::CreateDownloadDisplay()
{
mDownloadDisplay = [mControllerFactory createDownloadController];
[mDownloadDisplay setDownloadListener:this];
}

View File

@ -1,17 +0,0 @@
{
IBClasses = (
{
ACTIONS = {showPanel = id; };
CLASS = AboutBox;
LANGUAGE = ObjC;
OUTLETS = {
buildNumberField = NSTextField;
creditsField = NSTextView;
window = NSWindow;
};
SUPERCLASS = NSObject;
},
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBLockedObjects</key>
<array>
<integer>7</integer>
</array>
<key>IBOpenObjects</key>
<array>
<integer>5</integer>
</array>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,22 +0,0 @@
{
IBClasses = (
{
CLASS = BookmarkInfoController;
LANGUAGE = ObjC;
OUTLETS = {
mDescriptionField = NSTextField;
mDescriptionLabel = NSTextField;
mKeywordField = NSTextField;
mKeywordLabel = NSTextField;
mLocationField = NSTextField;
mLocationLabel = NSTextField;
mNameField = NSTextField;
mNameLabel = NSTextField;
};
SUPERCLASS = NSWindowController;
},
{CLASS = BookmarkItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>144 74 366 258 0 0 1280 1002 </string>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

View File

@ -1,141 +0,0 @@
{
IBClasses = (
{CLASS = AutoCompleteDataSource; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {onBlur = id; onResize = id; };
CLASS = AutoCompleteTextField;
LANGUAGE = ObjC;
OUTLETS = {mProxyIcon = PageProxyIcon; };
SUPERCLASS = NSTextField;
},
{CLASS = BookmarkItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {
addBookmark = id;
addFolder = id;
deleteBookmarks = id;
openBookmarkInNewTab = id;
openBookmarkInNewWindow = id;
showBookmarkInfo = id;
};
CLASS = BookmarksDataSource;
LANGUAGE = ObjC;
OUTLETS = {
mBrowserWindowController = id;
mDeleteBookmarkButton = id;
mEditBookmarkButton = id;
mOutlineView = id;
};
SUPERCLASS = NSObject;
},
{
CLASS = BookmarksOutlineView;
LANGUAGE = ObjC;
SUPERCLASS = ExtendedOutlineView;
},
{CLASS = BookmarksToolbar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{CLASS = BrowserTabView; LANGUAGE = ObjC; SUPERCLASS = NSTabView; },
{
CLASS = BrowserWindow;
LANGUAGE = ObjC;
OUTLETS = {mAutoCompleteTextField = id; };
SUPERCLASS = NSWindow;
},
{
ACTIONS = {
back = id;
bookmarkLink = id;
bookmarkPage = id;
cancelAddBookmarkSheet = id;
cancelLocationSheet = id;
copyLinkLocation = id;
endAddBookmarkSheet = id;
endLocationSheet = id;
forward = id;
goToLocationFromToolbarURLField = id;
home = id;
manageBookmarks = id;
openLinkInNewTab = id;
openLinkInNewWindow = id;
performSearch = id;
printDocument = id;
reload = id;
saveImageAs = id;
saveLinkAs = id;
savePageAs = id;
stop = id;
toggleSidebar = id;
viewOnlyThisImage = id;
viewSource = id;
};
CLASS = BrowserWindowController;
LANGUAGE = ObjC;
OUTLETS = {
mAddBookmarkCheckbox = NSButton;
mAddBookmarkFolderField = NSPopUpButton;
mAddBookmarkSheetWindow = NSWindow;
mAddBookmarkTitleField = NSTextField;
mBackItem = NSMenuItem;
mCachedBMDS = id;
mForwardItem = NSMenuItem;
mHistoryDataSource = HistoryDataSource;
mImageLinkMenu = NSMenu;
mImageMenu = NSMenu;
mInputMenu = NSMenu;
mLinkMenu = NSMenu;
mLocationSheetURLField = NSTextField;
mLocationSheetWindow = NSWindow;
mLocationToolbarView = NSView;
mLock = NSImageView;
mPageMenu = NSMenu;
mPersonalToolbar = BookmarksToolbar;
mProgress = NSProgressIndicator;
mProxyIcon = NSImageView;
mSidebarBookmarksDataSource = BookmarksDataSource;
mSidebarBrowserView = id;
mSidebarDrawer = NSDrawer;
mSidebarSourceTabView = NSTabView;
mSidebarTabView = NSTabView;
mStatus = NSTextField;
mStatusBar = NSView;
mTabBrowser = BrowserTabView;
mURLBar = NSTextField;
};
SUPERCLASS = NSWindowController;
},
{
ACTIONS = {load = id; };
CLASS = BrowserWrapper;
LANGUAGE = ObjC;
OUTLETS = {
mLockIcon = id;
mWindowController = id;
progress = id;
progressSuper = id;
status = id;
urlbar = id;
};
SUPERCLASS = NSView;
},
{CLASS = ExtendedOutlineView; LANGUAGE = ObjC; SUPERCLASS = NSOutlineView; },
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
CLASS = HistoryDataSource;
LANGUAGE = ObjC;
OUTLETS = {mBrowserWindowController = id; };
SUPERCLASS = RDFOutlineViewDataSource;
},
{CLASS = LocationBar; LANGUAGE = ObjC; SUPERCLASS = NSView; },
{CLASS = MainController; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = PageProxyIcon; LANGUAGE = ObjC; SUPERCLASS = NSImageView; },
{
CLASS = RDFOutlineViewDataSource;
LANGUAGE = ObjC;
OUTLETS = {mOutlineView = id; };
SUPERCLASS = NSObject;
},
{CLASS = RDFOutlineViewItem; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = ThrobberHandler; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>172 80 630 599 0 0 1280 1002 </string>
<key>IBEditorPositions</key>
<dict>
<key>124</key>
<string>345 803 170 144 0 0 1280 1002 </string>
<key>160</key>
<string>165 292 195 666 0 0 1280 1002 </string>
<key>28</key>
<string>524 439 195 457 0 0 1280 1002 </string>
<key>297</key>
<string>233 646 176 162 0 0 1152 848 </string>
<key>314</key>
<string>418 732 139 66 0 0 1152 848 </string>
<key>336</key>
<string>630 666 200 132 0 0 1152 848 </string>
<key>365</key>
<string>22 587 93 162 0 0 1152 848 </string>
<key>463</key>
<string>22 619 200 180 0 0 1152 848 </string>
<key>56</key>
<string>450 634 343 68 0 0 1280 1002 </string>
</dict>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBGroupedObjects</key>
<dict>
<key>3</key>
<array>
<string>8</string>
<string>9</string>
</array>
</dict>
<key>IBLastGroupID</key>
<string>4</string>
<key>IBLockedObjects</key>
<array/>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,19 +0,0 @@
{
IBClasses = (
{
ACTIONS = {find = id; };
CLASS = FindDlgController;
LANGUAGE = ObjC;
OUTLETS = {
mFindButton = NSButton;
mIgnoreCaseBox = NSButton;
mSearchBackwardsBox = NSButton;
mSearchField = NSTextField;
mWrapAroundBox = NSButton;
};
SUPERCLASS = NSWindowController;
},
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>180 86 356 240 0 0 1152 746 </string>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,32 +0,0 @@
{
IBClasses = (
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{
ACTIONS = {showAll = id; showPreferences = id; };
CLASS = MVPreferencesController;
LANGUAGE = ObjC;
OUTLETS = {
groupView = id;
loadingImageView = id;
loadingTextFeld = id;
loadingView = id;
multiView = id;
window = id;
};
SUPERCLASS = NSObject;
},
{
CLASS = MVPreferencesGroupedIconView;
LANGUAGE = ObjC;
OUTLETS = {preferencesController = id; };
SUPERCLASS = NSView;
},
{
CLASS = MVPreferencesMultipleIconView;
LANGUAGE = ObjC;
OUTLETS = {preferencesController = id; };
SUPERCLASS = NSView;
}
);
IBVersion = 1;
}

View File

@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>16 36 356 240 0 0 1024 746 </string>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBOpenObjects</key>
<array>
<integer>7</integer>
</array>
<key>IBSystem Version</key>
<string>5Q125</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,80 +0,0 @@
{
IBClasses = (
{
CLASS = BrowserToolbarController;
LANGUAGE = ObjC;
SUPERCLASS = ToolbarController;
},
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
{CLASS = GoMenu; LANGUAGE = ObjC; SUPERCLASS = NSMenu; },
{
ACTIONS = {
addBookmark = id;
addFolder = id;
addSeparator = id;
biggerTextSize = id;
closeTab = id;
displayPreferencesWindow = id;
doReload = id;
doSearch = id;
doStop = id;
feedbackLink = id;
findAgain = id;
findInPage = id;
getInfo = id;
goBack = id;
goForward = id;
goHome = id;
importBookmarks = id;
infoLink = id;
manageBookmarks = id;
newTab = id;
newWindow = id;
nextTab = id;
openFile = id;
openLocation = id;
openMenuBookmark = id;
previousTab = id;
printPage = id;
printPreview = id;
savePage = id;
showAboutBox = id;
smallerTextSize = id;
toggleBookmarksToolbar = id;
toggleOfflineMode = id;
toggleSidebar = id;
viewSource = id;
};
CLASS = MainController;
LANGUAGE = ObjC;
OUTLETS = {
mAddBookmarkMenuItem = NSMenuItem;
mApplication = NSApplication;
mBookmarksMenu = NSMenu;
mBookmarksToolbarMenuItem = NSMenuItem;
mCloseTabMenuItem = NSMenuItem;
mCloseWindowMenuItem = NSMenuItem;
mCreateBookmarksFolderMenuItem = NSMenuItem;
mCreateBookmarksSeparatorMenuItem = NSMenuItem;
mFilterList = NSPopUpButton;
mFilterView = NSView;
mToggleSidebarMenuItem = NSMenuItem;
};
SUPERCLASS = NSObject;
},
{
ACTIONS = {load = id; };
CLASS = MyBrowserView;
LANGUAGE = ObjC;
OUTLETS = {progress = id; progressSuper = id; status = id; urlbar = id; };
SUPERCLASS = NSView;
},
{
CLASS = ToolbarController;
LANGUAGE = ObjC;
OUTLETS = {mBrowserView = id; mWindow = id; };
SUPERCLASS = NSObject;
}
);
IBVersion = 1;
}

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>IBDocumentLocation</key>
<string>108 107 477 485 0 0 1280 1002 </string>
<key>IBEditorPositions</key>
<dict>
<key>266</key>
<string>483 623 277 90 0 0 1280 1002 </string>
<key>29</key>
<string>8 957 446 44 0 0 1280 1002 </string>
</dict>
<key>IBFramework Version</key>
<string>248.0</string>
<key>IBGroupedObjects</key>
<dict>
<key>0</key>
<array>
<string>0</string>
<string>0</string>
<string>0</string>
</array>
<key>1</key>
<array>
<string>0</string>
<string>0</string>
</array>
</dict>
<key>IBLastGroupID</key>
<string>2</string>
<key>IBOpenObjects</key>
<array>
<integer>29</integer>
</array>
<key>IBSystem Version</key>
<string>5S66</string>
</dict>
</plist>

Binary file not shown.

View File

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>Commands</key>
<dict>
<key>GetURL</key>
<dict>
<key>Description</key>
<string>Load a URL in the frontmost window</string>
<key>Name</key>
<string>Get URL</string>
</dict>
<key>OpenURL</key>
<dict>
<key>Description</key>
<string>Load a URL in the frontmost window</string>
<key>Name</key>
<string>open url</string>
</dict>
</dict>
<key>Description</key>
<string>Navigator's scripting suite</string>
<key>Name</key>
<string>Navigator suite</string>
</dict>
</plist>

Some files were not shown because too many files have changed in this diff Show More