[SCM] WebKit Debian packaging branch, debian/unstable, updated. debian/1.1.15-1-40151-g37bb677

mjs mjs at 268f45cc-cd09-0410-ab3c-d52691b4dbfc
Sat Sep 26 07:59:32 UTC 2009


The following commit has been merged in the debian/unstable branch:
commit 6e25d9d174e80364b85033f292e76b98f3130e55
Author: mjs <mjs at 268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Date:   Fri Oct 3 00:48:08 2003 +0000

            Folded Private implementation files into the regular ones as the
    	first step towards pulling in our SPI exposure and other code
    	cleanup.
    
            * History.subproj/WebHistory.m:
            * History.subproj/WebHistoryPrivate.m: Removed.
            * Misc.subproj/WebIconDatabasePrivate.h:
            * WebKit.pbproj/project.pbxproj:
            * WebView.subproj/WebDataSource.m:
            * WebView.subproj/WebDataSourcePrivate.m: Removed.
            * WebView.subproj/WebFrame.m:
            * WebView.subproj/WebFramePrivate.m: Removed.
            * WebView.subproj/WebFrameView.m:
            * WebView.subproj/WebFrameViewPrivate.m: Removed.
            * WebView.subproj/WebHTMLView.m:
            * WebView.subproj/WebHTMLViewPrivate.m: Removed.
            * WebView.subproj/WebView.m:
            * WebView.subproj/WebViewPrivate.m: Removed.
    
    
    git-svn-id: http://svn.webkit.org/repository/webkit/trunk@5127 268f45cc-cd09-0410-ab3c-d52691b4dbfc

diff --git a/WebKit/ChangeLog b/WebKit/ChangeLog
index bcd2111..055f89c 100644
--- a/WebKit/ChangeLog
+++ b/WebKit/ChangeLog
@@ -1,3 +1,24 @@
+2003-10-02  Maciej Stachowiak  <mjs at apple.com>
+
+        Folded Private implementation files into the regular ones as the
+	first step towards pulling in our SPI exposure and other code
+	cleanup.
+
+        * History.subproj/WebHistory.m:
+        * History.subproj/WebHistoryPrivate.m: Removed.
+        * Misc.subproj/WebIconDatabasePrivate.h:
+        * WebKit.pbproj/project.pbxproj:
+        * WebView.subproj/WebDataSource.m:
+        * WebView.subproj/WebDataSourcePrivate.m: Removed.
+        * WebView.subproj/WebFrame.m:
+        * WebView.subproj/WebFramePrivate.m: Removed.
+        * WebView.subproj/WebFrameView.m:
+        * WebView.subproj/WebFrameViewPrivate.m: Removed.
+        * WebView.subproj/WebHTMLView.m:
+        * WebView.subproj/WebHTMLViewPrivate.m: Removed.
+        * WebView.subproj/WebView.m:
+        * WebView.subproj/WebViewPrivate.m: Removed.
+
 2003-10-02  Chris Blumenberg  <cblu at apple.com>
 
 	Fixed: <rdar://problem/3440063>: Safari 1.1 won't load new pages after visiting adultswim.com, assertion failure on debug build
diff --git a/WebKit/History.subproj/WebHistory.m b/WebKit/History.subproj/WebHistory.m
index 7c21dba..e1ba922 100644
--- a/WebKit/History.subproj/WebHistory.m
+++ b/WebKit/History.subproj/WebHistory.m
@@ -5,18 +5,20 @@
 //  Created by John Sullivan on Mon Feb 18 2002.
 //  Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
 //
+
 #import <WebKit/WebHistory.h>
 #import <WebKit/WebHistoryPrivate.h>
+
 #import <WebKit/WebHistoryItem.h>
 #import <WebKit/WebHistoryItemPrivate.h>
 #import <WebKit/WebKitLogging.h>
 #import <WebKit/WebNSURLExtras.h>
-
 #import <Foundation/NSError.h>
 #import <WebKit/WebAssertions.h>
-
 #import <WebCore/WebCoreHistory.h>
 
+#import <Foundation/NSCalendarDate_NSURLExtras.h>
+
 
 NSString *WebHistoryItemsAddedNotification = @"WebHistoryItemsAddedNotification";
 NSString *WebHistoryItemsRemovedNotification = @"WebHistoryItemsRemovedNotification";
@@ -27,6 +29,461 @@ NSString *WebHistoryItemsKey = @"WebHistoryItems";
 
 static WebHistory *_sharedHistory = nil;
 
+
+
+NSString *FileVersionKey = @"WebHistoryFileVersion";
+NSString *DatesArrayKey = @"WebHistoryDates";
+
+#define currentFileVersion	1
+
+ at implementation WebHistoryPrivate
+
+#pragma mark OBJECT FRAMEWORK
+
++ (void)initialize
+{
+    [[NSUserDefaults standardUserDefaults] registerDefaults:
+        [NSDictionary dictionaryWithObjectsAndKeys:
+            @"1000", @"WebKitHistoryItemLimit",
+            @"7", @"WebKitHistoryAgeInDaysLimit",
+            nil]];    
+}
+
+- (id)init
+{
+    if (![super init]) {
+        return nil;
+    }
+    
+    _entriesByURL = [[NSMutableDictionary alloc] init];
+    _datesWithEntries = [[NSMutableArray alloc] init];
+    _entriesByDate = [[NSMutableArray alloc] init];
+
+    return self;
+}
+
+- (void)dealloc
+{
+    [_entriesByURL release];
+    [_datesWithEntries release];
+    [_entriesByDate release];
+    
+    [super dealloc];
+}
+
+#pragma mark MODIFYING CONTENTS
+
+// Returns whether the day is already in the list of days,
+// and fills in *index with the found or proposed index.
+- (BOOL)findIndex: (int *)index forDay: (NSCalendarDate *)date
+{
+    int count;
+
+    ASSERT_ARG(index, index != nil);
+
+    //FIXME: just does linear search through days; inefficient if many days
+    count = [_datesWithEntries count];
+    for (*index = 0; *index < count; ++*index) {
+        NSComparisonResult result = [date _web_compareDay: [_datesWithEntries objectAtIndex: *index]];
+        if (result == NSOrderedSame) {
+            return YES;
+        }
+        if (result == NSOrderedDescending) {
+            return NO;
+        }
+    }
+
+    return NO;
+}
+
+- (void)insertItem: (WebHistoryItem *)entry atDateIndex: (int)dateIndex
+{
+    int index, count;
+    NSMutableArray *entriesForDate;
+    NSCalendarDate *entryDate;
+
+    ASSERT_ARG(entry, entry != nil);
+    ASSERT_ARG(dateIndex, dateIndex >= 0 && (uint)dateIndex < [_entriesByDate count]);
+
+    //FIXME: just does linear search through entries; inefficient if many entries for this date
+    entryDate = [entry _lastVisitedDate];
+    entriesForDate = [_entriesByDate objectAtIndex: dateIndex];
+    count = [entriesForDate count];
+    // optimized for inserting oldest to youngest
+    for (index = 0; index < count; ++index) {
+        if ([entryDate compare: [[entriesForDate objectAtIndex: index] _lastVisitedDate]] != NSOrderedAscending) {
+            break;
+        }
+    }
+
+    [entriesForDate insertObject: entry atIndex: index];
+}
+
+- (BOOL)removeItemForURLString: (NSString *)URLString
+{
+    NSMutableArray *entriesForDate;
+    WebHistoryItem *entry;
+    int dateIndex;
+    BOOL foundDate;
+
+    entry = [_entriesByURL objectForKey: URLString];
+    if (entry == nil) {
+        return NO;
+    }
+
+    [_entriesByURL removeObjectForKey: URLString];
+
+    foundDate = [self findIndex: &dateIndex forDay: [entry _lastVisitedDate]];
+
+    ASSERT(foundDate);
+    
+    entriesForDate = [_entriesByDate objectAtIndex: dateIndex];
+    [entriesForDate removeObjectIdenticalTo: entry];
+
+    // remove this date entirely if there are no other entries on it
+    if ([entriesForDate count] == 0) {
+        [_entriesByDate removeObjectAtIndex: dateIndex];
+        [_datesWithEntries removeObjectAtIndex: dateIndex];
+    }
+
+    return YES;
+}
+
+
+- (void)addItem: (WebHistoryItem *)entry
+{
+    int dateIndex;
+    NSString *URLString;
+
+    ASSERT_ARG(entry, entry);
+    ASSERT_ARG(entry, [entry lastVisitedTimeInterval] != 0);
+
+    URLString = [entry URLString];
+
+    // If we already have an item with this URL, we need to merge info that drives the
+    // URL autocomplete heuristics from that item into the new one.
+    WebHistoryItem *oldEntry = [_entriesByURL objectForKey: URLString];
+    if (oldEntry) {
+        [entry _mergeAutoCompleteHints:oldEntry];
+    }
+
+    [self removeItemForURLString: URLString];
+
+    if ([self findIndex: &dateIndex forDay: [entry _lastVisitedDate]]) {
+        // other entries already exist for this date
+        [self insertItem: entry atDateIndex: dateIndex];
+    } else {
+        // no other entries exist for this date
+        [_datesWithEntries insertObject: [entry _lastVisitedDate] atIndex: dateIndex];
+        [_entriesByDate insertObject: [NSMutableArray arrayWithObject:entry] atIndex: dateIndex];
+    }
+
+    [_entriesByURL setObject: entry forKey: URLString];
+}
+
+- (BOOL)removeItem: (WebHistoryItem *)entry
+{
+    WebHistoryItem *matchingEntry;
+    NSString *URLString;
+
+    URLString = [entry URLString];
+
+    // If this exact object isn't stored, then make no change.
+    // FIXME: Is this the right behavior if this entry isn't present, but another entry for the same URL is?
+    // Maybe need to change the API to make something like removeEntryForURLString public instead.
+    matchingEntry = [_entriesByURL objectForKey: URLString];
+    if (matchingEntry != entry) {
+        return NO;
+    }
+
+    [self removeItemForURLString: URLString];
+
+    return YES;
+}
+
+- (BOOL)removeItems: (NSArray *)entries
+{
+    int index, count;
+
+    count = [entries count];
+    if (count == 0) {
+        return NO;
+    }
+
+    for (index = 0; index < count; ++index) {
+        [self removeItem:[entries objectAtIndex:index]];
+    }
+    
+    return YES;
+}
+
+- (BOOL)removeAllItems
+{
+    if ([_entriesByURL count] == 0) {
+        return NO;
+    }
+
+    [_entriesByDate removeAllObjects];
+    [_datesWithEntries removeAllObjects];
+    [_entriesByURL removeAllObjects];
+
+    return YES;
+}
+
+- (void)addItems:(NSArray *)newEntries
+{
+    NSEnumerator *enumerator;
+    WebHistoryItem *entry;
+
+    // There is no guarantee that the incoming entries are in any particular
+    // order, but if this is called with a set of entries that were created by
+    // iterating through the results of orderedLastVisitedDays and orderedItemsLastVisitedOnDayy
+    // then they will be ordered chronologically from newest to oldest. We can make adding them
+    // faster (fewer compares) by inserting them from oldest to newest.
+    enumerator = [newEntries reverseObjectEnumerator];
+    while ((entry = [enumerator nextObject]) != nil) {
+        [self addItem:entry];
+    }
+}
+
+#pragma mark DATE-BASED RETRIEVAL
+
+- (NSArray *)orderedLastVisitedDays
+{
+    return _datesWithEntries;
+}
+
+- (NSArray *)orderedItemsLastVisitedOnDay: (NSCalendarDate *)date
+{
+    int index;
+
+    if ([self findIndex: &index forDay: date]) {
+        return [_entriesByDate objectAtIndex: index];
+    }
+
+    return nil;
+}
+
+#pragma mark URL MATCHING
+
+- (WebHistoryItem *)itemForURLString:(NSString *)URLString
+{
+    return [_entriesByURL objectForKey: URLString];
+}
+
+- (BOOL)containsItemForURLString: (NSString *)URLString
+{
+    return [self itemForURLString:URLString] != nil;
+}
+
+- (BOOL)containsURL: (NSURL *)URL
+{
+    return [self itemForURLString:[URL _web_originalDataAsString]] != nil;
+}
+
+- (WebHistoryItem *)itemForURL:(NSURL *)URL
+{
+    return [self itemForURLString:[URL _web_originalDataAsString]];
+}	
+
+#pragma mark ARCHIVING/UNARCHIVING
+
+// Return a date that marks the age limit for history entries saved to or
+// loaded from disk. Any entry on this day or older should be rejected,
+// as tested with -[NSCalendarDate compareDay:]
+- (NSCalendarDate *)_ageLimitDate
+{
+    int ageInDaysLimit;
+
+    ageInDaysLimit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryAgeInDaysLimit"];
+    return [[NSCalendarDate calendarDate] dateByAddingYears:0 months:0 days:-ageInDaysLimit
+                                                      hours:0 minutes:0 seconds:0];
+}
+
+// Return a flat array of WebHistoryItems. Leaves out entries older than the age limit.
+// Stops filling array when item count limit is reached, even if there are currently
+// more entries than that.
+- (NSArray *)arrayRepresentation
+{
+    int dateCount, dateIndex;
+    int limit;
+    int totalSoFar;
+    NSMutableArray *arrayRep;
+    NSCalendarDate *ageLimitDate;
+
+    arrayRep = [NSMutableArray array];
+
+    limit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryItemLimit"];
+    ageLimitDate = [self _ageLimitDate];
+    totalSoFar = 0;
+    
+    dateCount = [_entriesByDate count];
+    for (dateIndex = 0; dateIndex < dateCount; ++dateIndex) {
+        int entryCount, entryIndex;
+        NSArray *entries;
+
+        // skip remaining days if they are older than the age limit
+        if ([[_datesWithEntries objectAtIndex:dateIndex] _web_compareDay:ageLimitDate] != NSOrderedDescending) {
+            break;
+        }
+
+        entries = [_entriesByDate objectAtIndex:dateIndex];
+        entryCount = [entries count];
+        for (entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
+            if (totalSoFar++ >= limit) {
+                break;
+            }
+            [arrayRep addObject: [[entries objectAtIndex:entryIndex] dictionaryRepresentation]];
+        }
+    }
+
+    return arrayRep;
+}
+
+- (BOOL)_loadHistoryGuts: (int *)numberOfItemsLoaded URL:(NSURL *)URL error:(NSError **)error
+{
+    *numberOfItemsLoaded = 0;
+
+    NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:error];
+    id propertyList = nil;
+    if (data && [data length] > 0) {
+        propertyList = [NSPropertyListSerialization propertyListFromData:data
+                                                        mutabilityOption:NSPropertyListImmutable
+                                                                  format:nil
+                                                        errorDescription:nil];
+    }
+
+    // propertyList might be an old-style NSArray or a more modern NSDictionary.
+    // If it's an NSArray, convert it to new format before further processing.
+    NSDictionary *fileAsDictionary = nil;
+    if ([propertyList isKindOfClass:[NSDictionary class]]) {
+        fileAsDictionary = propertyList;
+    } else if ([propertyList isKindOfClass:[NSArray class]]) {
+        // Convert old-style array into new-style dictionary
+        fileAsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
+            propertyList, DatesArrayKey,
+            [NSNumber numberWithInt:1], FileVersionKey,
+            nil];
+    } else {
+        if ([URL isFileURL] && [[NSFileManager defaultManager] fileExistsAtPath: [URL path]]) {
+            ERROR("unable to read history from file %@; perhaps contents are corrupted", [URL path]);
+        }
+        return NO;
+    }
+
+    NSNumber *fileVersionObject = [fileAsDictionary objectForKey:FileVersionKey];
+    int fileVersion;
+    // we don't trust data read from disk, so double-check
+    if (fileVersionObject != nil && [fileVersionObject isKindOfClass:[NSNumber class]]) {
+        fileVersion = [fileVersionObject intValue];
+    } else {
+        ERROR("history file version can't be determined, therefore not loading");
+        return NO;
+    }
+    if (fileVersion > currentFileVersion) {
+        ERROR("history file version is %d, newer than newest known version %d, therefore not loading", fileVersion, currentFileVersion);
+        return NO;
+    }    
+
+    NSArray *array = [fileAsDictionary objectForKey:DatesArrayKey];
+        
+    int limit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryItemLimit"];
+    NSCalendarDate *ageLimitDate = [self _ageLimitDate];
+    int index = 0;
+    // reverse dates so you're loading the oldest first, to minimize the number of comparisons
+    NSEnumerator *enumerator = [array reverseObjectEnumerator];
+    BOOL ageLimitPassed = NO;
+
+    NSDictionary *itemAsDictionary;
+    while ((itemAsDictionary = [enumerator nextObject]) != nil) {
+        WebHistoryItem *entry;
+
+        entry = [[[WebHistoryItem alloc] initFromDictionaryRepresentation:itemAsDictionary] autorelease];
+
+        if ([entry URLString] == nil) {
+            // entry without URL is useless; data on disk must have been bad; ignore
+            continue;
+        }
+
+        // test against date limit
+        if (!ageLimitPassed) {
+            if ([[entry _lastVisitedDate] _web_compareDay:ageLimitDate] != NSOrderedDescending) {
+                continue;
+            } else {
+                ageLimitPassed = YES;
+            }
+        }
+        
+        [self addItem: entry];
+        if (++index >= limit) {
+            break;
+        }
+    }
+
+    *numberOfItemsLoaded = MIN(index, limit);
+    return YES;    
+}
+
+- (BOOL)loadFromURL:(NSURL *)URL error:(NSError **)error
+{
+    int numberOfItems;
+    double start, duration;
+    BOOL result;
+
+    start = CFAbsoluteTimeGetCurrent();
+    result = [self _loadHistoryGuts: &numberOfItems URL:URL error:error];
+
+    if (result) {
+        duration = CFAbsoluteTimeGetCurrent() - start;
+        LOG(Timing, "loading %d history entries from %@ took %f seconds",
+            numberOfItems, URL, duration);
+    }
+
+    return result;
+}
+
+- (BOOL)_saveHistoryGuts: (int *)numberOfItemsSaved URL:(NSURL *)URL error:(NSError **)error
+{
+    *numberOfItemsSaved = 0;
+
+    // FIXME:  Correctly report error when new API is ready.
+    if (error)
+        *error = nil;
+
+    NSArray *array = [self arrayRepresentation];
+    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
+        array, DatesArrayKey,
+        [NSNumber numberWithInt:currentFileVersion], FileVersionKey,
+        nil];
+    if (![dictionary writeToURL:URL atomically:YES]) {
+        ERROR("attempt to save %@ to %@ failed", dictionary, URL);
+        return NO;
+    }
+    
+    *numberOfItemsSaved = [array count];
+    return YES;
+}
+
+- (BOOL)saveToURL:(NSURL *)URL error:(NSError **)error
+{
+    int numberOfItems;
+    double start, duration;
+    BOOL result;
+
+    start = CFAbsoluteTimeGetCurrent();
+    result = [self _saveHistoryGuts: &numberOfItems URL:URL error:error];
+
+    if (result) {
+        duration = CFAbsoluteTimeGetCurrent() - start;
+        LOG(Timing, "saving %d history entries to %@ took %f seconds",
+            numberOfItems, URL, duration);
+    }
+
+    return result;
+}
+
+ at end
+
 @interface _WebCoreHistoryProvider : NSObject  <WebCoreHistoryProvider> 
 {
     WebHistory *history;
diff --git a/WebKit/History.subproj/WebHistoryPrivate.m b/WebKit/History.subproj/WebHistoryPrivate.m
deleted file mode 100644
index 44d115a..0000000
--- a/WebKit/History.subproj/WebHistoryPrivate.m
+++ /dev/null
@@ -1,473 +0,0 @@
-//
-//  WebHistoryPrivate.m
-//  WebKit
-//
-//  Created by John Sullivan on Tue Feb 19 2002.
-//  Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
-//
-
-#import "WebHistoryPrivate.h"
-
-#import <WebKit/WebHistoryItem.h>
-#import <WebKit/WebHistoryItemPrivate.h>
-#import <WebKit/WebKitLogging.h>
-#import <WebKit/WebNSURLExtras.h>
-
-#import <Foundation/NSError.h>
-#import <Foundation/NSURLConnection.h>
-#import <Foundation/NSURLRequest.h>
-
-#import <Foundation/NSCalendarDate_NSURLExtras.h>
-
-NSString *FileVersionKey = @"WebHistoryFileVersion";
-NSString *DatesArrayKey = @"WebHistoryDates";
-
-#define currentFileVersion	1
-
- at implementation WebHistoryPrivate
-
-#pragma mark OBJECT FRAMEWORK
-
-+ (void)initialize
-{
-    [[NSUserDefaults standardUserDefaults] registerDefaults:
-        [NSDictionary dictionaryWithObjectsAndKeys:
-            @"1000", @"WebKitHistoryItemLimit",
-            @"7", @"WebKitHistoryAgeInDaysLimit",
-            nil]];    
-}
-
-- (id)init
-{
-    if (![super init]) {
-        return nil;
-    }
-    
-    _entriesByURL = [[NSMutableDictionary alloc] init];
-    _datesWithEntries = [[NSMutableArray alloc] init];
-    _entriesByDate = [[NSMutableArray alloc] init];
-
-    return self;
-}
-
-- (void)dealloc
-{
-    [_entriesByURL release];
-    [_datesWithEntries release];
-    [_entriesByDate release];
-    
-    [super dealloc];
-}
-
-#pragma mark MODIFYING CONTENTS
-
-// Returns whether the day is already in the list of days,
-// and fills in *index with the found or proposed index.
-- (BOOL)findIndex: (int *)index forDay: (NSCalendarDate *)date
-{
-    int count;
-
-    ASSERT_ARG(index, index != nil);
-
-    //FIXME: just does linear search through days; inefficient if many days
-    count = [_datesWithEntries count];
-    for (*index = 0; *index < count; ++*index) {
-        NSComparisonResult result = [date _web_compareDay: [_datesWithEntries objectAtIndex: *index]];
-        if (result == NSOrderedSame) {
-            return YES;
-        }
-        if (result == NSOrderedDescending) {
-            return NO;
-        }
-    }
-
-    return NO;
-}
-
-- (void)insertItem: (WebHistoryItem *)entry atDateIndex: (int)dateIndex
-{
-    int index, count;
-    NSMutableArray *entriesForDate;
-    NSCalendarDate *entryDate;
-
-    ASSERT_ARG(entry, entry != nil);
-    ASSERT_ARG(dateIndex, dateIndex >= 0 && (uint)dateIndex < [_entriesByDate count]);
-
-    //FIXME: just does linear search through entries; inefficient if many entries for this date
-    entryDate = [entry _lastVisitedDate];
-    entriesForDate = [_entriesByDate objectAtIndex: dateIndex];
-    count = [entriesForDate count];
-    // optimized for inserting oldest to youngest
-    for (index = 0; index < count; ++index) {
-        if ([entryDate compare: [[entriesForDate objectAtIndex: index] _lastVisitedDate]] != NSOrderedAscending) {
-            break;
-        }
-    }
-
-    [entriesForDate insertObject: entry atIndex: index];
-}
-
-- (BOOL)removeItemForURLString: (NSString *)URLString
-{
-    NSMutableArray *entriesForDate;
-    WebHistoryItem *entry;
-    int dateIndex;
-    BOOL foundDate;
-
-    entry = [_entriesByURL objectForKey: URLString];
-    if (entry == nil) {
-        return NO;
-    }
-
-    [_entriesByURL removeObjectForKey: URLString];
-
-    foundDate = [self findIndex: &dateIndex forDay: [entry _lastVisitedDate]];
-
-    ASSERT(foundDate);
-    
-    entriesForDate = [_entriesByDate objectAtIndex: dateIndex];
-    [entriesForDate removeObjectIdenticalTo: entry];
-
-    // remove this date entirely if there are no other entries on it
-    if ([entriesForDate count] == 0) {
-        [_entriesByDate removeObjectAtIndex: dateIndex];
-        [_datesWithEntries removeObjectAtIndex: dateIndex];
-    }
-
-    return YES;
-}
-
-
-- (void)addItem: (WebHistoryItem *)entry
-{
-    int dateIndex;
-    NSString *URLString;
-
-    ASSERT_ARG(entry, entry);
-    ASSERT_ARG(entry, [entry lastVisitedTimeInterval] != 0);
-
-    URLString = [entry URLString];
-
-    // If we already have an item with this URL, we need to merge info that drives the
-    // URL autocomplete heuristics from that item into the new one.
-    WebHistoryItem *oldEntry = [_entriesByURL objectForKey: URLString];
-    if (oldEntry) {
-        [entry _mergeAutoCompleteHints:oldEntry];
-    }
-
-    [self removeItemForURLString: URLString];
-
-    if ([self findIndex: &dateIndex forDay: [entry _lastVisitedDate]]) {
-        // other entries already exist for this date
-        [self insertItem: entry atDateIndex: dateIndex];
-    } else {
-        // no other entries exist for this date
-        [_datesWithEntries insertObject: [entry _lastVisitedDate] atIndex: dateIndex];
-        [_entriesByDate insertObject: [NSMutableArray arrayWithObject:entry] atIndex: dateIndex];
-    }
-
-    [_entriesByURL setObject: entry forKey: URLString];
-}
-
-- (BOOL)removeItem: (WebHistoryItem *)entry
-{
-    WebHistoryItem *matchingEntry;
-    NSString *URLString;
-
-    URLString = [entry URLString];
-
-    // If this exact object isn't stored, then make no change.
-    // FIXME: Is this the right behavior if this entry isn't present, but another entry for the same URL is?
-    // Maybe need to change the API to make something like removeEntryForURLString public instead.
-    matchingEntry = [_entriesByURL objectForKey: URLString];
-    if (matchingEntry != entry) {
-        return NO;
-    }
-
-    [self removeItemForURLString: URLString];
-
-    return YES;
-}
-
-- (BOOL)removeItems: (NSArray *)entries
-{
-    int index, count;
-
-    count = [entries count];
-    if (count == 0) {
-        return NO;
-    }
-
-    for (index = 0; index < count; ++index) {
-        [self removeItem:[entries objectAtIndex:index]];
-    }
-    
-    return YES;
-}
-
-- (BOOL)removeAllItems
-{
-    if ([_entriesByURL count] == 0) {
-        return NO;
-    }
-
-    [_entriesByDate removeAllObjects];
-    [_datesWithEntries removeAllObjects];
-    [_entriesByURL removeAllObjects];
-
-    return YES;
-}
-
-- (void)addItems:(NSArray *)newEntries
-{
-    NSEnumerator *enumerator;
-    WebHistoryItem *entry;
-
-    // There is no guarantee that the incoming entries are in any particular
-    // order, but if this is called with a set of entries that were created by
-    // iterating through the results of orderedLastVisitedDays and orderedItemsLastVisitedOnDayy
-    // then they will be ordered chronologically from newest to oldest. We can make adding them
-    // faster (fewer compares) by inserting them from oldest to newest.
-    enumerator = [newEntries reverseObjectEnumerator];
-    while ((entry = [enumerator nextObject]) != nil) {
-        [self addItem:entry];
-    }
-}
-
-#pragma mark DATE-BASED RETRIEVAL
-
-- (NSArray *)orderedLastVisitedDays
-{
-    return _datesWithEntries;
-}
-
-- (NSArray *)orderedItemsLastVisitedOnDay: (NSCalendarDate *)date
-{
-    int index;
-
-    if ([self findIndex: &index forDay: date]) {
-        return [_entriesByDate objectAtIndex: index];
-    }
-
-    return nil;
-}
-
-#pragma mark URL MATCHING
-
-- (WebHistoryItem *)itemForURLString:(NSString *)URLString
-{
-    return [_entriesByURL objectForKey: URLString];
-}
-
-- (BOOL)containsItemForURLString: (NSString *)URLString
-{
-    return [self itemForURLString:URLString] != nil;
-}
-
-- (BOOL)containsURL: (NSURL *)URL
-{
-    return [self itemForURLString:[URL _web_originalDataAsString]] != nil;
-}
-
-- (WebHistoryItem *)itemForURL:(NSURL *)URL
-{
-    return [self itemForURLString:[URL _web_originalDataAsString]];
-}	
-
-#pragma mark ARCHIVING/UNARCHIVING
-
-// Return a date that marks the age limit for history entries saved to or
-// loaded from disk. Any entry on this day or older should be rejected,
-// as tested with -[NSCalendarDate compareDay:]
-- (NSCalendarDate *)_ageLimitDate
-{
-    int ageInDaysLimit;
-
-    ageInDaysLimit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryAgeInDaysLimit"];
-    return [[NSCalendarDate calendarDate] dateByAddingYears:0 months:0 days:-ageInDaysLimit
-                                                      hours:0 minutes:0 seconds:0];
-}
-
-// Return a flat array of WebHistoryItems. Leaves out entries older than the age limit.
-// Stops filling array when item count limit is reached, even if there are currently
-// more entries than that.
-- (NSArray *)arrayRepresentation
-{
-    int dateCount, dateIndex;
-    int limit;
-    int totalSoFar;
-    NSMutableArray *arrayRep;
-    NSCalendarDate *ageLimitDate;
-
-    arrayRep = [NSMutableArray array];
-
-    limit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryItemLimit"];
-    ageLimitDate = [self _ageLimitDate];
-    totalSoFar = 0;
-    
-    dateCount = [_entriesByDate count];
-    for (dateIndex = 0; dateIndex < dateCount; ++dateIndex) {
-        int entryCount, entryIndex;
-        NSArray *entries;
-
-        // skip remaining days if they are older than the age limit
-        if ([[_datesWithEntries objectAtIndex:dateIndex] _web_compareDay:ageLimitDate] != NSOrderedDescending) {
-            break;
-        }
-
-        entries = [_entriesByDate objectAtIndex:dateIndex];
-        entryCount = [entries count];
-        for (entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
-            if (totalSoFar++ >= limit) {
-                break;
-            }
-            [arrayRep addObject: [[entries objectAtIndex:entryIndex] dictionaryRepresentation]];
-        }
-    }
-
-    return arrayRep;
-}
-
-- (BOOL)_loadHistoryGuts: (int *)numberOfItemsLoaded URL:(NSURL *)URL error:(NSError **)error
-{
-    *numberOfItemsLoaded = 0;
-
-    NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:error];
-    id propertyList = nil;
-    if (data && [data length] > 0) {
-        propertyList = [NSPropertyListSerialization propertyListFromData:data
-                                                        mutabilityOption:NSPropertyListImmutable
-                                                                  format:nil
-                                                        errorDescription:nil];
-    }
-
-    // propertyList might be an old-style NSArray or a more modern NSDictionary.
-    // If it's an NSArray, convert it to new format before further processing.
-    NSDictionary *fileAsDictionary = nil;
-    if ([propertyList isKindOfClass:[NSDictionary class]]) {
-        fileAsDictionary = propertyList;
-    } else if ([propertyList isKindOfClass:[NSArray class]]) {
-        // Convert old-style array into new-style dictionary
-        fileAsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
-            propertyList, DatesArrayKey,
-            [NSNumber numberWithInt:1], FileVersionKey,
-            nil];
-    } else {
-        if ([URL isFileURL] && [[NSFileManager defaultManager] fileExistsAtPath: [URL path]]) {
-            ERROR("unable to read history from file %@; perhaps contents are corrupted", [URL path]);
-        }
-        return NO;
-    }
-
-    NSNumber *fileVersionObject = [fileAsDictionary objectForKey:FileVersionKey];
-    int fileVersion;
-    // we don't trust data read from disk, so double-check
-    if (fileVersionObject != nil && [fileVersionObject isKindOfClass:[NSNumber class]]) {
-        fileVersion = [fileVersionObject intValue];
-    } else {
-        ERROR("history file version can't be determined, therefore not loading");
-        return NO;
-    }
-    if (fileVersion > currentFileVersion) {
-        ERROR("history file version is %d, newer than newest known version %d, therefore not loading", fileVersion, currentFileVersion);
-        return NO;
-    }    
-
-    NSArray *array = [fileAsDictionary objectForKey:DatesArrayKey];
-        
-    int limit = [[NSUserDefaults standardUserDefaults] integerForKey: @"WebKitHistoryItemLimit"];
-    NSCalendarDate *ageLimitDate = [self _ageLimitDate];
-    int index = 0;
-    // reverse dates so you're loading the oldest first, to minimize the number of comparisons
-    NSEnumerator *enumerator = [array reverseObjectEnumerator];
-    BOOL ageLimitPassed = NO;
-
-    NSDictionary *itemAsDictionary;
-    while ((itemAsDictionary = [enumerator nextObject]) != nil) {
-        WebHistoryItem *entry;
-
-        entry = [[[WebHistoryItem alloc] initFromDictionaryRepresentation:itemAsDictionary] autorelease];
-
-        if ([entry URLString] == nil) {
-            // entry without URL is useless; data on disk must have been bad; ignore
-            continue;
-        }
-
-        // test against date limit
-        if (!ageLimitPassed) {
-            if ([[entry _lastVisitedDate] _web_compareDay:ageLimitDate] != NSOrderedDescending) {
-                continue;
-            } else {
-                ageLimitPassed = YES;
-            }
-        }
-        
-        [self addItem: entry];
-        if (++index >= limit) {
-            break;
-        }
-    }
-
-    *numberOfItemsLoaded = MIN(index, limit);
-    return YES;    
-}
-
-- (BOOL)loadFromURL:(NSURL *)URL error:(NSError **)error
-{
-    int numberOfItems;
-    double start, duration;
-    BOOL result;
-
-    start = CFAbsoluteTimeGetCurrent();
-    result = [self _loadHistoryGuts: &numberOfItems URL:URL error:error];
-
-    if (result) {
-        duration = CFAbsoluteTimeGetCurrent() - start;
-        LOG(Timing, "loading %d history entries from %@ took %f seconds",
-            numberOfItems, URL, duration);
-    }
-
-    return result;
-}
-
-- (BOOL)_saveHistoryGuts: (int *)numberOfItemsSaved URL:(NSURL *)URL error:(NSError **)error
-{
-    *numberOfItemsSaved = 0;
-
-    // FIXME:  Correctly report error when new API is ready.
-    if (error)
-        *error = nil;
-
-    NSArray *array = [self arrayRepresentation];
-    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
-        array, DatesArrayKey,
-        [NSNumber numberWithInt:currentFileVersion], FileVersionKey,
-        nil];
-    if (![dictionary writeToURL:URL atomically:YES]) {
-        ERROR("attempt to save %@ to %@ failed", dictionary, URL);
-        return NO;
-    }
-    
-    *numberOfItemsSaved = [array count];
-    return YES;
-}
-
-- (BOOL)saveToURL:(NSURL *)URL error:(NSError **)error
-{
-    int numberOfItems;
-    double start, duration;
-    BOOL result;
-
-    start = CFAbsoluteTimeGetCurrent();
-    result = [self _saveHistoryGuts: &numberOfItems URL:URL error:error];
-
-    if (result) {
-        duration = CFAbsoluteTimeGetCurrent() - start;
-        LOG(Timing, "saving %d history entries to %@ took %f seconds",
-            numberOfItems, URL, duration);
-    }
-
-    return result;
-}
-
- at end
diff --git a/WebKit/Misc.subproj/WebIconDatabasePrivate.h b/WebKit/Misc.subproj/WebIconDatabasePrivate.h
index 90525d9..7b5e368 100644
--- a/WebKit/Misc.subproj/WebIconDatabasePrivate.h
+++ b/WebKit/Misc.subproj/WebIconDatabasePrivate.h
@@ -8,6 +8,7 @@
  */
 
 #import <Cocoa/Cocoa.h>
+#import <WebKit/WebIconDatabase.h>
 
 @class WebFileDatabase;
 
diff --git a/WebKit/WebKit.pbproj/project.pbxproj b/WebKit/WebKit.pbproj/project.pbxproj
index b653f0f..35713be 100644
--- a/WebKit/WebKit.pbproj/project.pbxproj
+++ b/WebKit/WebKit.pbproj/project.pbxproj
@@ -344,9 +344,7 @@
 				F57D1956034E734901A80180,
 				F57D195A034E734901A80180,
 				394460A8020F50ED0ECA1767,
-				F520FB1C0221DEFD01C1A525,
 				394460A9020F50ED0ECA1767,
-				F5B92B850223191D01C1A525,
 				F5E0A77102B8FEE401C1A525,
 				F59EAE420253C8DE018635CA,
 				394460A7020F50ED0ECA1767,
@@ -395,16 +393,13 @@
 				933D659C03413FF2008635CE,
 				6523FAD2032DA06B005EFCFF,
 				394460A2020F50ED0ECA1767,
-				394460A3020F50ED0ECA1767,
 				F57FB8C7034E180101A80180,
 				5152FAE2033FC50400CA2ACD,
 				5152FAE4033FC50400CA2ACD,
 				394460A1020F50ED0ECA1767,
 				F5143A380221DCCE01A80181,
-				9CF0E24C021361B10ECA16EA,
 				35081D9D02B6D4D80ACA2ACA,
 				35081D9F02B6D4D80ACA2ACA,
-				35081DA102B6D4D80ACA2ACA,
 				35081DA302B6D4D80ACA2ACA,
 				35081DA502B6D4D80ACA2ACA,
 				F5D538ED02441FDD01A80181,
@@ -423,9 +418,7 @@
 				700BC50E04144DA100A80182,
 				70BC9ED704144F3200A80182,
 				51A8B53104282B5900CA2D3A,
-				51A8B53504282BD200CA2D3A,
 				51A8B57C042834F700CA2D3A,
-				51A8B5800428353A00CA2D3A,
 				51443F9E0429392B00CA2D3A,
 				70ECD6CF043B727400A80181,
 				515E27D20458CA4B00CA2D3A,
@@ -437,6 +430,7 @@
 				BE07CEB0047538F000CA289C,
 				BE07CEB2047538F000CA289C,
 				BE6DC39C04C62C4E004D0EF6,
+				65DA2609052CC18700A97B31,
 			);
 			isa = PBXSourcesBuildPhase;
 			runOnlyForDeploymentPostprocessing = 0;
@@ -589,13 +583,12 @@
 			children = (
 				3944607D020F50ED0ECA1767,
 				3944607E020F50ED0ECA1767,
+				65DA2608052CC18700A97B31,
 				F520FB190221DEFD01C1A525,
-				F520FB1A0221DEFD01C1A525,
 				3944607F020F50ED0ECA1767,
 				39446080020F50ED0ECA1767,
 				516F296F03A6C45A00CA2D3A,
 				F5B92B820223191D01C1A525,
-				F5B92B830223191D01C1A525,
 				F5E0A76E02B8FEE401C1A525,
 				F5E0A76F02B8FEE401C1A525,
 			);
@@ -710,14 +703,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		35081D9702B6D4D80ACA2ACA = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			path = WebHTMLViewPrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		35081D9802B6D4D80ACA2ACA = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 4;
@@ -789,12 +774,6 @@
 				);
 			};
 		};
-		35081DA102B6D4D80ACA2ACA = {
-			fileRef = 35081D9702B6D4D80ACA2ACA;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		35081DA202B6D4D80ACA2ACA = {
 			fileRef = 35081D9802B6D4D80ACA2ACA;
 			isa = PBXBuildFile;
@@ -977,14 +956,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		39446073020F50ED0ECA1767 = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			path = WebDataSourcePrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		39446074020F50ED0ECA1767 = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 4;
@@ -1119,12 +1090,6 @@
 			settings = {
 			};
 		};
-		394460A3020F50ED0ECA1767 = {
-			fileRef = 39446073020F50ED0ECA1767;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		394460A7020F50ED0ECA1767 = {
 			fileRef = 3944607B020F50ED0ECA1767;
 			isa = PBXBuildFile;
@@ -1450,26 +1415,12 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		51A8B53304282BD200CA2D3A = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			path = WebFrameViewPrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		51A8B53404282BD200CA2D3A = {
 			fileRef = 51A8B53204282BD200CA2D3A;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
-		51A8B53504282BD200CA2D3A = {
-			fileRef = 51A8B53304282BD200CA2D3A;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		51A8B579042834F700CA2D3A = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 30;
@@ -1509,14 +1460,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		51A8B57E0428353A00CA2D3A = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			path = WebViewPrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		51A8B57F0428353A00CA2D3A = {
 			fileRef = 51A8B57D0428353A00CA2D3A;
 			isa = PBXBuildFile;
@@ -1526,12 +1469,6 @@
 				);
 			};
 		};
-		51A8B5800428353A00CA2D3A = {
-			fileRef = 51A8B57E0428353A00CA2D3A;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		51F6866C0366057300CA2D3A = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 30;
@@ -1786,6 +1723,20 @@
 			shellPath = /bin/sh;
 			shellScript = "ln -sf Versions/Current/Frameworks ${SYMROOT}/WebKit.framework/Frameworks; ln -sf Versions/Current/Frameworks ${DSTROOT}/System/Library/Frameworks/WebKit.framework/Frameworks; echo -n \"\"";
 		};
+		65DA2608052CC18700A97B31 = {
+			expectedFileType = sourcecode.c.objc;
+			fileEncoding = 30;
+			isa = PBXFileReference;
+			path = WebHistory.m;
+			refType = 4;
+			sourceTree = "<group>";
+		};
+		65DA2609052CC18700A97B31 = {
+			fileRef = 65DA2608052CC18700A97B31;
+			isa = PBXBuildFile;
+			settings = {
+			};
+		};
 //650
 //651
 //652
@@ -2504,7 +2455,6 @@
 				39446070020F50ED0ECA1767,
 				39446071020F50ED0ECA1767,
 				39446072020F50ED0ECA1767,
-				39446073020F50ED0ECA1767,
 				5152FADD033FC50400CA2ACD,
 				5152FADE033FC50400CA2ACD,
 				70BC9ED804144FC500A80182,
@@ -2526,11 +2476,9 @@
 				F5143A370221DCCE01A80181,
 				5152FAE5033FC52200CA2ACD,
 				9CF0E249021361B00ECA16EA,
-				9CF0E24A021361B00ECA16EA,
 				51A8B52E04282B5900CA2D3A,
 				51A8B52F04282B5900CA2D3A,
 				51A8B53204282BD200CA2D3A,
-				51A8B53304282BD200CA2D3A,
 				F5D538E802441F2601A80181,
 				F5D538EC02441FDD01A80181,
 				51443F9A0429392B00CA2D3A,
@@ -2544,7 +2492,6 @@
 				51A8B579042834F700CA2D3A,
 				51A8B57A042834F700CA2D3A,
 				51A8B57D0428353A00CA2D3A,
-				51A8B57E0428353A00CA2D3A,
 			);
 			isa = PBXGroup;
 			name = WebView;
@@ -2633,14 +2580,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		9CF0E24A021361B00ECA16EA = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 4;
-			isa = PBXFileReference;
-			path = WebFramePrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		9CF0E24B021361B10ECA16EA = {
 			fileRef = 9CF0E249021361B00ECA16EA;
 			isa = PBXBuildFile;
@@ -2650,12 +2589,6 @@
 				);
 			};
 		};
-		9CF0E24C021361B10ECA16EA = {
-			fileRef = 9CF0E24A021361B00ECA16EA;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 //9C0
 //9C1
 //9C2
@@ -3003,14 +2936,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		F520FB1A0221DEFD01C1A525 = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			path = WebHistory.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		F520FB1B0221DEFD01C1A525 = {
 			fileRef = F520FB190221DEFD01C1A525;
 			isa = PBXBuildFile;
@@ -3020,12 +2945,6 @@
 				);
 			};
 		};
-		F520FB1C0221DEFD01C1A525 = {
-			fileRef = F520FB1A0221DEFD01C1A525;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		F528E3E9031E91AD01CA2ACA = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 4;
@@ -3082,7 +3001,6 @@
 				35081D9402B6D4D80ACA2ACA,
 				35081D9502B6D4D80ACA2ACA,
 				35081D9602B6D4D80ACA2ACA,
-				35081D9702B6D4D80ACA2ACA,
 			);
 			isa = PBXGroup;
 			name = HTML;
@@ -3703,14 +3621,6 @@
 			refType = 4;
 			sourceTree = "<group>";
 		};
-		F5B92B830223191D01C1A525 = {
-			expectedFileType = sourcecode.c.objc;
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			path = WebHistoryPrivate.m;
-			refType = 4;
-			sourceTree = "<group>";
-		};
 		F5B92B840223191D01C1A525 = {
 			fileRef = F5B92B820223191D01C1A525;
 			isa = PBXBuildFile;
@@ -3720,12 +3630,6 @@
 				);
 			};
 		};
-		F5B92B850223191D01C1A525 = {
-			fileRef = F5B92B830223191D01C1A525;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		F5C283730284676D018635CA = {
 			expectedFileType = sourcecode.c.h;
 			fileEncoding = 4;
diff --git a/WebKit/WebView.subproj/WebDataSource.m b/WebKit/WebView.subproj/WebDataSource.m
index 693b36f..50b5080 100644
--- a/WebKit/WebView.subproj/WebDataSource.m
+++ b/WebKit/WebView.subproj/WebDataSource.m
@@ -22,6 +22,801 @@
 #import <Foundation/NSURLResponse.h>
 #import <Foundation/NSDictionary_NSURLExtras.h>
 
+#import <WebKit/WebIconLoader.h>
+#import <WebKit/WebViewPrivate.h>
+#import <WebKit/WebFrameLoadDelegate.h>
+#import <WebKit/WebResourceLoadDelegate.h>
+#import <WebKit/WebDefaultResourceLoadDelegate.h>
+#import <WebKit/WebSubresourceClient.h>
+#import <WebKit/WebKitErrorsPrivate.h>
+#import <Foundation/NSString_NSURLExtras.h>
+#import <WebKit/WebNSURLExtras.h>
+#import <WebKit/WebFrameViewPrivate.h>
+#import <WebKit/WebHistory.h>
+#import <WebKit/WebHistoryItemPrivate.h>
+#import <WebKit/WebHTMLViewPrivate.h>
+#import <WebKit/WebTextRepresentation.h>
+#import <WebKit/WebImageRepresentation.h>
+#import <WebKit/WebImageView.h>
+#import <Foundation/NSURLResponsePrivate.h>
+#import <WebKit/WebIconDatabasePrivate.h>
+
+ at implementation WebDataSourcePrivate 
+
+- (void)dealloc
+{
+    // The WebView is only retained while loading, but this object is also
+    // retained while loading, so no need to release here
+    ASSERT(!loading);
+    
+    // FIXME: We don't know why this is needed, but without it we leak icon loaders.
+    [iconLoader stopLoading];
+
+    [resourceData release];
+    [representation release];
+    [request release];
+    [originalRequest release];
+    [originalRequestCopy release];
+    [mainClient release];
+    [subresourceClients release];
+    [pageTitle release];
+    [response release];
+    [mainDocumentError release];
+    [iconLoader setDelegate:nil];
+    [iconLoader release];
+    [iconURL release];
+    [ourBackForwardItems release];
+    [triggeringAction release];
+    [lastCheckedRequest release];
+    [responses release];
+    [webFrame release];
+
+    [super dealloc];
+}
+
+ at end
+
+ at implementation WebDataSource (WebPrivate)
+
+- (WebView *)_webView
+{
+    return _private->webView;
+}
+
+- (void)_setRepresentation: (id<WebDocumentRepresentation>)representation
+{
+    [_private->representation release];
+    _private->representation = [representation retain];
+}
+
+- (Class)_representationClass
+{
+    return [[self class] _representationClassForMIMEType:[[self response] MIMEType]];
+}
+
+- (void)_setLoading:(BOOL)loading
+{
+    ASSERT_ARG(loading, loading == NO || loading == YES);
+
+    if (_private->loading == loading) {
+        return;
+    }
+    
+    _private->loading = loading;
+    
+    if (loading) {
+        [self retain];
+        [_private->webView retain];
+    } else {
+        [_private->webView release];
+        // FIXME: It would be cleanest to set webView to nil here. Keeping a non-retained reference
+        // to the WebView is dangerous. But WebSubresourceClient actually depends on this non-retained
+        // reference when starting loads after the data source has stoppped loading.
+        [self release];
+    }
+}
+
+- (void)_updateLoading
+{
+    [self _setLoading:_private->mainClient || [_private->subresourceClients count]];
+}
+
+- (void)_setWebView: (WebView *)webView
+{
+    if (_private->loading) {
+        [webView retain];
+        [_private->webView release];
+    }
+    _private->webView = webView;
+    
+    [self _defersCallbacksChanged];
+}
+
+- (void)_setPrimaryLoadComplete: (BOOL)flag
+{
+    _private->primaryLoadComplete = flag;
+    
+    if (flag) {
+	// FIXME: We could actually load it as soon as we've parsed
+	// the HEAD section, or determined there isn't one - but
+	// there's no callback for that.
+        [self _loadIcon];
+
+        [_private->mainClient release];
+        _private->mainClient = 0; 
+        [self _updateLoading];
+    }
+}
+
+- (void)_startLoading
+{
+    [self _startLoading: nil];
+}
+
+
+// Cancels any pending loads.  A data source is conceptually only ever loading
+// one document at a time, although one document may have many related
+// resources.  stopLoading will stop all loads related to the data source.  This
+// method will also stop loads that may be loading in child frames.
+- (void)_stopLoading
+{
+    [self _recursiveStopLoading];
+}
+
+
+- (void)_startLoading: (NSDictionary *)pageCache
+{
+    ASSERT([self _isStopping] == NO);
+
+    [self _setPrimaryLoadComplete: NO];
+    
+    ASSERT([self webFrame] != nil);
+    
+    [self _clearErrors];
+    
+    // Mark the start loading time.
+    _private->loadingStartedTime = CFAbsoluteTimeGetCurrent();
+    
+    [self _setLoading:YES];
+
+    [_private->webView _progressStarted];
+    
+    [_private->webView _didStartProvisionalLoadForFrame:[self webFrame]];
+    [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
+                                     didStartProvisionalLoadForFrame:[self webFrame]];
+
+    if (pageCache){
+        _private->loadingFromPageCache = YES;
+        [self _commitIfReady: pageCache];
+    } else if (!_private->mainClient) {
+        _private->loadingFromPageCache = NO;
+        
+        id identifier;
+        id resourceLoadDelegate = [_private->webView resourceLoadDelegate];
+        if ([resourceLoadDelegate respondsToSelector:@selector(webView:identifierForInitialRequest:fromDataSource:)])
+            identifier = [resourceLoadDelegate webView:_private->webView identifierForInitialRequest:_private->originalRequest fromDataSource:self];
+        else
+            identifier = [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:_private->webView identifierForInitialRequest:_private->originalRequest fromDataSource:self];
+            
+        _private->mainClient = [[WebMainResourceClient alloc] initWithDataSource:self];
+        [_private->mainClient setIdentifier: identifier];
+        [[self webFrame] _addExtraFieldsToRequest:_private->request alwaysFromRequest: NO];
+        if (![_private->mainClient loadWithRequest:_private->request]) {
+            ERROR("could not create WebResourceHandle for URL %@ -- should be caught by policy handler level",
+                [_private->request URL]);
+            [_private->mainClient release];
+            _private->mainClient = nil;
+            [self _updateLoading];
+        }
+    }
+}
+
+- (void)_addSubresourceClient:(WebSubresourceClient *)client
+{
+    if (_private->subresourceClients == nil) {
+        _private->subresourceClients = [[NSMutableArray alloc] init];
+    }
+    if ([_private->webView defersCallbacks]) {
+        [client setDefersCallbacks:YES];
+    }
+    [_private->subresourceClients addObject:client];
+    [self _setLoading:YES];
+}
+
+- (void)_removeSubresourceClient:(WebSubresourceClient *)client
+{
+    [_private->subresourceClients removeObject:client];
+    [self _updateLoading];
+}
+
+- (BOOL)_isStopping
+{
+    return _private->stopping;
+}
+
+- (void)_stopLoadingInternal
+{
+    if (!_private->loading) {
+	return;
+    }
+
+    _private->stopping = YES;
+
+    if(_private->mainClient){
+        // Stop the main handle and let it set the cancelled error.
+        [_private->mainClient cancel];
+    }else{
+        // Main handle is already done. Set the cancelled error.
+        NSError *cancelledError = [NSError _webKitErrorWithDomain:NSURLErrorDomain
+                                                             code:NSURLErrorCancelled
+                                                              URL:[self _URL]];
+        [self _setMainDocumentError:cancelledError];
+    }
+    
+    NSArray *clients = [_private->subresourceClients copy];
+    [clients makeObjectsPerformSelector:@selector(cancel)];
+    [clients release];
+    
+    if (_private->committed) {
+	[[self _bridge] closeURL];        
+    }
+
+    [_private->iconLoader stopLoading];
+}
+
+- (void)_recursiveStopLoading
+{
+    [self retain];
+    
+    // We depend on the WebView in the webFrame method and we release it in _stopLoading,
+    // so call webFrame first so we don't send a message the released WebView (3129503).
+    [[[self webFrame] childFrames] makeObjectsPerformSelector:@selector(stopLoading)];
+    [self _stopLoadingInternal];
+    
+    [self release];
+}
+
+- (double)_loadingStartedTime
+{
+    return _private->loadingStartedTime;
+}
+
+- (void)_setTitle:(NSString *)title
+{
+    NSString *trimmed;
+    if (title == nil) {
+        trimmed = nil;
+    } else {
+        trimmed = [title _web_stringByTrimmingWhitespace];
+        if ([trimmed length] == 0)
+            trimmed = nil;
+    }
+    if (trimmed == nil) {
+        if (_private->pageTitle == nil)
+            return;
+    } else {
+        if ([_private->pageTitle isEqualToString:trimmed])
+            return;
+    }
+    
+    if (!trimmed || [trimmed length] == 0)
+        return;
+        
+    [_private->webView _willChangeValueForKey: _WebMainFrameTitleKey];
+    [_private->pageTitle release];
+    _private->pageTitle = [trimmed copy];
+    [_private->webView _didChangeValueForKey: _WebMainFrameTitleKey];
+    
+    // The title doesn't get communicated to the WebView until we are committed.
+    if (_private->committed) {
+        WebHistoryItem *entry;
+        NSURL *canonURL = [[[self _originalRequest] URL] _webkit_canonicalize];
+        entry = [[WebHistory optionalSharedHistory] itemForURL: canonURL];
+        [entry setTitle: _private->pageTitle];
+
+        // Must update the entries in the back-forward list too.
+        [_private->ourBackForwardItems makeObjectsPerformSelector:@selector(setTitle:) withObject:_private->pageTitle];
+
+        [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
+                                                         didReceiveTitle:_private->pageTitle
+                                                                forFrame:[self webFrame]];
+    }
+}
+
+- (NSString *)_title
+{
+    return _private->pageTitle;
+}
+
+- (void)_setURL:(NSURL *)URL
+{
+    NSMutableURLRequest *newRequest = [_private->request mutableCopy];
+    [_private->request release];
+    [newRequest setURL:URL];
+    _private->request = newRequest;
+}
+
+- (void)__setRequest:(NSURLRequest *)request
+{
+    if (request != _private->request){
+        [_private->request release];
+        _private->request = [request retain];
+    }
+}
+
+- (void)_setRequest:(NSURLRequest *)request
+{
+    // We should never be getting a redirect callback after the data
+    // source is committed. It would be a WebFoundation bug if it sent
+    // a redirect callback after commit.
+    ASSERT(!_private->committed);
+
+    NSURLRequest *oldRequest = _private->request;
+
+    _private->request = [request retain];
+
+    // Only send webView:didReceiveServerRedirectForProvisionalLoadForFrame: if URL changed.
+    if (![[oldRequest URL] isEqual: [request URL]]) {
+        LOG(Redirect, "Server redirect to: %@", [request URL]);
+        [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
+                      didReceiveServerRedirectForProvisionalLoadForFrame:[self webFrame]];
+    }
+        
+    [oldRequest release];
+}
+
+- (void)_setResponse:(NSURLResponse *)response
+{
+    [_private->response release];
+    _private->response = [response retain];
+}
+
+- (void)_setOverrideEncoding:(NSString *)overrideEncoding
+{
+    NSString *copy = [overrideEncoding copy];
+    [_private->overrideEncoding release];
+    _private->overrideEncoding = copy;
+}
+
+- (NSString *)_overrideEncoding
+{
+    return [[_private->overrideEncoding copy] autorelease];
+}
+
+- (void)_setIsClientRedirect:(BOOL)flag
+{
+    _private->isClientRedirect = flag;
+}
+
+- (BOOL)_isClientRedirect
+{
+    return _private->isClientRedirect;
+}
+
+- (void)_addBackForwardItem:(WebHistoryItem *)item
+{
+    if (!item) {
+        return;
+    }
+    if (!_private->ourBackForwardItems) {
+        _private->ourBackForwardItems = [[NSMutableArray alloc] initWithCapacity:1];
+    }
+    if ([_private->ourBackForwardItems indexOfObjectIdenticalTo:item] == NSNotFound) {
+        [_private->ourBackForwardItems addObject:item];
+    }
+}
+
+- (void)_addBackForwardItems:(NSArray *)items
+{
+    if (!items || [items count] == 0) {
+        return;
+    }
+    if (!_private->ourBackForwardItems) {
+        _private->ourBackForwardItems = [items mutableCopy];
+    } else {
+        [_private->ourBackForwardItems addObjectsFromArray:items];
+    }
+}
+
+- (NSArray *)_backForwardItems
+{
+    return _private->ourBackForwardItems;
+}
+
+- (void)_setMainDocumentError: (NSError *)error
+{
+    [error retain];
+    [_private->mainDocumentError release];
+    _private->mainDocumentError = error;
+
+    [[self representation] receivedError:error withDataSource:self];
+}
+
+- (void)_clearErrors
+{
+    [_private->mainDocumentError release];
+    _private->mainDocumentError = nil;
+}
+
+
+- (void)_layoutChildren
+{
+    NSArray *subFrames = [[self webFrame] childFrames];
+    if ([subFrames count]) {
+        WebFrame *subFrame;
+        unsigned int i;
+        id dview;
+        for (i = 0; i < [subFrames count]; i++){
+            subFrame = [subFrames objectAtIndex: i];
+            dview = [[subFrame frameView] documentView];
+            if ([[subFrame dataSource] _isDocumentHTML])
+                [dview _adjustFrames];
+            [dview setNeedsDisplay: YES];
+            [[subFrame dataSource] _layoutChildren];
+        }
+    }
+}
+
++ (NSMutableDictionary *)_repTypesAllowImageTypeOmission:(BOOL)allowImageTypeOmission
+{
+    static NSMutableDictionary *repTypes = nil;
+    static BOOL addedImageTypes;
+    
+    if (!repTypes) {
+        repTypes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
+            [WebHTMLRepresentation class], @"text/html",
+	    [WebHTMLRepresentation class], @"text/xml",
+	    [WebHTMLRepresentation class], @"application/xml",
+	    [WebHTMLRepresentation class], @"application/xhtml+xml",
+            [WebTextRepresentation class], @"text/",
+            [WebTextRepresentation class], @"application/x-javascript",
+            nil];
+    }
+    
+    if (!addedImageTypes && !allowImageTypeOmission) {
+        NSEnumerator *enumerator = [[WebImageView supportedImageMIMETypes] objectEnumerator];
+        NSString *mime;
+        while ((mime = [enumerator nextObject]) != nil) {
+            [repTypes setObject:[WebImageRepresentation class] forKey:mime];
+        }
+        addedImageTypes = YES;
+    }
+    
+    return repTypes;
+}
+
++ (Class)_representationClassForMIMEType:(NSString *)MIMEType
+{
+    // Getting the image types is slow, so don't do it until we have to.
+    Class c = [[self _repTypesAllowImageTypeOmission:YES] _web_objectForMIMEType:MIMEType];
+    if (c == nil) {
+        c = [[self _repTypesAllowImageTypeOmission:NO] _web_objectForMIMEType:MIMEType];
+    }
+    return c;
+}
+
+- (WebBridge *)_bridge
+{
+    ASSERT(_private->committed);
+    return [[self webFrame] _bridge];
+}
+
+- (BOOL)_isCommitted
+{
+    return _private->committed;
+}
+
+- (void)_commitIfReady: (NSDictionary *)pageCache
+{
+    if (_private->loadingFromPageCache || (_private->gotFirstByte && !_private->committed)) {
+        WebFrame *frame = [self webFrame];
+        WebFrameLoadType loadType = [frame _loadType];
+        bool reload = loadType == WebFrameLoadTypeReload
+            || loadType == WebFrameLoadTypeReloadAllowingStaleData;
+        
+        NSDictionary *headers = [_private->response isKindOfClass:[NSHTTPURLResponse class]]
+            ? [(NSHTTPURLResponse *)_private->response allHeaderFields] : nil;
+
+        [frame _closeOldDataSources];
+
+        LOG(Loading, "committed resource = %@", [[self request] URL]);
+	_private->committed = TRUE;
+        if (!pageCache)
+            [self _makeRepresentation];
+            
+        [frame _transitionToCommitted: pageCache];
+
+        NSURL *baseURL = [[self request] _webDataRequestBaseURL];        
+        NSURL *URL = nil;
+        
+        if (baseURL)
+            URL = baseURL;
+        else
+            URL = [_private->response URL];
+            
+        // WebCore will crash if given an empty URL here.
+        // FIXME: could use CFURL, when available, range API to save an allocation here
+        if (!URL || [URL _web_isEmpty])
+            URL = [NSURL URLWithString:@"about:blank"];
+
+        [[self _bridge] openURL:URL
+                         reload:reload 
+                    contentType:[_private->response MIMEType]
+                        refresh:[headers objectForKey:@"Refresh"]
+                   lastModified:(pageCache ? nil : [_private->response _lastModifiedDate])
+                      pageCache:pageCache];
+
+        [frame _opened];
+    }
+}
+
+- (void)_commitIfReady
+{
+    [self _commitIfReady: nil];
+}
+
+-(void)_makeRepresentation
+{
+    Class repClass = [self _representationClass];
+
+    // Check if the data source was already bound?
+    if (![[self representation] isKindOfClass:repClass]) {
+        id newRep = repClass != nil ? [[repClass alloc] init] : nil;
+	[self _setRepresentation:(id <WebDocumentRepresentation>)newRep];
+        [newRep release];
+    }
+
+    [_private->representation setDataSource:self];
+}
+
+-(void)_receivedData:(NSData *)data
+{
+    if (!_private->resourceData) {
+        _private->resourceData = [[NSMutableData alloc] init];
+    }
+    [_private->resourceData appendData:data];
+    
+    _private->gotFirstByte = YES;
+    [self _commitIfReady];
+
+    // parsing some of the page can result in running a script which
+    // could possibly destroy the frame and data source. So retain
+    // self temporarily.
+    [self retain];
+    [[self representation] receivedData:data withDataSource:self];
+    [[[[self webFrame] frameView] documentView] dataSourceUpdated:self];
+    [self release];
+}
+
+- (void)_finishedLoading
+{
+    _private->gotFirstByte = YES;
+    [self _commitIfReady];
+
+    [[self representation] finishedLoadingWithDataSource:self];
+}
+
+- (void)_receivedError:(NSError *)error complete:(BOOL)isComplete
+{
+    if (!_private->committed) {
+        [[[self webFrame] _bridge] didNotOpenURL:[_private->originalRequestCopy URL]];
+    }
+    [[self _webView] _mainReceivedError:error
+                           fromDataSource:self
+                                 complete:isComplete];
+}
+
+- (void)_updateIconDatabaseWithURL:(NSURL *)iconURL
+{
+    WebIconDatabase *iconDB = [WebIconDatabase sharedIconDatabase];
+
+    // Bind the URL of the original request and the final URL to the icon URL.
+    [iconDB _setIconURL:[iconURL _web_originalDataAsString] forURL:[[self _URL] _web_originalDataAsString]];
+    [iconDB _setIconURL:[iconURL _web_originalDataAsString] forURL:[[[self _originalRequest] URL] _web_originalDataAsString]];
+
+    
+    if ([self webFrame] == [_private->webView mainFrame])
+        [_private->webView _willChangeValueForKey:_WebMainFrameIconKey];
+    
+    NSImage *icon = [iconDB iconForURL:[[self _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
+    [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
+                                                      didReceiveIcon:icon
+                                                            forFrame:[self webFrame]];
+    
+    if ([self webFrame] == [_private->webView mainFrame])
+        [_private->webView _didChangeValueForKey:_WebMainFrameIconKey];
+}
+
+- (void)_iconLoaderReceivedPageIcon:(WebIconLoader *)iconLoader
+{
+    [self _updateIconDatabaseWithURL:[iconLoader URL]];
+}
+
+- (void)_loadIcon
+{
+    // Don't load an icon if 1) this is not the main frame 2) we ended in error 3) we already did 4) they aren't save by the DB.
+    if ([self webFrame] != [[self _webView] mainFrame] || _private->mainDocumentError || _private->iconLoader ||
+       ![[WebIconDatabase sharedIconDatabase] iconsAreSaved]) {
+        return;
+    }
+                
+    if(!_private->iconURL){
+        // No icon URL from the LINK tag so try the server's root.
+        // This is only really a feature of http or https, so don't try this with other protocols.
+        NSString *scheme = [[self _URL] scheme];
+        if([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]){
+            _private->iconURL = [[[NSURL _web_URLWithDataAsString:@"/favicon.ico"
+                                              relativeToURL:[self _URL]] absoluteURL] retain];
+        }
+    }
+
+    if(_private->iconURL != nil){
+        if([[WebIconDatabase sharedIconDatabase] _hasIconForIconURL:[_private->iconURL _web_originalDataAsString]]){
+            [self _updateIconDatabaseWithURL:_private->iconURL];
+        }else{
+            ASSERT(!_private->iconLoader);
+            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_private->iconURL];
+            [[self webFrame] _addExtraFieldsToRequest:request alwaysFromRequest:NO];
+            _private->iconLoader = [[WebIconLoader alloc] initWithRequest:request];
+            [request release];
+            [_private->iconLoader setDelegate:self];
+            [_private->iconLoader startLoading];
+        }
+    }
+}
+
+- (void)_setIconURL:(NSURL *)URL
+{
+    // Lower priority than typed icon, so ignore this if we already have an iconURL.
+    if (_private->iconURL == nil) {
+	[_private->iconURL release];
+	_private->iconURL = [URL retain];
+    }
+}
+
+- (void)_setIconURL:(NSURL *)URL withType:(NSString *)iconType
+{
+    // FIXME: Should check to make sure the type is one we know how to handle.
+    [_private->iconURL release];
+    _private->iconURL = [URL retain];
+}
+
+- (void)_defersCallbacksChanged
+{
+    BOOL defers = [_private->webView defersCallbacks];
+    
+    if (defers == _private->defersCallbacks) {
+        return;
+    }
+
+    _private->defersCallbacks = defers;
+    [_private->mainClient setDefersCallbacks:defers];
+
+    NSEnumerator *e = [_private->subresourceClients objectEnumerator];
+    WebSubresourceClient *client;
+    while ((client = [e nextObject])) {
+        [client setDefersCallbacks:defers];
+    }
+
+    [[[self webFrame] childFrames] makeObjectsPerformSelector:@selector(_defersCallbacksChanged)];
+}
+
+- (NSURLRequest *)_originalRequest
+{
+    return _private->originalRequestCopy;
+}
+
+- (void)_setTriggeringAction:(NSDictionary *)action
+{
+    [action retain];
+    [_private->triggeringAction release];
+    _private->triggeringAction = action;
+}
+
+- (NSDictionary *)_triggeringAction
+{
+    return [[_private->triggeringAction retain] autorelease];
+}
+
+
+- (NSURLRequest *)_lastCheckedRequest
+{
+    // It's OK not to make a copy here because we know the caller
+    // isn't going to modify this request
+    return [[_private->lastCheckedRequest retain] autorelease];
+}
+
+- (void)_setLastCheckedRequest:(NSURLRequest *)request
+{
+    NSURLRequest *oldRequest = _private->lastCheckedRequest;
+    _private->lastCheckedRequest = [request copy];
+    [oldRequest release];
+}
+
+- (void)_setJustOpenedForTargetedLink:(BOOL)justOpened
+{
+    _private->justOpenedForTargetedLink = justOpened;
+}
+
+- (BOOL)_justOpenedForTargetedLink
+{
+    return _private->justOpenedForTargetedLink;
+}
+
+- (void)_setStoredInPageCache:(BOOL)f
+{
+    _private->storedInPageCache = f;
+}
+
+- (BOOL)_storedInPageCache
+{
+    return _private->storedInPageCache;
+}
+
+- (BOOL)_loadingFromPageCache
+{
+    return _private->loadingFromPageCache;
+}
+
+- (void)_addResponse: (NSURLResponse *)r
+{
+    if (!_private->responses)
+        _private->responses = [[NSMutableArray alloc] init];
+    [_private->responses addObject: r];
+}
+
+- (NSArray *)_responses
+{
+    return _private->responses;
+}
+
+- (void)_stopLoadingWithError:(NSError *)error
+{
+    [_private->mainClient cancelWithError:error];
+}
+
+- (void)_setWebFrame:(WebFrame *)frame
+{
+    [frame retain];
+    [_private->webFrame release];
+    _private->webFrame = frame;
+}
+
+// May return nil if not initialized with a URL.
+- (NSURL *)_URL
+{
+    return [[self request] URL];
+}
+
+- (NSString *)_stringWithData:(NSData *)data
+{
+    NSString *textEncodingName = [self _overrideEncoding];
+
+    if(!textEncodingName){
+        textEncodingName = [[self response] textEncodingName];
+    }
+
+    if(textEncodingName){
+        return [WebBridge stringWithData:data textEncodingName:textEncodingName];
+    }else{
+        return [WebBridge stringWithData:data textEncoding:kCFStringEncodingISOLatin1];
+    }
+}
+
+- (NSError *)_mainDocumentError
+{
+    return _private->mainDocumentError;
+}
+
+- (BOOL)_isDocumentHTML
+{
+    NSString *MIMEType = [[self response] MIMEType];
+    return [WebView canShowMIMETypeAsHTML:MIMEType];
+}
+
+
+ at end
+
 @implementation WebDataSource
 
 -(id)initWithRequest:(NSURLRequest *)request
diff --git a/WebKit/WebView.subproj/WebDataSourcePrivate.m b/WebKit/WebView.subproj/WebDataSourcePrivate.m
deleted file mode 100644
index 4cd45f4..0000000
--- a/WebKit/WebView.subproj/WebDataSourcePrivate.m
+++ /dev/null
@@ -1,818 +0,0 @@
-/*	WebDataSourcePrivate.h
-	Copyright 2001, 2002, Apple, Inc. All rights reserved.
-*/
-
-#import <WebKit/WebDataSourcePrivate.h>
-
-#import <WebKit/WebBridge.h>
-#import <WebKit/WebDataProtocol.h>
-#import <WebKit/WebDefaultResourceLoadDelegate.h>
-#import <WebKit/WebDocument.h>
-#import <WebKit/WebException.h>
-#import <WebKit/WebFrameLoadDelegate.h>
-#import <WebKit/WebFramePrivate.h>
-#import <WebKit/WebFrameViewPrivate.h>
-#import <WebKit/WebHistory.h>
-#import <WebKit/WebHistoryItem.h>
-#import <WebKit/WebHistoryItemPrivate.h>
-#import <WebKit/WebHTMLRepresentation.h>
-#import <WebKit/WebHTMLViewPrivate.h>
-#import <WebKit/WebIconDatabase.h>
-#import <WebKit/WebIconDatabasePrivate.h>
-#import <WebKit/WebIconLoader.h>
-#import <WebKit/WebImageRepresentation.h>
-#import <WebKit/WebImageView.h>
-#import <WebKit/WebKitErrorsPrivate.h>
-#import <WebKit/WebKitLogging.h>
-#import <WebKit/WebMainResourceClient.h>
-#import <WebKit/WebNSURLExtras.h>
-#import <WebKit/WebPolicyDelegate.h>
-#import <WebKit/WebResourceLoadDelegate.h>
-#import <WebKit/WebSubresourceClient.h>
-#import <WebKit/WebTextRepresentation.h>
-#import <WebKit/WebViewPrivate.h>
-
-#import <Foundation/NSDictionary_NSURLExtras.h>
-#import <Foundation/NSError_NSURLExtras.h>
-#import <Foundation/NSString_NSURLExtras.h>
-#import <Foundation/NSURLConnection.h>
-#import <Foundation/NSURLRequest.h>
-#import <Foundation/NSURLResponse.h>
-#import <Foundation/NSURLResponsePrivate.h>
-
-
- at implementation WebDataSourcePrivate 
-
-- (void)dealloc
-{
-    // The WebView is only retained while loading, but this object is also
-    // retained while loading, so no need to release here
-    ASSERT(!loading);
-    
-    // FIXME: We don't know why this is needed, but without it we leak icon loaders.
-    [iconLoader stopLoading];
-
-    [resourceData release];
-    [representation release];
-    [request release];
-    [originalRequest release];
-    [originalRequestCopy release];
-    [mainClient release];
-    [subresourceClients release];
-    [pageTitle release];
-    [response release];
-    [mainDocumentError release];
-    [iconLoader setDelegate:nil];
-    [iconLoader release];
-    [iconURL release];
-    [ourBackForwardItems release];
-    [triggeringAction release];
-    [lastCheckedRequest release];
-    [responses release];
-    [webFrame release];
-
-    [super dealloc];
-}
-
- at end
-
- at implementation WebDataSource (WebPrivate)
-
-- (WebView *)_webView
-{
-    return _private->webView;
-}
-
-- (void)_setRepresentation: (id<WebDocumentRepresentation>)representation
-{
-    [_private->representation release];
-    _private->representation = [representation retain];
-}
-
-- (Class)_representationClass
-{
-    return [[self class] _representationClassForMIMEType:[[self response] MIMEType]];
-}
-
-- (void)_setLoading:(BOOL)loading
-{
-    ASSERT_ARG(loading, loading == NO || loading == YES);
-
-    if (_private->loading == loading) {
-        return;
-    }
-    
-    _private->loading = loading;
-    
-    if (loading) {
-        [self retain];
-        [_private->webView retain];
-    } else {
-        [_private->webView release];
-        // FIXME: It would be cleanest to set webView to nil here. Keeping a non-retained reference
-        // to the WebView is dangerous. But WebSubresourceClient actually depends on this non-retained
-        // reference when starting loads after the data source has stoppped loading.
-        [self release];
-    }
-}
-
-- (void)_updateLoading
-{
-    [self _setLoading:_private->mainClient || [_private->subresourceClients count]];
-}
-
-- (void)_setWebView: (WebView *)webView
-{
-    if (_private->loading) {
-        [webView retain];
-        [_private->webView release];
-    }
-    _private->webView = webView;
-    
-    [self _defersCallbacksChanged];
-}
-
-- (void)_setPrimaryLoadComplete: (BOOL)flag
-{
-    _private->primaryLoadComplete = flag;
-    
-    if (flag) {
-	// FIXME: We could actually load it as soon as we've parsed
-	// the HEAD section, or determined there isn't one - but
-	// there's no callback for that.
-        [self _loadIcon];
-
-        [_private->mainClient release];
-        _private->mainClient = 0; 
-        [self _updateLoading];
-    }
-}
-
-- (void)_startLoading
-{
-    [self _startLoading: nil];
-}
-
-
-// Cancels any pending loads.  A data source is conceptually only ever loading
-// one document at a time, although one document may have many related
-// resources.  stopLoading will stop all loads related to the data source.  This
-// method will also stop loads that may be loading in child frames.
-- (void)_stopLoading
-{
-    [self _recursiveStopLoading];
-}
-
-
-- (void)_startLoading: (NSDictionary *)pageCache
-{
-    ASSERT([self _isStopping] == NO);
-
-    [self _setPrimaryLoadComplete: NO];
-    
-    ASSERT([self webFrame] != nil);
-    
-    [self _clearErrors];
-    
-    // Mark the start loading time.
-    _private->loadingStartedTime = CFAbsoluteTimeGetCurrent();
-    
-    [self _setLoading:YES];
-
-    [_private->webView _progressStarted];
-    
-    [_private->webView _didStartProvisionalLoadForFrame:[self webFrame]];
-    [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
-                                     didStartProvisionalLoadForFrame:[self webFrame]];
-
-    if (pageCache){
-        _private->loadingFromPageCache = YES;
-        [self _commitIfReady: pageCache];
-    } else if (!_private->mainClient) {
-        _private->loadingFromPageCache = NO;
-        
-        id identifier;
-        id resourceLoadDelegate = [_private->webView resourceLoadDelegate];
-        if ([resourceLoadDelegate respondsToSelector:@selector(webView:identifierForInitialRequest:fromDataSource:)])
-            identifier = [resourceLoadDelegate webView:_private->webView identifierForInitialRequest:_private->originalRequest fromDataSource:self];
-        else
-            identifier = [[WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] webView:_private->webView identifierForInitialRequest:_private->originalRequest fromDataSource:self];
-            
-        _private->mainClient = [[WebMainResourceClient alloc] initWithDataSource:self];
-        [_private->mainClient setIdentifier: identifier];
-        [[self webFrame] _addExtraFieldsToRequest:_private->request alwaysFromRequest: NO];
-        if (![_private->mainClient loadWithRequest:_private->request]) {
-            ERROR("could not create WebResourceHandle for URL %@ -- should be caught by policy handler level",
-                [_private->request URL]);
-            [_private->mainClient release];
-            _private->mainClient = nil;
-            [self _updateLoading];
-        }
-    }
-}
-
-- (void)_addSubresourceClient:(WebSubresourceClient *)client
-{
-    if (_private->subresourceClients == nil) {
-        _private->subresourceClients = [[NSMutableArray alloc] init];
-    }
-    if ([_private->webView defersCallbacks]) {
-        [client setDefersCallbacks:YES];
-    }
-    [_private->subresourceClients addObject:client];
-    [self _setLoading:YES];
-}
-
-- (void)_removeSubresourceClient:(WebSubresourceClient *)client
-{
-    [_private->subresourceClients removeObject:client];
-    [self _updateLoading];
-}
-
-- (BOOL)_isStopping
-{
-    return _private->stopping;
-}
-
-- (void)_stopLoadingInternal
-{
-    if (!_private->loading) {
-	return;
-    }
-
-    _private->stopping = YES;
-
-    if(_private->mainClient){
-        // Stop the main handle and let it set the cancelled error.
-        [_private->mainClient cancel];
-    }else{
-        // Main handle is already done. Set the cancelled error.
-        NSError *cancelledError = [NSError _webKitErrorWithDomain:NSURLErrorDomain
-                                                             code:NSURLErrorCancelled
-                                                              URL:[self _URL]];
-        [self _setMainDocumentError:cancelledError];
-    }
-    
-    NSArray *clients = [_private->subresourceClients copy];
-    [clients makeObjectsPerformSelector:@selector(cancel)];
-    [clients release];
-    
-    if (_private->committed) {
-	[[self _bridge] closeURL];        
-    }
-
-    [_private->iconLoader stopLoading];
-}
-
-- (void)_recursiveStopLoading
-{
-    [self retain];
-    
-    // We depend on the WebView in the webFrame method and we release it in _stopLoading,
-    // so call webFrame first so we don't send a message the released WebView (3129503).
-    [[[self webFrame] childFrames] makeObjectsPerformSelector:@selector(stopLoading)];
-    [self _stopLoadingInternal];
-    
-    [self release];
-}
-
-- (double)_loadingStartedTime
-{
-    return _private->loadingStartedTime;
-}
-
-- (void)_setTitle:(NSString *)title
-{
-    NSString *trimmed;
-    if (title == nil) {
-        trimmed = nil;
-    } else {
-        trimmed = [title _web_stringByTrimmingWhitespace];
-        if ([trimmed length] == 0)
-            trimmed = nil;
-    }
-    if (trimmed == nil) {
-        if (_private->pageTitle == nil)
-            return;
-    } else {
-        if ([_private->pageTitle isEqualToString:trimmed])
-            return;
-    }
-    
-    if (!trimmed || [trimmed length] == 0)
-        return;
-        
-    [_private->webView _willChangeValueForKey: _WebMainFrameTitleKey];
-    [_private->pageTitle release];
-    _private->pageTitle = [trimmed copy];
-    [_private->webView _didChangeValueForKey: _WebMainFrameTitleKey];
-    
-    // The title doesn't get communicated to the WebView until we are committed.
-    if (_private->committed) {
-        WebHistoryItem *entry;
-        NSURL *canonURL = [[[self _originalRequest] URL] _webkit_canonicalize];
-        entry = [[WebHistory optionalSharedHistory] itemForURL: canonURL];
-        [entry setTitle: _private->pageTitle];
-
-        // Must update the entries in the back-forward list too.
-        [_private->ourBackForwardItems makeObjectsPerformSelector:@selector(setTitle:) withObject:_private->pageTitle];
-
-        [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
-                                                         didReceiveTitle:_private->pageTitle
-                                                                forFrame:[self webFrame]];
-    }
-}
-
-- (NSString *)_title
-{
-    return _private->pageTitle;
-}
-
-- (void)_setURL:(NSURL *)URL
-{
-    NSMutableURLRequest *newRequest = [_private->request mutableCopy];
-    [_private->request release];
-    [newRequest setURL:URL];
-    _private->request = newRequest;
-}
-
-- (void)__setRequest:(NSURLRequest *)request
-{
-    if (request != _private->request){
-        [_private->request release];
-        _private->request = [request retain];
-    }
-}
-
-- (void)_setRequest:(NSURLRequest *)request
-{
-    // We should never be getting a redirect callback after the data
-    // source is committed. It would be a WebFoundation bug if it sent
-    // a redirect callback after commit.
-    ASSERT(!_private->committed);
-
-    NSURLRequest *oldRequest = _private->request;
-
-    _private->request = [request retain];
-
-    // Only send webView:didReceiveServerRedirectForProvisionalLoadForFrame: if URL changed.
-    if (![[oldRequest URL] isEqual: [request URL]]) {
-        LOG(Redirect, "Server redirect to: %@", [request URL]);
-        [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
-                      didReceiveServerRedirectForProvisionalLoadForFrame:[self webFrame]];
-    }
-        
-    [oldRequest release];
-}
-
-- (void)_setResponse:(NSURLResponse *)response
-{
-    [_private->response release];
-    _private->response = [response retain];
-}
-
-- (void)_setOverrideEncoding:(NSString *)overrideEncoding
-{
-    NSString *copy = [overrideEncoding copy];
-    [_private->overrideEncoding release];
-    _private->overrideEncoding = copy;
-}
-
-- (NSString *)_overrideEncoding
-{
-    return [[_private->overrideEncoding copy] autorelease];
-}
-
-- (void)_setIsClientRedirect:(BOOL)flag
-{
-    _private->isClientRedirect = flag;
-}
-
-- (BOOL)_isClientRedirect
-{
-    return _private->isClientRedirect;
-}
-
-- (void)_addBackForwardItem:(WebHistoryItem *)item
-{
-    if (!item) {
-        return;
-    }
-    if (!_private->ourBackForwardItems) {
-        _private->ourBackForwardItems = [[NSMutableArray alloc] initWithCapacity:1];
-    }
-    if ([_private->ourBackForwardItems indexOfObjectIdenticalTo:item] == NSNotFound) {
-        [_private->ourBackForwardItems addObject:item];
-    }
-}
-
-- (void)_addBackForwardItems:(NSArray *)items
-{
-    if (!items || [items count] == 0) {
-        return;
-    }
-    if (!_private->ourBackForwardItems) {
-        _private->ourBackForwardItems = [items mutableCopy];
-    } else {
-        [_private->ourBackForwardItems addObjectsFromArray:items];
-    }
-}
-
-- (NSArray *)_backForwardItems
-{
-    return _private->ourBackForwardItems;
-}
-
-- (void)_setMainDocumentError: (NSError *)error
-{
-    [error retain];
-    [_private->mainDocumentError release];
-    _private->mainDocumentError = error;
-
-    [[self representation] receivedError:error withDataSource:self];
-}
-
-- (void)_clearErrors
-{
-    [_private->mainDocumentError release];
-    _private->mainDocumentError = nil;
-}
-
-
-- (void)_layoutChildren
-{
-    NSArray *subFrames = [[self webFrame] childFrames];
-    if ([subFrames count]) {
-        WebFrame *subFrame;
-        unsigned int i;
-        id dview;
-        for (i = 0; i < [subFrames count]; i++){
-            subFrame = [subFrames objectAtIndex: i];
-            dview = [[subFrame frameView] documentView];
-            if ([[subFrame dataSource] _isDocumentHTML])
-                [dview _adjustFrames];
-            [dview setNeedsDisplay: YES];
-            [[subFrame dataSource] _layoutChildren];
-        }
-    }
-}
-
-+ (NSMutableDictionary *)_repTypesAllowImageTypeOmission:(BOOL)allowImageTypeOmission
-{
-    static NSMutableDictionary *repTypes = nil;
-    static BOOL addedImageTypes;
-    
-    if (!repTypes) {
-        repTypes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
-            [WebHTMLRepresentation class], @"text/html",
-	    [WebHTMLRepresentation class], @"text/xml",
-	    [WebHTMLRepresentation class], @"application/xml",
-	    [WebHTMLRepresentation class], @"application/xhtml+xml",
-            [WebTextRepresentation class], @"text/",
-            [WebTextRepresentation class], @"application/x-javascript",
-            nil];
-    }
-    
-    if (!addedImageTypes && !allowImageTypeOmission) {
-        NSEnumerator *enumerator = [[WebImageView supportedImageMIMETypes] objectEnumerator];
-        NSString *mime;
-        while ((mime = [enumerator nextObject]) != nil) {
-            [repTypes setObject:[WebImageRepresentation class] forKey:mime];
-        }
-        addedImageTypes = YES;
-    }
-    
-    return repTypes;
-}
-
-+ (Class)_representationClassForMIMEType:(NSString *)MIMEType
-{
-    // Getting the image types is slow, so don't do it until we have to.
-    Class c = [[self _repTypesAllowImageTypeOmission:YES] _web_objectForMIMEType:MIMEType];
-    if (c == nil) {
-        c = [[self _repTypesAllowImageTypeOmission:NO] _web_objectForMIMEType:MIMEType];
-    }
-    return c;
-}
-
-- (WebBridge *)_bridge
-{
-    ASSERT(_private->committed);
-    return [[self webFrame] _bridge];
-}
-
-- (BOOL)_isCommitted
-{
-    return _private->committed;
-}
-
-- (void)_commitIfReady: (NSDictionary *)pageCache
-{
-    if (_private->loadingFromPageCache || (_private->gotFirstByte && !_private->committed)) {
-        WebFrame *frame = [self webFrame];
-        WebFrameLoadType loadType = [frame _loadType];
-        bool reload = loadType == WebFrameLoadTypeReload
-            || loadType == WebFrameLoadTypeReloadAllowingStaleData;
-        
-        NSDictionary *headers = [_private->response isKindOfClass:[NSHTTPURLResponse class]]
-            ? [(NSHTTPURLResponse *)_private->response allHeaderFields] : nil;
-
-        [frame _closeOldDataSources];
-
-        LOG(Loading, "committed resource = %@", [[self request] URL]);
-	_private->committed = TRUE;
-        if (!pageCache)
-            [self _makeRepresentation];
-            
-        [frame _transitionToCommitted: pageCache];
-
-        NSURL *baseURL = [[self request] _webDataRequestBaseURL];        
-        NSURL *URL = nil;
-        
-        if (baseURL)
-            URL = baseURL;
-        else
-            URL = [_private->response URL];
-            
-        // WebCore will crash if given an empty URL here.
-        // FIXME: could use CFURL, when available, range API to save an allocation here
-        if (!URL || [URL _web_isEmpty])
-            URL = [NSURL URLWithString:@"about:blank"];
-
-        [[self _bridge] openURL:URL
-                         reload:reload 
-                    contentType:[_private->response MIMEType]
-                        refresh:[headers objectForKey:@"Refresh"]
-                   lastModified:(pageCache ? nil : [_private->response _lastModifiedDate])
-                      pageCache:pageCache];
-
-        [frame _opened];
-    }
-}
-
-- (void)_commitIfReady
-{
-    [self _commitIfReady: nil];
-}
-
--(void)_makeRepresentation
-{
-    Class repClass = [self _representationClass];
-
-    // Check if the data source was already bound?
-    if (![[self representation] isKindOfClass:repClass]) {
-        id newRep = repClass != nil ? [[repClass alloc] init] : nil;
-	[self _setRepresentation:(id <WebDocumentRepresentation>)newRep];
-        [newRep release];
-    }
-
-    [_private->representation setDataSource:self];
-}
-
--(void)_receivedData:(NSData *)data
-{
-    if (!_private->resourceData) {
-        _private->resourceData = [[NSMutableData alloc] init];
-    }
-    [_private->resourceData appendData:data];
-    
-    _private->gotFirstByte = YES;
-    [self _commitIfReady];
-
-    // parsing some of the page can result in running a script which
-    // could possibly destroy the frame and data source. So retain
-    // self temporarily.
-    [self retain];
-    [[self representation] receivedData:data withDataSource:self];
-    [[[[self webFrame] frameView] documentView] dataSourceUpdated:self];
-    [self release];
-}
-
-- (void)_finishedLoading
-{
-    _private->gotFirstByte = YES;
-    [self _commitIfReady];
-
-    [[self representation] finishedLoadingWithDataSource:self];
-}
-
-- (void)_receivedError:(NSError *)error complete:(BOOL)isComplete
-{
-    if (!_private->committed) {
-        [[[self webFrame] _bridge] didNotOpenURL:[_private->originalRequestCopy URL]];
-    }
-    [[self _webView] _mainReceivedError:error
-                           fromDataSource:self
-                                 complete:isComplete];
-}
-
-- (void)_updateIconDatabaseWithURL:(NSURL *)iconURL
-{
-    WebIconDatabase *iconDB = [WebIconDatabase sharedIconDatabase];
-
-    // Bind the URL of the original request and the final URL to the icon URL.
-    [iconDB _setIconURL:[iconURL _web_originalDataAsString] forURL:[[self _URL] _web_originalDataAsString]];
-    [iconDB _setIconURL:[iconURL _web_originalDataAsString] forURL:[[[self _originalRequest] URL] _web_originalDataAsString]];
-
-    
-    if ([self webFrame] == [_private->webView mainFrame])
-        [_private->webView _willChangeValueForKey:_WebMainFrameIconKey];
-    
-    NSImage *icon = [iconDB iconForURL:[[self _URL] _web_originalDataAsString] withSize:WebIconSmallSize];
-    [[_private->webView _frameLoadDelegateForwarder] webView:_private->webView
-                                                      didReceiveIcon:icon
-                                                            forFrame:[self webFrame]];
-    
-    if ([self webFrame] == [_private->webView mainFrame])
-        [_private->webView _didChangeValueForKey:_WebMainFrameIconKey];
-}
-
-- (void)_iconLoaderReceivedPageIcon:(WebIconLoader *)iconLoader
-{
-    [self _updateIconDatabaseWithURL:[iconLoader URL]];
-}
-
-- (void)_loadIcon
-{
-    // Don't load an icon if 1) this is not the main frame 2) we ended in error 3) we already did 4) they aren't save by the DB.
-    if ([self webFrame] != [[self _webView] mainFrame] || _private->mainDocumentError || _private->iconLoader ||
-       ![[WebIconDatabase sharedIconDatabase] iconsAreSaved]) {
-        return;
-    }
-                
-    if(!_private->iconURL){
-        // No icon URL from the LINK tag so try the server's root.
-        // This is only really a feature of http or https, so don't try this with other protocols.
-        NSString *scheme = [[self _URL] scheme];
-        if([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]){
-            _private->iconURL = [[[NSURL _web_URLWithDataAsString:@"/favicon.ico"
-                                              relativeToURL:[self _URL]] absoluteURL] retain];
-        }
-    }
-
-    if(_private->iconURL != nil){
-        if([[WebIconDatabase sharedIconDatabase] _hasIconForIconURL:[_private->iconURL _web_originalDataAsString]]){
-            [self _updateIconDatabaseWithURL:_private->iconURL];
-        }else{
-            ASSERT(!_private->iconLoader);
-            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_private->iconURL];
-            [[self webFrame] _addExtraFieldsToRequest:request alwaysFromRequest:NO];
-            _private->iconLoader = [[WebIconLoader alloc] initWithRequest:request];
-            [request release];
-            [_private->iconLoader setDelegate:self];
-            [_private->iconLoader startLoading];
-        }
-    }
-}
-
-- (void)_setIconURL:(NSURL *)URL
-{
-    // Lower priority than typed icon, so ignore this if we already have an iconURL.
-    if (_private->iconURL == nil) {
-	[_private->iconURL release];
-	_private->iconURL = [URL retain];
-    }
-}
-
-- (void)_setIconURL:(NSURL *)URL withType:(NSString *)iconType
-{
-    // FIXME: Should check to make sure the type is one we know how to handle.
-    [_private->iconURL release];
-    _private->iconURL = [URL retain];
-}
-
-- (void)_defersCallbacksChanged
-{
-    BOOL defers = [_private->webView defersCallbacks];
-    
-    if (defers == _private->defersCallbacks) {
-        return;
-    }
-
-    _private->defersCallbacks = defers;
-    [_private->mainClient setDefersCallbacks:defers];
-
-    NSEnumerator *e = [_private->subresourceClients objectEnumerator];
-    WebSubresourceClient *client;
-    while ((client = [e nextObject])) {
-        [client setDefersCallbacks:defers];
-    }
-
-    [[[self webFrame] childFrames] makeObjectsPerformSelector:@selector(_defersCallbacksChanged)];
-}
-
-- (NSURLRequest *)_originalRequest
-{
-    return _private->originalRequestCopy;
-}
-
-- (void)_setTriggeringAction:(NSDictionary *)action
-{
-    [action retain];
-    [_private->triggeringAction release];
-    _private->triggeringAction = action;
-}
-
-- (NSDictionary *)_triggeringAction
-{
-    return [[_private->triggeringAction retain] autorelease];
-}
-
-
-- (NSURLRequest *)_lastCheckedRequest
-{
-    // It's OK not to make a copy here because we know the caller
-    // isn't going to modify this request
-    return [[_private->lastCheckedRequest retain] autorelease];
-}
-
-- (void)_setLastCheckedRequest:(NSURLRequest *)request
-{
-    NSURLRequest *oldRequest = _private->lastCheckedRequest;
-    _private->lastCheckedRequest = [request copy];
-    [oldRequest release];
-}
-
-- (void)_setJustOpenedForTargetedLink:(BOOL)justOpened
-{
-    _private->justOpenedForTargetedLink = justOpened;
-}
-
-- (BOOL)_justOpenedForTargetedLink
-{
-    return _private->justOpenedForTargetedLink;
-}
-
-- (void)_setStoredInPageCache:(BOOL)f
-{
-    _private->storedInPageCache = f;
-}
-
-- (BOOL)_storedInPageCache
-{
-    return _private->storedInPageCache;
-}
-
-- (BOOL)_loadingFromPageCache
-{
-    return _private->loadingFromPageCache;
-}
-
-- (void)_addResponse: (NSURLResponse *)r
-{
-    if (!_private->responses)
-        _private->responses = [[NSMutableArray alloc] init];
-    [_private->responses addObject: r];
-}
-
-- (NSArray *)_responses
-{
-    return _private->responses;
-}
-
-- (void)_stopLoadingWithError:(NSError *)error
-{
-    [_private->mainClient cancelWithError:error];
-}
-
-- (void)_setWebFrame:(WebFrame *)frame
-{
-    [frame retain];
-    [_private->webFrame release];
-    _private->webFrame = frame;
-}
-
-// May return nil if not initialized with a URL.
-- (NSURL *)_URL
-{
-    return [[self request] URL];
-}
-
-- (NSString *)_stringWithData:(NSData *)data
-{
-    NSString *textEncodingName = [self _overrideEncoding];
-
-    if(!textEncodingName){
-        textEncodingName = [[self response] textEncodingName];
-    }
-
-    if(textEncodingName){
-        return [WebBridge stringWithData:data textEncodingName:textEncodingName];
-    }else{
-        return [WebBridge stringWithData:data textEncoding:kCFStringEncodingISOLatin1];
-    }
-}
-
-- (NSError *)_mainDocumentError
-{
-    return _private->mainDocumentError;
-}
-
-- (BOOL)_isDocumentHTML
-{
-    NSString *MIMEType = [[self response] MIMEType];
-    return [WebView canShowMIMETypeAsHTML:MIMEType];
-}
-
-
- at end
diff --git a/WebKit/WebView.subproj/WebFrame.m b/WebKit/WebView.subproj/WebFrame.m
index 23f3617..3c06694 100644
--- a/WebKit/WebView.subproj/WebFrame.m
+++ b/WebKit/WebView.subproj/WebFrame.m
@@ -25,6 +25,2323 @@
 
 #import <Foundation/NSString_NSURLExtras.h>
 
+#import <objc/objc-runtime.h>
+#import <Foundation/NSURLRequestPrivate.h>
+#import <WebKit/WebNSURLExtras.h>
+#import <WebKit/WebHistoryItemPrivate.h>
+#import <WebKit/WebPreferencesPrivate.h>
+#import <WebKit/WebHistoryPrivate.h>
+#import <WebKit/WebBackForwardList.h>
+#import <WebKit/WebViewPrivate.h>
+#import <WebKit/WebFrameLoadDelegate.h>
+#import <WebKit/WebKitErrorsPrivate.h>
+#import <WebKit/WebDocumentInternal.h>
+#import <WebKit/WebDefaultUIDelegate.h>
+
+
+#ifndef NDEBUG
+static const char * const stateNames[] = {
+    "WebFrameStateProvisional",
+    "WebFrameStateCommittedPage",
+    "WebFrameStateLayoutAcceptable",
+    "WebFrameStateComplete"
+};
+#endif
+
+/*
+Here is the current behavior matrix for four types of navigations:
+
+Standard Nav:
+
+ Restore form state:   YES
+ Restore scroll and focus state:  YES
+ WF Cache policy: NSURLRequestUseProtocolCachePolicy
+ Add to back/forward list: YES
+ 
+Back/Forward:
+
+ Restore form state:   YES
+ Restore scroll and focus state:  YES
+ WF Cache policy: NSURLRequestReturnCacheDataElseLoad
+ Add to back/forward list: NO
+
+Reload (meaning only the reload button):
+
+ Restore form state:   NO
+ Restore scroll and focus state:  YES
+ WF Cache policy: NSURLRequestReloadIgnoringCacheData
+ Add to back/forward list: NO
+
+Repeat load of the same URL (by any other means of navigation other than the reload button, including hitting return in the location field):
+
+ Restore form state:   NO
+ Restore scroll and focus state:  NO, reset to initial conditions
+ WF Cache policy: NSURLRequestReloadIgnoringCacheData
+ Add to back/forward list: NO
+*/
+
+NSString *WebPageCacheEntryDateKey = @"WebPageCacheEntryDateKey";
+NSString *WebPageCacheDataSourceKey = @"WebPageCacheDataSourceKey";
+NSString *WebPageCacheDocumentViewKey = @"WebPageCacheDocumentViewKey";
+
+ at interface NSObject (WebExtraPerformMethod)
+
+- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2 withObject:(id)object3;
+
+ at end
+
+ at implementation NSObject (WebExtraPerformMethod)
+
+- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2 withObject:(id)object3
+{
+    return objc_msgSend(self, aSelector, object1, object2, object3);
+}
+
+ at end
+
+
+// One day we might want to expand the use of this kind of class such that we'd receive one
+// over the bridge, and possibly hand it on through to the FormsDelegate.
+// Today it is just used internally to keep some state as we make our way through a bunch
+// layers while doing a load.
+ at interface WebFormState : NSObject
+{
+    NSObject <WebDOMElement> *_form;
+    NSDictionary *_values;
+    WebFrame *_sourceFrame;
+}
+- (id)initWithForm:(NSObject <WebDOMElement> *)form values:(NSDictionary *)values sourceFrame:(WebFrame *)sourceFrame;
+- (id <WebDOMElement>)form;
+- (NSDictionary *)values;
+- (WebFrame *)sourceFrame;
+ at end
+
+ at interface WebFrame (ForwardDecls)
+- (void)_loadRequest:(NSURLRequest *)request triggeringAction:(NSDictionary *)action loadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState;
+
+- (NSDictionary *)_actionInformationForLoadType:(WebFrameLoadType)loadType isFormSubmission:(BOOL)isFormSubmission event:(NSEvent *)event originalURL:(NSURL *)URL;
+
+- (void)_saveScrollPositionToItem:(WebHistoryItem *)item;
+- (void)_restoreScrollPosition;
+- (void)_scrollToTop;
+
+- (WebHistoryItem *)_createItem: (BOOL)useOriginal;
+- (WebHistoryItem *)_createItemTreeWithTargetFrame:(WebFrame *)targetFrame clippedAtTarget:(BOOL)doClip;
+
+- (void)_resetBackForwardListToCurrent;
+ at end
+
+ at implementation WebFramePrivate
+
+- init
+{
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+    
+    state = WebFrameStateComplete;
+    loadType = WebFrameLoadTypeStandard;
+    
+    return self;
+}
+
+- (void)dealloc
+{
+    ASSERT(scheduledLayoutTimer == nil);
+
+    [webFrameView _setWebView:nil];
+    [dataSource _setWebView:nil];
+    [provisionalDataSource _setWebView:nil];
+
+    [name release];
+    [webFrameView release];
+    [dataSource release];
+    [provisionalDataSource release];
+    [bridge release];
+    [children release];
+
+    [currentItem release];
+    [provisionalItem release];
+    [previousItem release];
+    
+    ASSERT(listener == nil);
+    ASSERT(policyRequest == nil);
+    ASSERT(policyFrameName == nil);
+    ASSERT(policyTarget == nil);
+    ASSERT(policyFormState == nil);
+    ASSERT(policyDataSource == nil);
+
+    [super dealloc];
+}
+
+- (NSString *)name { return name; }
+- (void)setName:(NSString *)n 
+{
+    NSString *newName = [n copy];
+    [name release];
+    name = newName;
+}
+
+- (WebFrameView *)webFrameView { return webFrameView; }
+- (void)setWebFrameView: (WebFrameView *)v 
+{ 
+    [v retain];
+    [webFrameView release];
+    webFrameView = v;
+}
+
+- (WebDataSource *)dataSource { return dataSource; }
+- (void)setDataSource: (WebDataSource *)d
+{
+    [d retain];
+    [dataSource release];
+    dataSource = d;
+}
+
+- (WebView *)webView { return webView; }
+- (void)setWebView: (WebView *)wv
+{
+    webView = wv; // not retained (yet)
+}
+
+- (WebDataSource *)provisionalDataSource { return provisionalDataSource; }
+- (void)setProvisionalDataSource: (WebDataSource *)d
+{
+    ASSERT(!d || !provisionalDataSource);
+    [d retain];
+    [provisionalDataSource release];
+    provisionalDataSource = d;
+}
+
+- (WebFrameLoadType)loadType { return loadType; }
+- (void)setLoadType: (WebFrameLoadType)t
+{
+    loadType = t;
+}
+
+- (WebHistoryItem *)provisionalItem { return provisionalItem; }
+- (void)setProvisionalItem: (WebHistoryItem *)item
+{
+    [item retain];
+    [provisionalItem release];
+    provisionalItem = item;
+}
+
+- (WebHistoryItem *)previousItem { return previousItem; }
+- (void)setPreviousItem:(WebHistoryItem *)item
+{
+    [item retain];
+    [previousItem release];
+    previousItem = item;
+}
+
+- (WebHistoryItem *)currentItem { return currentItem; }
+- (void)setCurrentItem:(WebHistoryItem *)item
+{
+    [item retain];
+    [currentItem release];
+    currentItem = item;
+}
+
+ at end
+
+ at implementation WebFrame (WebPrivate)
+
+- (void)_setWebView:(WebView *)v
+{
+    // To set to nil, we have to use _detachFromParent, not this.
+    ASSERT(v);
+    [_private setWebView:v];
+}
+
+// helper method used in various nav cases below
+- (void)_addBackForwardItemClippedAtTarget:(BOOL)doClip
+{
+    if (![WebDataProtocol _webIsDataProtocolURL:[[[[[self webView] mainFrame] dataSource] response] URL]]) {
+        WebHistoryItem *bfItem = [[[self webView] mainFrame] _createItemTreeWithTargetFrame:self clippedAtTarget:doClip];
+        LOG (BackForward, "for frame %@, adding item  %@\n", [self name], bfItem);
+        [[[self webView] backForwardList] addItem:bfItem];
+    }
+}
+
+- (WebHistoryItem *)_createItem: (BOOL)useOriginal
+{
+    WebDataSource *dataSrc = [self dataSource];
+    NSURLRequest *request;
+    NSURL *URL;
+    WebHistoryItem *bfItem;
+
+    if (useOriginal && 1) {
+        request = [dataSrc _originalRequest];
+    }
+    else {
+        request = [dataSrc request];
+    }
+    URL = [request URL];
+
+    LOG (History, "creating item for %@", request);
+    
+    // Frames that have never successfully loaded any content
+    // may have no URL at all. Currently our history code can't
+    // deal with such things, so we nip that in the bud here.
+    // Later we may want to learn to live with nil for URL.
+    // See bug 3368236 and related bugs for more information.
+    if (URL == nil) {
+        URL = [NSURL URLWithString:@"about:blank"];
+    }
+
+    bfItem = [[[WebHistoryItem alloc] initWithURL:URL target:[self name] parent:[[self parentFrame] name] title:[dataSrc pageTitle]] autorelease];
+    [dataSrc _addBackForwardItem:bfItem];
+    [bfItem setOriginalURLString:[[[dataSrc _originalRequest] URL] _web_originalDataAsString]];
+
+    // save form state if this is a POST
+    if ([[request HTTPMethod] _web_isCaseInsensitiveEqualToString:@"POST"]) {
+        [bfItem setFormData:[request HTTPBody]];
+        [bfItem setFormContentType:[request HTTPContentType]];
+        [bfItem setFormReferrer:[request HTTPReferrer]];
+    }
+
+    // Set the item for which we will save document state
+    [_private setPreviousItem:[_private currentItem]];
+    [_private setCurrentItem:bfItem];
+
+    return bfItem;
+}
+
+/*
+    In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree.  The item that was the target of the user's navigation is designated as the "targetItem".  When this method is called with doClip=YES we're able to create the whole tree except for the target's children, which will be loaded in the future.  That part of the tree will be filled out as the child loads are committed.
+*/
+- (WebHistoryItem *)_createItemTreeWithTargetFrame:(WebFrame *)targetFrame clippedAtTarget:(BOOL)doClip
+{
+    WebHistoryItem *bfItem = [self _createItem: [self parentFrame]?YES:NO];
+
+    [self _saveScrollPositionToItem:[_private previousItem]];
+    if (!(doClip && self == targetFrame)) {
+        // save frame state for items that aren't loading (khtml doesn't save those)
+        [_private->bridge saveDocumentState];
+
+        if (_private->children) {
+            unsigned i;
+            for (i = 0; i < [_private->children count]; i++) {
+                WebFrame *child = [_private->children objectAtIndex:i];
+                WebHistoryItem *childItem = [child _createItemTreeWithTargetFrame:targetFrame clippedAtTarget:doClip];
+                [bfItem addChildItem:childItem];
+            }
+        }
+    }
+    if (self == targetFrame) {
+        [bfItem setIsTargetItem:YES];
+    }
+    return bfItem;
+}
+
+- (WebFrame *)_immediateChildFrameNamed:(NSString *)name
+{
+    int i;
+    for (i = [_private->children count]-1; i >= 0; i--) {
+        WebFrame *frame = [_private->children objectAtIndex:i];
+        if ([[frame name] isEqualToString:name]) {
+            return frame;
+        }
+    }
+    return nil;
+}
+
+- (void)_setName:(NSString *)name
+{
+    // It's wrong to name a frame "_blank".
+    if (![name isEqualToString:@"_blank"]) {
+	[_private setName:name];
+    }
+}
+
+- (WebFrame *)_descendantFrameNamed:(NSString *)name
+{
+    if ([[self name] isEqualToString: name]){
+        return self;
+    }
+
+    NSArray *children = [self childFrames];
+    WebFrame *frame;
+    unsigned i;
+
+    for (i = 0; i < [children count]; i++){
+        frame = [children objectAtIndex: i];
+        frame = [frame _descendantFrameNamed:name];
+        if (frame){
+            return frame;
+        }
+    }
+
+    return nil;
+}
+
+- (void)_detachChildren
+{
+    // Note we have to be careful to remove the kids as we detach each one,
+    // since detaching stops loading, which checks loadComplete, which runs the whole
+    // frame tree, at which point we don't want to trip on already detached kids.
+    if (_private->children) {
+        int i;
+        for (i = [_private->children count]-1; i >=0; i--) {
+            [[_private->children objectAtIndex:i] _detachFromParent];
+            [_private->children removeObjectAtIndex:i];
+        }
+        [_private->children release];
+        _private->children = nil;
+    }
+}
+
+- (void)_closeOldDataSources
+{
+    if (_private->children) {
+        int i;
+        for (i = [_private->children count]-1; i >=0; i--) {
+            [[_private->children objectAtIndex:i] _closeOldDataSources];
+        }
+    }
+    if (_private->dataSource) {
+        [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView willCloseFrame:self];
+    }
+}
+
+- (void)_detachFromParent
+{
+    WebBridge *bridge = _private->bridge;
+    _private->bridge = nil;
+
+    NSTimer *timer = _private->scheduledLayoutTimer;
+    _private->scheduledLayoutTimer = nil;
+    
+    [self stopLoading];
+    [self _saveScrollPositionToItem:[_private currentItem]];
+
+    [bridge closeURL];
+
+    [self _detachChildren];
+
+    [_private setWebView:nil];
+    [_private->webFrameView _setWebView:nil];
+    [_private->dataSource _setWebView:nil];
+    [_private->provisionalDataSource _setWebView:nil];
+
+    [self _setDataSource:nil];
+    [_private setWebFrameView:nil];
+
+    [bridge close];
+    
+    [bridge release];
+
+    [timer invalidate];
+    [timer release];
+}
+
+- (void)_setDataSource:(WebDataSource *)ds
+{
+    if (ds == nil && _private->dataSource == nil) {
+	return;
+    }
+
+    ASSERT(ds != _private->dataSource);
+
+    if (_private->dataSource) {
+        // Make sure that any work that is triggered by resigning first reponder can get done.
+        // The main example where this came up is the textDidEndEditing that is sent to the
+        // FormsDelegate (3223413).  We need to do this before _detachChildren, since that will
+        // remove the views as a side-effect of freeing the bridge, at which point we can't
+        // post the FormDelegate messages.
+        //
+        // Note that this can also take FirstResponder away from a child of our frameView that
+        // is not in a child frame's view.  This is OK because we are in the process
+        // of loading new content, which will blow away all editors in this top frame, and if
+        // a non-editor is firstReponder it will not be affected by endEditingFor:.
+        // Potentially one day someone could write a DocView whose editors were not all
+        // replaced by loading new content, but that does not apply currently.
+        NSView *frameView = [self frameView];
+        NSWindow *window = [frameView window];
+        NSResponder *firstResp = [window firstResponder];
+        if ([firstResp isKindOfClass:[NSView class]]
+            && [(NSView *)firstResp isDescendantOf:frameView])
+        {
+            [window endEditingFor:firstResp];
+        }
+
+        [self _detachChildren];
+
+        [_private->dataSource _setWebFrame:nil];
+    } else {
+        ASSERT(!_private->children);
+    }
+
+    [_private setDataSource:ds];
+    [ds _setWebView:[self webView]];
+    [ds _setWebFrame:self];
+}
+
+- (void)_setLoadType: (WebFrameLoadType)t
+{
+    [_private setLoadType: t];
+}
+
+- (WebFrameLoadType)_loadType
+{
+    return [_private loadType];
+}
+
+- (void)_scheduleLayout:(NSTimeInterval)inSeconds
+{
+    // FIXME: Maybe this should have the code to move up the deadline if the new interval brings the time even closer.
+    if (_private->scheduledLayoutTimer == nil) {
+        _private->scheduledLayoutTimer = [[NSTimer scheduledTimerWithTimeInterval:inSeconds target:self selector:@selector(_timedLayout:) userInfo:nil repeats:FALSE] retain];
+    }
+}
+
+- (void)_timedLayout:(id)userInfo
+{
+    LOG(Timing, "%@:  state = %s", [self name], stateNames[_private->state]);
+
+    NSTimer *timer = _private->scheduledLayoutTimer;
+    _private->scheduledLayoutTimer = nil;
+    
+    if (_private->state >= WebFrameStateLayoutAcceptable) {
+        NSView <WebDocumentView> *documentView = [[self frameView] documentView];
+        
+        if ([self webView])
+            LOG(Timing, "%@:  performing timed layout, %f seconds since start of document load", [self name], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
+            
+        [documentView setNeedsLayout: YES];
+
+        if ([documentView isKindOfClass: [NSView class]]) {
+            NSView *dview = (NSView *)documentView;
+            
+            NSRect frame = [dview frame];
+            
+            if (frame.size.width == 0 || frame.size.height == 0){
+                // We must do the layout now, rather than depend on
+                // display to do a lazy layout because the view
+                // may be recently initialized with a zero size
+                // and the AppKit will optimize out any drawing.
+                
+                // Force a layout now.  At this point we could
+                // check to see if any CSS is pending and delay
+                // the layout further to avoid the flash of unstyled
+                // content.             
+                [documentView layout];
+            }
+        }
+          
+        [documentView setNeedsDisplay: YES];
+    }
+    else {
+        if ([self webView])
+            LOG(Timing, "%@:  NOT performing timed layout (not needed), %f seconds since start of document load", [self name], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
+    }
+
+    [timer release];
+}
+
+
+- (void)_transitionToLayoutAcceptable
+{
+    switch ([self _state]) {
+        case WebFrameStateCommittedPage:
+        {
+            [self _setState: WebFrameStateLayoutAcceptable];
+                    
+            // Start a timer to guarantee that we get an initial layout after
+            // X interval, even if the document and resources are not completely
+            // loaded.
+            BOOL timedDelayEnabled = [[WebPreferences standardPreferences] _initialTimedLayoutEnabled];
+            if (timedDelayEnabled) {
+                NSTimeInterval defaultTimedDelay = [[WebPreferences standardPreferences] _initialTimedLayoutDelay];
+                double timeSinceStart;
+
+                // If the delay getting to the commited state exceeds the initial layout delay, go
+                // ahead and schedule a layout.
+                timeSinceStart = (CFAbsoluteTimeGetCurrent() - [[self dataSource] _loadingStartedTime]);
+                if (timeSinceStart > (double)defaultTimedDelay) {
+                    LOG(Timing, "performing early layout because commit time, %f, exceeded initial layout interval %f", timeSinceStart, defaultTimedDelay);
+                    [self _timedLayout: nil];
+                }
+                else {
+                    NSTimeInterval timedDelay = defaultTimedDelay - timeSinceStart;
+                    
+                    LOG(Timing, "registering delayed layout after %f seconds, time since start %f", timedDelay, timeSinceStart);
+                    [self _scheduleLayout: timedDelay];
+                }
+            }
+            return;
+        }
+
+        case WebFrameStateProvisional:
+        case WebFrameStateComplete:
+        case WebFrameStateLayoutAcceptable:
+            return;
+    }
+    ASSERT_NOT_REACHED();
+}
+
+- (void)_makeDocumentView
+{
+    NSView <WebDocumentView> *documentView = [_private->webFrameView _makeDocumentViewForDataSource:_private->dataSource];
+    if (!documentView) {
+        return;
+    }
+
+    // FIXME: We could save work and not do this for a top-level view that is not a WebHTMLView.
+    WebFrameView *v = _private->webFrameView;
+    [_private->bridge createKHTMLViewWithNSView:documentView marginWidth:[v _marginWidth] marginHeight:[v _marginHeight]];
+    [_private->bridge installInFrame:[v _scrollView]];
+
+    // Call setDataSource on the document view after it has been placed in the view hierarchy.
+    // This what we for the top-level view, so should do this for views in subframes as well.
+    [documentView setDataSource:_private->dataSource];
+}
+
+- (void)_transitionToCommitted: (NSDictionary *)pageCache
+{
+    ASSERT([self webView] != nil);
+
+    switch ([self _state]) {
+        case WebFrameStateProvisional:
+        {
+	    [[[[self frameView] _scrollView] contentView] setCopiesOnScroll:YES];
+
+            WebFrameLoadType loadType = [self _loadType];
+            if (loadType == WebFrameLoadTypeForward ||
+                loadType == WebFrameLoadTypeBack ||
+                loadType == WebFrameLoadTypeIndexedBackForward)
+            {
+                // Once committed, we want to use current item for saving DocState, and
+                // the provisional item for restoring state.
+                // Note previousItem must be set before we close the URL, which will
+                // happen when the data source is made non-provisional below
+                [_private setPreviousItem:[_private currentItem]];
+                ASSERT([_private provisionalItem]);
+                [_private setCurrentItem:[_private provisionalItem]];
+                [_private setProvisionalItem:nil];
+            }
+
+            // Set the committed data source on the frame.
+            [self _setDataSource:_private->provisionalDataSource];
+                
+            [self _setProvisionalDataSource: nil];
+
+            [self _setState: WebFrameStateCommittedPage];
+        
+            // Handle adding the URL to the back/forward list.
+            WebDataSource *ds = [self dataSource];
+            WebHistoryItem *entry = nil;
+            NSString *ptitle = [ds pageTitle];
+
+            switch (loadType) {
+            case WebFrameLoadTypeForward:
+            case WebFrameLoadTypeBack:
+            case WebFrameLoadTypeIndexedBackForward:
+                if ([[self webView] backForwardList]) {
+                    // Must grab the current scroll position before disturbing it
+                    [self _saveScrollPositionToItem:[_private previousItem]];
+                    
+                    // Create a document view for this document, or used the cached view.
+                    if (pageCache){
+                        NSView <WebDocumentView> *cachedView = [pageCache objectForKey: WebPageCacheDocumentViewKey];
+                        ASSERT(cachedView != nil);
+                        [[self frameView] _setDocumentView: cachedView];
+                    }
+                    else
+                        [self _makeDocumentView];
+                        
+                    // FIXME - I'm not sure this call does anything.  Should be dealt with as
+                    // part of 3024377
+                    [self _restoreScrollPosition];
+                }
+                break;
+
+            case WebFrameLoadTypeReload:
+            case WebFrameLoadTypeSame:
+            {
+                WebHistoryItem *currItem = [_private currentItem];
+                LOG(PageCache, "Clearing back/forward cache, %@\n", [currItem URL]);
+                // FIXME: rjw sez this cache clearing is no longer needed
+                [currItem setHasPageCache:NO];
+                if (loadType == WebFrameLoadTypeReload) {
+                    [self _saveScrollPositionToItem:currItem];
+                }
+                // Update the last visited time.  Mostly interesting for URL autocompletion
+                // statistics.
+                NSURL *URL = [[[ds _originalRequest] URL] _webkit_canonicalize];
+                WebHistoryItem *oldItem = [[WebHistory optionalSharedHistory] itemForURL:URL];
+                if (oldItem) {
+                    [oldItem _setLastVisitedTimeInterval:[NSDate timeIntervalSinceReferenceDate]];
+                }
+                [self _makeDocumentView];
+                break;
+            }
+
+            // FIXME - just get rid of this case, and merge WebFrameLoadTypeReloadAllowingStaleData with the above case
+            case WebFrameLoadTypeReloadAllowingStaleData:
+                [self _makeDocumentView];
+                break;
+                
+            case WebFrameLoadTypeStandard:
+                if (![ds _isClientRedirect]) {
+                    // Add item to history.
+		    NSURL *URL = [[[ds _originalRequest] URL] _webkit_canonicalize];
+		    if (![URL _web_isEmpty] && ![WebDataProtocol _webIsDataProtocolURL:URL] ){
+			entry = [[WebHistory optionalSharedHistory] addItemForURL:URL];
+			if (ptitle)
+			    [entry setTitle: ptitle];
+                        [self _addBackForwardItemClippedAtTarget:YES];
+		    }
+
+                } else {
+                    // update the URL in the BF list that we made before the redirect
+                    [[_private currentItem] setURL:[[ds request] URL]];
+                }
+                [self _makeDocumentView];
+                break;
+                
+            case WebFrameLoadTypeOnLoadEvent:
+            case WebFrameLoadTypeInternal:
+                // Add an item to the item tree for this frame
+                ASSERT(![ds _isClientRedirect]);
+                WebHistoryItem *parentItem = [[self parentFrame]->_private currentItem];
+                // The only case where parentItem==nil should be when a parent frame loaded an
+                // empty URL, which doesn't set up a current item in that parent.
+                if (parentItem) {
+                    [parentItem addChildItem:[self _createItem: YES]];
+                }
+                [self _makeDocumentView];
+                break;
+
+            // FIXME Remove this check when dummy ds is removed.  An exception should be thrown
+            // if we're in the WebFrameLoadTypeUninitialized state.
+            default:
+                ASSERT_NOT_REACHED();
+            }
+
+            
+            // Tell the client we've committed this URL.
+            ASSERT([[self frameView] documentView] != nil);
+            [[self webView] _didCommitLoadForFrame: self];
+            [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView didCommitLoadForFrame:self];
+            
+            // If we have a title let the WebView know about it.
+            if (ptitle) {
+                [entry setTitle:ptitle];
+                [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                                                           didReceiveTitle:ptitle
+                                                                  forFrame:self];
+            }
+            break;
+        }
+        
+        case WebFrameStateCommittedPage:
+        case WebFrameStateLayoutAcceptable:
+        case WebFrameStateComplete:
+        default:
+        {
+            ASSERT_NOT_REACHED();
+        }
+    }
+
+
+    if (pageCache){
+        [[self dataSource] _setPrimaryLoadComplete: YES];
+        [self _isLoadComplete];
+    }
+}
+
+- (BOOL)_canCachePage
+{
+    return [[[self webView] backForwardList] _usesPageCache];
+}
+
+- (void)_purgePageCache
+{
+    // This method implements the rule for purging the page cache.
+    unsigned sizeLimit = [[[self webView] backForwardList] pageCacheSize];
+    unsigned pagesCached = 0;
+    WebBackForwardList *backForwardList = [[self webView] backForwardList];
+    NSArray *backList = [backForwardList backListWithLimit: 999999];
+    WebHistoryItem *oldestItem = nil;
+    
+    unsigned i;
+    for (i = 0; i < [backList count]; i++){
+        WebHistoryItem *item = [backList objectAtIndex: i];
+        if ([item hasPageCache]){
+            if (oldestItem == nil)
+                oldestItem = item;
+            pagesCached++;
+        }
+    }
+    
+    // Snapback items are never directly purged here.
+    if (pagesCached >= sizeLimit && ![oldestItem alwaysAttemptToUsePageCache]){
+        LOG(PageCache, "Purging back/forward cache, %@\n", [oldestItem URL]);
+        [oldestItem setHasPageCache: NO];
+    }
+}
+
+- (WebFrameState)_state
+{
+    return _private->state;
+}
+
+static CFAbsoluteTime _timeOfLastCompletedLoad;
++ (CFAbsoluteTime)_timeOfLastCompletedLoad
+{
+    return _timeOfLastCompletedLoad;
+}
+
+- (void)_createPageCacheForItem:(WebHistoryItem *)item
+{
+    NSMutableDictionary *pageCache;
+
+    [item setHasPageCache: YES];
+    pageCache = [item pageCache];
+    [[self dataSource] _setStoredInPageCache: YES];
+    [pageCache setObject: [NSDate date]  forKey: WebPageCacheEntryDateKey];
+    [pageCache setObject: [self dataSource] forKey: WebPageCacheDataSourceKey];
+    [pageCache setObject: [[self frameView] documentView] forKey: WebPageCacheDocumentViewKey];
+    [_private->bridge saveDocumentToPageCache];
+}
+
+- (void)_setState: (WebFrameState)newState
+{
+    LOG(Loading, "%@:  transition from %s to %s", [self name], stateNames[_private->state], stateNames[newState]);
+    if ([self webView])
+        LOG(Timing, "%@:  transition from %s to %s, %f seconds since start of document load", [self name], stateNames[_private->state], stateNames[newState], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
+    
+    if (newState == WebFrameStateComplete && self == [[self webView] mainFrame]){
+        LOG(DocumentLoad, "completed %@ (%f seconds)", [[[self dataSource] request] URL], CFAbsoluteTimeGetCurrent() - [[self dataSource] _loadingStartedTime]);
+    }
+    
+    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
+                    [NSNumber numberWithInt:_private->state], WebPreviousFrameState,
+                    [NSNumber numberWithInt:newState], WebCurrentFrameState, nil];
+                    
+    [[NSNotificationCenter defaultCenter] postNotificationName:WebFrameStateChangedNotification object:self userInfo:userInfo];
+    
+    _private->state = newState;
+    
+    if (_private->state == WebFrameStateProvisional) {
+	[_private->bridge provisionalLoadStarted];
+    
+        // FIXME: This is OK as long as no one resizes the window,
+        // but in the case where someone does, it means garbage outside
+        // the occupied part of the scroll view.
+        [[[self frameView] _scrollView] setDrawsBackground:NO];
+
+        // Cache the page, if possible.
+        // Don't write to the cache if in the middle of a redirect, since we will want to
+        // store the final page we end up on.
+        // No point writing to the cache on a reload or loadSame, since we will just write
+        // over it again when we leave that page.
+        WebHistoryItem *item = [_private currentItem];
+        WebFrameLoadType loadType = [self _loadType];
+        if ([self _canCachePage]
+            && [_private->bridge canCachePage]
+            && item
+            && !_private->quickRedirectComing
+            && loadType != WebFrameLoadTypeReload 
+            && loadType != WebFrameLoadTypeReloadAllowingStaleData
+            && loadType != WebFrameLoadTypeSame
+            && ![[self dataSource] isLoading]
+            && ![[self dataSource] _isStopping]
+            && [[[self dataSource] representation] isKindOfClass: [WebHTMLRepresentation class]])
+        {
+            if (![item pageCache]){
+                LOG(PageCache, "Saving page to back/forward cache, %@\n", [[self dataSource] _URL]);
+
+                // Add the items to this page's cache.
+                [self _createPageCacheForItem:item];
+
+                // See if any page caches need to be purged after the addition of this
+                // new page cache.
+                [self _purgePageCache];
+            }
+        }
+        else {
+            LOG(PageCache, "NOT saving page to back/forward cache, %@\n", [[self dataSource] _URL]);
+        }
+    }
+    
+    if (_private->state == WebFrameStateComplete) {
+        NSScrollView *sv = [[self frameView] _scrollView];
+        [sv setDrawsBackground:YES];
+        NSTimer *timer = _private->scheduledLayoutTimer;
+        _private->scheduledLayoutTimer = nil;
+        [_private setPreviousItem:nil];
+        _timeOfLastCompletedLoad = CFAbsoluteTimeGetCurrent();
+        [timer invalidate];
+        [timer release];
+    }
+}
+
+// Called after we send an openURL:... down to WebCore.
+- (void)_opened
+{
+    if ([[self dataSource] _loadingFromPageCache]){
+        // Force a layout to update view size and thereby update scrollbars.
+        NSView <WebDocumentView> *view = [[self frameView] documentView];
+        if ([view isKindOfClass:[WebHTMLView class]]) {
+            [(WebHTMLView *)view setNeedsToApplyStyles:YES];
+        }
+        [view setNeedsLayout: YES];
+        [view layout];
+        [self _restoreScrollPosition];
+        
+        NSArray *responses = [[self dataSource] _responses];
+        NSURLResponse *response;
+        int i, count = [responses count];
+        for (i = 0; i < count; i++){
+            response = [responses objectAtIndex: i];
+            [_private->bridge objectLoadedFromCacheWithURL:[response URL]
+                    response: response
+                    size: [response expectedContentLength]];
+        }
+        
+        // Release the resources kept in the page cache.  They will be
+        // reset when we leave this page.  The core side of the page cache
+        // will have already been invalidated by the bridge to prevent
+        // premature release.
+        [[_private currentItem] setHasPageCache: NO];
+    }
+}
+
+- (void)_isLoadComplete
+{
+    ASSERT([self webView] != nil);
+
+    switch ([self _state]) {
+        case WebFrameStateProvisional:
+        {
+            WebDataSource *pd = [self provisionalDataSource];
+            
+            LOG(Loading, "%@:  checking complete in WebFrameStateProvisional", [self name]);
+            // If we've received any errors we may be stuck in the provisional state and actually
+            // complete.
+            if ([pd _mainDocumentError]) {
+                // Check all children first.
+                LOG(Loading, "%@:  checking complete, current state WebFrameStateProvisional", [self name]);
+                [self _resetBackForwardListToCurrent];
+                if (![pd isLoading]) {
+                    LOG(Loading, "%@:  checking complete in WebFrameStateProvisional, load done", [self name]);
+
+                    [[self webView] _didFailProvisionalLoadWithError:[pd _mainDocumentError] forFrame:self];
+                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                                          didFailProvisionalLoadWithError:[pd _mainDocumentError]
+                                                                 forFrame:self];
+
+                    // We know the provisional data source didn't cut the muster, release it.
+                    [_private->provisionalDataSource _stopLoading];
+                    [self _setProvisionalDataSource:nil];
+                    
+                    [self _setState:WebFrameStateComplete];
+                    return;
+                }
+            }
+            return;
+        }
+        
+        case WebFrameStateCommittedPage:
+        case WebFrameStateLayoutAcceptable:
+        {
+            WebDataSource *ds = [self dataSource];
+            
+            //LOG(Loading, "%@:  checking complete, current state WEBFRAMESTATE_COMMITTED", [self name]);
+            if (![ds isLoading]) {
+                WebFrameView *thisView = [self frameView];
+                NSView <WebDocumentView> *thisDocumentView = [thisView documentView];
+                ASSERT(thisDocumentView != nil);
+
+                // FIXME: need to avoid doing this in the non-HTML case or the bridge may assert.
+                // Should instead make sure the bridge/part is in the proper state even for
+                // non-HTML content, or make a call to the document and let it deal with the bridge.
+
+                [self _setState:WebFrameStateComplete];
+                if ([ds _isDocumentHTML]) {
+                    [_private->bridge end];
+                }
+
+                // FIXME: Is this subsequent work important if we already navigated away?
+                // Maybe there are bugs because of that, or extra work we can skip because
+                // the new page is ready.
+
+                // Unfortunately we have to get our parent to adjust the frames in this
+                // frameset so this frame's geometry is set correctly.  This should
+                // be a reasonably inexpensive operation.
+                WebDataSource *parentDS = [[self parentFrame] dataSource];
+                if ([[parentDS _bridge] isFrameSet]){
+                    WebFrameView *parentWebFrameView = [[self parentFrame] frameView];
+                    if ([parentDS _isDocumentHTML])
+                        [(WebHTMLView *)[parentWebFrameView documentView] _adjustFrames];
+                }
+
+                // Tell the just loaded document to layout.  This may be necessary
+                // for non-html content that needs a layout message.
+                if (!([[self dataSource] _isDocumentHTML])) {
+                    [thisDocumentView setNeedsLayout:YES];
+                    [thisDocumentView layout];
+                    [thisDocumentView setNeedsDisplay:YES];
+                }
+                 
+                // If the user had a scroll point scroll to it.  This will override
+                // the anchor point.  After much discussion it was decided by folks
+                // that the user scroll point should override the anchor point.
+                if ([[self webView] backForwardList]) {
+                    switch ([self _loadType]) {
+                    case WebFrameLoadTypeForward:
+                    case WebFrameLoadTypeBack:
+                    case WebFrameLoadTypeIndexedBackForward:
+                    case WebFrameLoadTypeReload:
+                        [self _restoreScrollPosition];
+                        break;
+
+                    case WebFrameLoadTypeOnLoadEvent:
+                    case WebFrameLoadTypeStandard:
+                    case WebFrameLoadTypeInternal:
+                    case WebFrameLoadTypeReloadAllowingStaleData:
+                    case WebFrameLoadTypeSame:
+                        // Do nothing.
+                        break;
+
+                    default:
+                        ASSERT_NOT_REACHED();
+                        break;
+                    }
+                }
+
+                [[self webView] _progressCompleted];
+                
+                if ([ds _mainDocumentError]) {
+                    [[self webView] _didFailLoadWithError:[ds _mainDocumentError] forFrame:self];
+                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                                                     didFailLoadWithError:[ds _mainDocumentError]
+                                                                 forFrame:self];
+                } else {
+                    [[self webView] _didFinishLoadForFrame:self];
+                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                                                    didFinishLoadForFrame:self];
+                }
+ 
+                return;
+            }
+            // A resource was loaded, but the entire frame isn't complete.  Schedule a
+            // layout.
+            else {
+                if ([self _state] == WebFrameStateLayoutAcceptable) {
+                    BOOL resourceTimedDelayEnabled = [[WebPreferences standardPreferences] _resourceTimedLayoutEnabled];
+                    if (resourceTimedDelayEnabled) {
+                        NSTimeInterval timedDelay = [[WebPreferences standardPreferences] _resourceTimedLayoutDelay];
+                        [self _scheduleLayout:timedDelay];
+                    }
+                }
+            }
+            return;
+        }
+        
+        case WebFrameStateComplete:
+        {
+            LOG(Loading, "%@:  checking complete, current state WebFrameStateComplete", [self name]);
+            // Even if already complete, we might have set a previous item on a frame that
+            // didn't do any data loading on the past transaction.  Make sure to clear these out.
+            [_private setPreviousItem:nil];
+            return;
+        }
+    }
+    
+    // Yikes!  Serious horkage.
+    ASSERT_NOT_REACHED();
+}
+
++ (void)_recursiveCheckCompleteFromFrame: (WebFrame *)fromFrame
+{
+    int i, count;
+    NSArray *childFrames;
+    
+    childFrames = [fromFrame childFrames];
+    count = [childFrames count];
+    for (i = 0; i < count; i++) {
+        WebFrame *childFrame;
+        
+        childFrame = [childFrames objectAtIndex: i];
+        [WebFrame _recursiveCheckCompleteFromFrame: childFrame];
+        [childFrame _isLoadComplete];
+    }
+    [fromFrame _isLoadComplete];
+}
+
+// Called every time a resource is completely loaded, or an error is received.
+- (void)_checkLoadComplete
+{
+    ASSERT([self webView] != nil);
+
+    // Now walk the frame tree to see if any frame that may have initiated a load is done.
+    [WebFrame _recursiveCheckCompleteFromFrame: [[self webView] mainFrame]];
+}
+
+- (WebBridge *)_bridge
+{
+    return _private->bridge;
+}
+
+- (void)_handleUnimplementablePolicyWithErrorCode:(int)code forURL:(NSURL *)URL
+{
+    NSError *error = [NSError _webKitErrorWithDomain:WebKitErrorDomain code:code URL:URL];
+    WebView *wv = [self webView];
+    [[wv _policyDelegateForwarder] webView:wv unableToImplementPolicyWithError:error frame:self];    
+}
+
+- (void)_clearProvisionalDataSource
+{
+    [self _setProvisionalDataSource:nil];
+}
+
+// helper method that determines whether the subframes described by the item's subitems
+// match our own current frameset
+- (BOOL)_childFramesMatchItem:(WebHistoryItem *)item
+{
+    NSArray *childItems = [item children];
+    int numChildItems = childItems ? [childItems count] : 0;
+    int numChildFrames = _private->children ? [_private->children count] : 0;
+    if (numChildFrames != numChildItems) {
+        return NO;
+    } else {
+        int i;
+        for (i = 0; i < numChildItems; i++) {
+            NSString *itemTargetName = [[childItems objectAtIndex:i] target];
+            //Search recursive here?
+            if (![self _immediateChildFrameNamed:itemTargetName]) {
+                return NO; // couldn't match the i'th itemTarget
+            }
+        }
+        return YES; // found matches for all itemTargets
+    }
+}
+
+- (BOOL)_shouldReloadForCurrent:(NSURL *)currentURL andDestination:(NSURL *)destinationURL
+{
+    return !(([currentURL fragment] || [destinationURL fragment]) &&
+    [[currentURL _webkit_URLByRemovingFragment] isEqual: [destinationURL _webkit_URLByRemovingFragment]]);
+}
+
+// Walk the frame tree and ensure that the URLs match the URLs in the item.
+- (BOOL)_URLsMatchItem:(WebHistoryItem *)item
+{
+    NSURL *currentURL = [[[self dataSource] request] URL];
+
+    if (![[[item URL] _webkit_URLByRemovingFragment] isEqual:[currentURL _webkit_URLByRemovingFragment]])
+        return NO;
+    
+    NSArray *childItems = [item children];
+    WebHistoryItem *childItem;
+    WebFrame *childFrame;
+    int i, count = [childItems count];
+    for (i = 0; i < count; i++){
+        childItem = [childItems objectAtIndex:i];
+        childFrame = [self _immediateChildFrameNamed:[childItem target]];
+        if (![childFrame _URLsMatchItem: childItem])
+            return NO;
+    }
+    
+    return YES;
+}
+
+// loads content into this frame, as specified by item
+- (void)_loadItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)loadType
+{
+    NSURL *itemURL = [item URL];
+    NSURL *itemOriginalURL = [NSURL _web_URLWithDataAsString:[item originalURLString]];
+    NSURL *currentURL = [[[self dataSource] request] URL];
+    NSData *formData = [item formData];
+
+    // Are we navigating to an anchor within the page?
+    // Note if we have child frames we do a real reload, since the child frames might not
+    // match our current frame structure, or they might not have the right content.  We could
+    // check for all that as an additional optimization.
+    // We also do not do anchor-style navigation if we're posting a form.
+    
+    // FIXME: These checks don't match the ones in _loadURL:referrer:loadType:target:triggeringEvent:isFormSubmission:
+    // Perhaps they should.
+    if (!formData && ![self _shouldReloadForCurrent:itemURL andDestination:currentURL] && [self _URLsMatchItem:item] )
+    {
+#if 0
+        // FIXME:  We need to normalize the code paths for anchor navigation.  Something
+        // like the following line of code should be done, but also accounting for correct
+        // updates to the back/forward list and scroll position.
+        // rjw 4/9/03 See 3223929.
+        [self _loadURL:itemURL referrer:[[[self dataSource] request] HTTPReferrer] loadType:loadType target:nil triggeringEvent:nil form:nil formValues:nil];
+#endif
+        // must do this maintenance here, since we don't go through a real page reload
+        [self _saveScrollPositionToItem:[_private currentItem]];
+        // FIXME: form state might want to be saved here too
+
+        // FIXME: Perhaps we can use scrollToAnchorWithURL here instead and remove the older scrollToAnchor:?
+        NSString *anchor = [[item URLString] _web_URLFragment];
+        if (anchor)
+            [[_private->dataSource _bridge] scrollToAnchor: anchor];
+    
+        // must do this maintenance here, since we don't go through a real page reload
+        [_private setCurrentItem:item];
+        [self _restoreScrollPosition];
+
+        // Fake the URL change by updating the datasource's request.  This will no longer
+        // be necessary if we do the better fix described above.
+        NSMutableURLRequest *hackedRequest = [[[self dataSource] request] mutableCopy];
+        [hackedRequest setURL: itemURL];
+        [[self dataSource] __setRequest: [[hackedRequest copy] autorelease]];
+        [hackedRequest release];
+        
+        [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                               didChangeLocationWithinPageForFrame:self];
+    } else {
+        // Remember this item so we can traverse any child items as child frames load
+        [_private setProvisionalItem:item];
+
+        WebDataSource *newDataSource;
+        BOOL inPageCache = NO;
+        
+        // Check if we'll be using the page cache.  We only use the page cache
+        // if one exists and it is less than _backForwardCacheExpirationInterval
+        // seconds old.  If the cache is expired it gets flushed here.
+        if ([item hasPageCache]){
+            NSDictionary *pageCache = [item pageCache];
+            NSDate *cacheDate = [pageCache objectForKey: WebPageCacheEntryDateKey];
+            NSTimeInterval delta = [[NSDate date] timeIntervalSinceDate: cacheDate];
+
+            if (delta <= [[WebPreferences standardPreferences] _backForwardCacheExpirationInterval]){
+                newDataSource = [pageCache objectForKey: WebPageCacheDataSourceKey];
+                [self _loadDataSource:newDataSource withLoadType:loadType formState:nil];   
+                inPageCache = YES;
+            }         
+            else {
+                LOG (PageCache, "Not restoring page from back/forward cache because cache entry has expired, %@ (%3.5f > %3.5f seconds)\n", [[_private provisionalItem] URL], delta, [[WebPreferences standardPreferences] _backForwardCacheExpirationInterval]);
+                [item setHasPageCache: NO];
+            }
+        }
+        
+        if (!inPageCache) {
+            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:itemURL];
+            [self _addExtraFieldsToRequest:request alwaysFromRequest: (formData != nil)?YES:NO];
+
+            // If this was a repost that failed the page cache, we might try to repost the form.
+            NSDictionary *action;
+            if (formData) {
+                [request setHTTPMethod:@"POST"];
+                [request setHTTPBody:formData];
+                [request setHTTPContentType:[item formContentType]];
+                [request setHTTPReferrer:[item formReferrer]];
+
+                // Slight hack to test if the WF cache contains the page we're going to.  We want
+                // to know this before talking to the policy delegate, since it affects whether we
+                // show the DoYouReallyWantToRepost nag.
+                //
+                // This trick has a small bug (3123893) where we might find a cache hit, but then
+                // have the item vanish when we try to use it in the ensuing nav.  This should be
+                // extremely rare, but in that case the user will get an error on the navigation.
+                [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
+                NSURLResponse *synchResponse = nil;
+                [NSURLConnection sendSynchronousRequest:request returningResponse:&synchResponse error:nil];
+                if (synchResponse == nil) { 
+                    // Not in WF cache
+                    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
+                    action = [self _actionInformationForNavigationType:WebNavigationTypeFormResubmitted event:nil originalURL:itemURL];
+                } else {
+                    // We can use the cache, don't use navType=resubmit
+                    action = [self _actionInformationForLoadType:loadType isFormSubmission:NO event:nil originalURL:itemURL];
+                }
+            } else {
+                switch (loadType) {
+                    case WebFrameLoadTypeReload:
+                        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
+                        break;
+                    case WebFrameLoadTypeBack:
+                    case WebFrameLoadTypeForward:
+                    case WebFrameLoadTypeIndexedBackForward:
+			if (![[itemURL scheme] isEqual:@"https"]) {
+			    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
+			}
+                        break;
+                    case WebFrameLoadTypeOnLoadEvent:
+                    case WebFrameLoadTypeStandard:
+                    case WebFrameLoadTypeInternal:
+                        // no-op: leave as protocol default
+                        // FIXME:  I wonder if we ever hit this case
+                        break;
+                    case WebFrameLoadTypeSame:
+                    case WebFrameLoadTypeReloadAllowingStaleData:
+                    default:
+                        ASSERT_NOT_REACHED();
+                }
+
+                action = [self _actionInformationForLoadType:loadType isFormSubmission:NO event:nil originalURL:itemOriginalURL];
+            }
+
+            [self _loadRequest:request triggeringAction:action loadType:loadType formState:nil];
+            [request release];
+        }
+    }
+}
+
+// The general idea here is to traverse the frame tree and the item tree in parallel,
+// tracking whether each frame already has the content the item requests.  If there is
+// a match (by URL), we just restore scroll position and recurse.  Otherwise we must
+// reload that frame, and all its kids.
+- (void)_recursiveGoToItem:(WebHistoryItem *)item fromItem:(WebHistoryItem *)fromItem withLoadType:(WebFrameLoadType)type
+{
+    NSURL *itemURL = [item URL];
+    NSURL *currentURL = [[[self dataSource] request] URL];
+
+    // Always reload the target frame of the item we're going to.  This ensures that we will
+    // do -some- load for the transition, which means a proper notification will be posted
+    // to the app.
+    // The exact URL has to match, including fragment.  We want to go through the _load
+    // method, even if to do a within-page navigation.
+    // The current frame tree and the frame tree snapshot in the item have to match.
+    if (![item isTargetItem] &&
+        [itemURL isEqual:currentURL] &&
+	(([self name] == nil && [item target] == nil) ||[[self name] isEqualToString:[item target]]) &&
+        [self _childFramesMatchItem:item])
+    {
+        // This content is good, so leave it alone and look for children that need reloading
+
+        // Save form state (works from currentItem, since prevItem is nil)
+        ASSERT(![_private previousItem]);
+        [_private->bridge saveDocumentState];
+        [self _saveScrollPositionToItem:[_private currentItem]];
+        
+        [_private setCurrentItem:item];
+
+        // Restore form state (works from currentItem)
+        [_private->bridge restoreDocumentState];
+        // Restore the scroll position (taken in favor of going back to the anchor)
+        [self _restoreScrollPosition];
+        
+        NSArray *childItems = [item children];
+        int numChildItems = childItems ? [childItems count] : 0;
+        int i;
+        for (i = numChildItems - 1; i >= 0; i--) {
+            WebHistoryItem *childItem = [childItems objectAtIndex:i];
+            NSString *childName = [childItem target];
+            WebHistoryItem *fromChildItem = [fromItem childItemWithName:childName];
+            ASSERT(fromChildItem || [fromItem isTargetItem]);
+            WebFrame *childFrame = [self _immediateChildFrameNamed:childName];
+            ASSERT(childFrame);
+            [childFrame _recursiveGoToItem:childItem fromItem:fromChildItem withLoadType:type];
+        }
+    } else {
+        // We need to reload the content
+        [self _loadItem:item withLoadType:type];
+    }
+}
+
+// Main funnel for navigating to a previous location (back/forward, non-search snap-back)
+// This includes recursion to handle loading into framesets properly
+- (void)_goToItem: (WebHistoryItem *)item withLoadType: (WebFrameLoadType)type
+{
+    ASSERT(!_private->parent);
+    WebBackForwardList *backForwardList = [[self webView] backForwardList];
+    WebHistoryItem *currItem = [backForwardList currentItem];
+    // Set the BF cursor before commit, which lets the user quickly click back/forward again.
+    // - plus, it only makes sense for the top level of the operation through the frametree,
+    // as opposed to happening for some/one of the page commits that might happen soon
+    [backForwardList goToItem:item];
+    [self _recursiveGoToItem:item fromItem:currItem withLoadType:type];
+}
+
+- (void)_loadRequest:(NSURLRequest *)request triggeringAction:(NSDictionary *)action loadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState
+{
+    WebDataSource *newDataSource = [[WebDataSource alloc] initWithRequest:request];
+    [newDataSource _setTriggeringAction:action];
+
+    [newDataSource _setOverrideEncoding:[[self dataSource] _overrideEncoding]];
+
+    [self _loadDataSource:newDataSource withLoadType:loadType formState:formState];
+
+    [newDataSource release];
+}
+
+-(NSDictionary *)_actionInformationForNavigationType:(WebNavigationType)navigationType event:(NSEvent *)event originalURL:(NSURL *)URL
+{
+    switch ([event type]) {
+        case NSLeftMouseDown:
+        case NSRightMouseDown:
+        case NSOtherMouseDown:
+        case NSLeftMouseUp:
+        case NSRightMouseUp:
+        case NSOtherMouseUp:
+        {
+            NSView *topViewInEventWindow = [[event window] contentView];
+            NSView *viewContainingPoint = [topViewInEventWindow hitTest:[topViewInEventWindow convertPoint:[event locationInWindow] fromView:nil]];
+            while (viewContainingPoint != nil) {
+                if ([viewContainingPoint isKindOfClass:[WebHTMLView class]]) {
+                    break;
+                }
+                viewContainingPoint = [viewContainingPoint superview];
+            }
+            if (viewContainingPoint != nil) {
+                NSPoint point = [viewContainingPoint convertPoint:[event locationInWindow] fromView:nil];
+                NSDictionary *elementInfo = [(WebHTMLView *)viewContainingPoint _elementAtPoint:point];
+        
+                return [NSDictionary dictionaryWithObjectsAndKeys:
+                    [NSNumber numberWithInt:navigationType], WebActionNavigationTypeKey,
+                    elementInfo, WebActionElementKey,
+                    [NSNumber numberWithInt:[event buttonNumber]], WebActionButtonKey,
+                    [NSNumber numberWithInt:[event modifierFlags]], WebActionModifierFlagsKey,
+                    URL, WebActionOriginalURLKey,
+                    nil];
+            }
+        }
+        
+        // fall through
+        
+        default:
+            return [NSDictionary dictionaryWithObjectsAndKeys:
+                [NSNumber numberWithInt:navigationType], WebActionNavigationTypeKey,
+                URL, WebActionOriginalURLKey,
+                nil];
+    }
+}
+
+-(NSDictionary *)_actionInformationForLoadType:(WebFrameLoadType)loadType isFormSubmission:(BOOL)isFormSubmission event:(NSEvent *)event originalURL:(NSURL *)URL
+{
+    WebNavigationType navType;
+    if (isFormSubmission) {
+        navType = WebNavigationTypeFormSubmitted;
+    } else if (event == nil) {
+        if (loadType == WebFrameLoadTypeReload) {
+            navType = WebNavigationTypeReload;
+        } else if (loadType == WebFrameLoadTypeForward
+                   || loadType == WebFrameLoadTypeBack
+                   || loadType == WebFrameLoadTypeIndexedBackForward) {
+            navType = WebNavigationTypeBackForward;
+        } else {
+            navType = WebNavigationTypeOther;
+        }
+    } else {
+        navType = WebNavigationTypeLinkClicked;
+    }
+    return [self _actionInformationForNavigationType:navType event:event originalURL:URL];
+}
+
+- (void)_invalidatePendingPolicyDecisionCallingDefaultAction:(BOOL)call
+{
+    [_private->listener _invalidate];
+    [_private->listener release];
+    _private->listener = nil;
+
+    NSURLRequest *request = _private->policyRequest;
+    NSString *frameName = _private->policyFrameName;
+    id target = _private->policyTarget;
+    SEL selector = _private->policySelector;
+    WebFormState *formState = _private->policyFormState;
+
+    _private->policyRequest = nil;
+    _private->policyFrameName = nil;
+    _private->policyTarget = nil;
+    _private->policySelector = nil;
+    _private->policyFormState = nil;
+
+    if (call) {
+	if (frameName) {
+	    [target performSelector:selector withObject:nil withObject:nil withObject:nil];
+	} else {
+	    [target performSelector:selector withObject:nil withObject:nil];
+	}
+    }
+
+    [request release];
+    [frameName release];
+    [target release];
+    [formState release];
+}
+
+- (void)_setPolicyDataSource:(WebDataSource *)dataSource
+{
+    [dataSource retain];
+    [_private->policyDataSource release];
+    _private->policyDataSource = dataSource;
+}
+
+- (void)_checkNewWindowPolicyForRequest:(NSURLRequest *)request action:(NSDictionary *)action frameName:(NSString *)frameName formState:(WebFormState *)formState andCall:(id)target withSelector:(SEL)selector
+{
+    WebPolicyDecisionListener *listener = [[WebPolicyDecisionListener alloc]
+        _initWithTarget:self action:@selector(_continueAfterNewWindowPolicy:)];
+
+    _private->policyRequest = [request retain];
+    _private->policyTarget = [target retain];
+    _private->policyFrameName = [frameName retain];
+    _private->policySelector = selector;
+    _private->listener = [listener retain];
+    _private->policyFormState = [formState retain];
+
+    WebView *wv = [self webView];
+    [[wv _policyDelegateForwarder] webView:wv
+            decidePolicyForNewWindowAction:action
+                                   request:request
+                              newFrameName:frameName
+                          decisionListener:listener];
+    
+    [listener release];
+}
+
+-(void)_continueAfterNewWindowPolicy:(WebPolicyAction)policy
+{
+    NSURLRequest *request = [[_private->policyRequest retain] autorelease];
+    NSString *frameName = [[_private->policyFrameName retain] autorelease];
+    id target = [[_private->policyTarget retain] autorelease];
+    SEL selector = _private->policySelector;
+    WebFormState *formState = [[_private->policyFormState retain] autorelease];
+
+    // will release _private->policy* objects, hence the above retains
+    [self _invalidatePendingPolicyDecisionCallingDefaultAction:NO];
+
+    BOOL shouldContinue = NO;
+
+    switch (policy) {
+    case WebPolicyIgnore:
+        break;
+    case WebPolicyDownload:
+	// FIXME: should download full request
+        [[self webView] _downloadURL:[request URL]];
+        break;
+    case WebPolicyUse:
+	shouldContinue = YES;
+        break;
+    default:
+	ASSERT_NOT_REACHED();
+    }
+
+    [target performSelector:selector withObject:(shouldContinue ? request : nil) withObject:frameName withObject:formState];
+}
+
+- (void)_checkNavigationPolicyForRequest:(NSURLRequest *)request
+                              dataSource:(WebDataSource *)dataSource
+                               formState:(WebFormState *)formState
+                                 andCall:(id)target
+                            withSelector:(SEL)selector
+{
+    NSDictionary *action = [dataSource _triggeringAction];
+    if (action == nil) {
+        action = [self _actionInformationForNavigationType:WebNavigationTypeOther event:nil originalURL:[request URL]];
+        [dataSource _setTriggeringAction:action];
+    }
+
+    // Don't ask more than once for the same request or if we are loading an empty URL.
+    // This avoids confusion on the part of the client.
+    if ([request isEqual:[dataSource _lastCheckedRequest]] || [[request URL] _web_isEmpty]) {
+        [target performSelector:selector withObject:request withObject:nil];
+        return;
+    }
+
+    [dataSource _setLastCheckedRequest:request];
+
+    WebPolicyDecisionListener *listener = [[WebPolicyDecisionListener alloc] _initWithTarget:self action:@selector(_continueAfterNavigationPolicy:)];
+    
+    _private->policyRequest = [request retain];
+    _private->policyTarget = [target retain];
+    _private->policySelector = selector;
+    _private->listener = [listener retain];
+    _private->policyFormState = [formState retain];
+
+    WebView *wv = [self webView];
+    [[wv _policyDelegateForwarder] webView:wv
+           decidePolicyForNavigationAction:action
+                                   request:request
+                                     frame:self
+                          decisionListener:listener];
+    
+    [listener release];
+}
+
+-(void)_continueAfterNavigationPolicy:(WebPolicyAction)policy
+{
+    NSURLRequest *request = [[_private->policyRequest retain] autorelease];
+    id target = [[_private->policyTarget retain] autorelease];
+    SEL selector = _private->policySelector;
+    WebFormState *formState = [[_private->policyFormState retain] autorelease];
+    
+    // will release _private->policy* objects, hence the above retains
+    [self _invalidatePendingPolicyDecisionCallingDefaultAction:NO];
+
+    BOOL shouldContinue = NO;
+
+    switch (policy) {
+    case WebPolicyIgnore:
+        break;
+    case WebPolicyDownload:
+	// FIXME: should download full request
+        [[self webView] _downloadURL:[request URL]];
+        break;
+    case WebPolicyUse:
+        if (![WebView _canHandleRequest:request]) {
+            [self _handleUnimplementablePolicyWithErrorCode:WebKitErrorCannotShowURL forURL:[request URL]];
+        } else {
+            shouldContinue = YES;
+        }
+        break;
+    default:
+	ASSERT_NOT_REACHED();
+    }
+
+    [target performSelector:selector withObject:(shouldContinue ? request : nil) withObject:formState];
+}
+
+-(void)_continueFragmentScrollAfterNavigationPolicy:(NSURLRequest *)request formState:(WebFormState *)formState
+{
+    if (!request) {
+        return;
+    }
+
+    NSURL *URL = [request URL];
+    WebDataSource *dataSrc = [self dataSource];
+
+    BOOL isRedirect = _private->quickRedirectComing;
+    LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
+    _private->quickRedirectComing = NO;
+
+    [dataSrc _setURL:URL];
+    if (!isRedirect && ![self _shouldTreatURLAsSameAsCurrent:URL]) {
+        // NB: must happen after _setURL, since we add based on the current request.
+        // Must also happen before we openURL and displace the scroll position, since
+        // adding the BF item will save away scroll state.
+
+        // NB2:  If we were loading a long, slow doc, and the user anchor nav'ed before
+        // it was done, currItem is now set the that slow doc, and prevItem is whatever was
+        // before it.  Adding the b/f item will bump the slow doc down to prevItem, even
+        // though its load is not yet done.  I think this all works out OK, for one because
+        // we have already saved away the scroll and doc state for the long slow load,
+        // but it's not an obvious case.
+        [self _addBackForwardItemClippedAtTarget:NO];
+    }
+
+    [_private->bridge scrollToAnchorWithURL:URL];
+    
+    if (!isRedirect) {
+        // This will clear previousItem from the rest of the frame tree tree that didn't
+        // doing any loading.  We need to make a pass on this now, since for anchor nav
+        // we'll not go through a real load and reach Completed state
+        [self _checkLoadComplete];
+    }
+
+    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                      didChangeLocationWithinPageForFrame:self];
+}
+
+- (void)_addExtraFieldsToRequest:(NSMutableURLRequest *)request alwaysFromRequest: (BOOL)f
+{
+    [request setHTTPUserAgent:[[self webView] userAgentForURL:[request URL]]];
+    
+    // Don't set the cookie policy URL if it's already been set.
+    if ([request HTTPCookiePolicyBaseURL] == nil){
+        if (self == [[self webView] mainFrame] || f) {
+            [request setHTTPCookiePolicyBaseURL:[request URL]];
+        } else {
+            [request setHTTPCookiePolicyBaseURL:[[[[self webView] mainFrame] dataSource] _URL]];
+        }
+    }
+}
+
+
+
+-(void)_continueLoadRequestAfterNewWindowPolicy:(NSURLRequest *)request frameName:(NSString *)frameName formState:(WebFormState *)formState
+{
+    if (!request) {
+        return;
+    }
+    
+    WebView *webView = nil;
+    WebView *currentWebView = [self webView];
+    id wd = [currentWebView UIDelegate];
+    if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
+	webView = [wd webView:currentWebView createWebViewWithRequest:nil];
+    else
+        webView = [[WebDefaultUIDelegate sharedUIDelegate] webView:currentWebView createWebViewWithRequest:nil];
+        
+    [webView _setTopLevelFrameName:frameName];
+    [[webView _UIDelegateForwarder] webViewShow:webView];
+    WebFrame *frame = [webView mainFrame];
+
+    [frame _loadRequest:request triggeringAction:nil loadType:WebFrameLoadTypeStandard formState:formState];
+}
+
+
+// main funnel for navigating via callback from WebCore (e.g., clicking a link, redirect)
+- (void)_loadURL:(NSURL *)URL referrer:(NSString *)referrer loadType:(WebFrameLoadType)loadType target:(NSString *)target triggeringEvent:(NSEvent *)event form:(NSObject <WebDOMElement> *)form formValues:(NSDictionary *)values
+{
+    BOOL isFormSubmission = (values != nil);
+
+    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
+    [request setHTTPReferrer:referrer];
+    [self _addExtraFieldsToRequest:request alwaysFromRequest: (event != nil || isFormSubmission)];
+    if (loadType == WebFrameLoadTypeReload) {
+        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
+    }
+
+    // I believe this is never called with LoadSame.  If it is, we probably want to set the cache
+    // policy of LoadFromOrigin, but I didn't test that.
+    ASSERT(loadType != WebFrameLoadTypeSame);
+
+    NSDictionary *action = [self _actionInformationForLoadType:loadType isFormSubmission:isFormSubmission event:event originalURL:URL];
+    WebFormState *formState = nil;
+    if (form && values) {
+        formState = [[WebFormState alloc] initWithForm:form values:values sourceFrame:self];
+    }
+
+    if (target != nil) {
+	WebFrame *targetFrame = [self findFrameNamed:target];
+	if (targetFrame != nil) {
+	    [targetFrame _loadURL:URL referrer:referrer loadType:loadType target:nil triggeringEvent:event form:form formValues:values];
+	} else {
+	    [self _checkNewWindowPolicyForRequest:request
+                                    action:action
+                                 frameName:target
+                                 formState:formState
+                                   andCall:self
+                              withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
+	}
+	[request release];
+	[formState release];
+	return;
+    }
+
+    WebDataSource *oldDataSource = [[self dataSource] retain];
+
+    BOOL sameURL = [self _shouldTreatURLAsSameAsCurrent:URL];
+
+    // Make sure to do scroll to anchor processing even if the URL is
+    // exactly the same so pages with '#' links and DHTML side effects
+    // work properly.
+    if (!isFormSubmission
+        && loadType != WebFrameLoadTypeReload
+        && loadType != WebFrameLoadTypeSame
+        && ![self _shouldReloadForCurrent:URL andDestination:[_private->bridge URL]]
+
+        // We don't want to just scroll if a link from within a
+        // frameset is trying to reload the frameset into _top.
+        && ![_private->bridge isFrameSet]) {
+        
+        // Just do anchor navigation within the existing content.
+        
+        // We don't do this if we are submitting a form, explicitly reloading,
+        // currently displaying a frameset, or if the new URL does not have a fragment.
+        // These rules are based on what KHTML was doing in KHTMLPart::openURL.
+        
+        
+        // FIXME: What about load types other than Standard and Reload?
+
+        [oldDataSource _setTriggeringAction:action];
+        [self _invalidatePendingPolicyDecisionCallingDefaultAction:YES];
+        [self _checkNavigationPolicyForRequest:request
+                                    dataSource:oldDataSource
+                                     formState:formState
+                                       andCall:self
+                                  withSelector:@selector(_continueFragmentScrollAfterNavigationPolicy:formState:)];
+    } else {
+        [self _loadRequest:request triggeringAction:action loadType:loadType formState:formState];
+        if (_private->quickRedirectComing) {
+            LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
+            _private->quickRedirectComing = NO;
+            
+            // need to transfer BF items from the dataSource that we're replacing
+            WebDataSource *newDataSource = [self provisionalDataSource];
+            [newDataSource _setIsClientRedirect:YES];
+            [newDataSource _addBackForwardItems:[oldDataSource _backForwardItems]];
+        } else if (sameURL) {
+            // Example of this case are sites that reload the same URL with a different cookie
+            // driving the generated content, or a master frame with links that drive a target
+            // frame, where the user has clicked on the same link repeatedly.
+            [self _setLoadType:WebFrameLoadTypeSame];
+        }            
+        [request release];
+    }
+
+    [oldDataSource release];
+    [formState release];
+}
+
+- (void)_loadURL:(NSURL *)URL intoChild:(WebFrame *)childFrame
+{
+    WebHistoryItem *parentItem = [_private currentItem];
+    NSArray *childItems = [parentItem children];
+    WebFrameLoadType loadType = [self _loadType];
+    WebFrameLoadType childLoadType = WebFrameLoadTypeInternal;
+    WebHistoryItem *childItem = nil;
+
+    // If we're moving in the backforward list, we might want to replace the content
+    // of this child frame with whatever was there at that point.
+    // Reload will maintain the frame contents, LoadSame will not.
+    if (childItems &&
+        (loadType == WebFrameLoadTypeForward
+         || loadType == WebFrameLoadTypeBack
+         || loadType == WebFrameLoadTypeIndexedBackForward
+         || loadType == WebFrameLoadTypeReload
+         || loadType == WebFrameLoadTypeReloadAllowingStaleData))
+    {
+        childItem = [parentItem childItemWithName:[childFrame name]];
+        if (childItem) {
+	    // Use the original URL to ensure we get all the side-effects, such as
+	    // onLoad handlers, of any redirects that happened. An example of where
+	    // this is needed is Radar 3213556.
+            URL = [NSURL _web_URLWithDataAsString:[childItem originalURLString]];
+            // These behaviors implied by these loadTypes should apply to the child frames
+            childLoadType = loadType;
+
+            if (loadType == WebFrameLoadTypeForward
+                || loadType == WebFrameLoadTypeBack
+                || loadType == WebFrameLoadTypeIndexedBackForward)
+            {
+                // For back/forward, remember this item so we can traverse any child items as child frames load
+                [childFrame->_private setProvisionalItem:childItem];
+            } else {
+                // For reload, just reinstall the current item, since a new child frame was created but we won't be creating a new BF item
+                [childFrame->_private setCurrentItem:childItem];
+            }
+        }
+    }
+
+    // FIXME: is this the right referrer?
+    [childFrame _loadURL:URL referrer:[[self _bridge] referrer] loadType:childLoadType target:nil triggeringEvent:nil form:nil formValues:nil];
+}
+
+- (void)_postWithURL:(NSURL *)URL referrer:(NSString *)referrer target:(NSString *)target data:(NSData *)data contentType:(NSString *)contentType triggeringEvent:(NSEvent *)event form:(NSObject <WebDOMElement> *)form formValues:(NSDictionary *)values
+{
+    // When posting, use the NSURLRequestReloadIgnoringCacheData load flag.
+    // This prevents a potential bug which may cause a page with a form that uses itself
+    // as an action to be returned from the cache without submitting.
+    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
+    [self _addExtraFieldsToRequest:request alwaysFromRequest: YES];
+    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
+    [request setHTTPMethod:@"POST"];
+    [request setHTTPBody:data];
+    [request setHTTPContentType:contentType];
+    [request setHTTPReferrer:referrer];
+
+    NSDictionary *action = [self _actionInformationForLoadType:WebFrameLoadTypeStandard isFormSubmission:YES event:event originalURL:URL];
+    WebFormState *formState = nil;
+    if (form && values) {
+        formState = [[WebFormState alloc] initWithForm:form values:values sourceFrame:self];
+    }
+
+    if (target != nil) {
+	WebFrame *targetFrame = [self findFrameNamed:target];
+
+	if (targetFrame != nil) {
+	    [targetFrame _loadRequest:request triggeringAction:action loadType:WebFrameLoadTypeStandard formState:formState];
+	} else {
+	    [self _checkNewWindowPolicyForRequest:request action:action frameName:target formState:formState andCall:self withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
+	}
+	[request release];
+	[formState release];
+	return;
+    }
+
+    [self _loadRequest:request triggeringAction:action loadType:WebFrameLoadTypeStandard formState:formState];
+
+    [request release];
+    [formState release];
+}
+
+- (void)_clientRedirectedTo:(NSURL *)URL delay:(NSTimeInterval)seconds fireDate:(NSDate *)date lockHistory:(BOOL)lockHistory isJavaScriptFormAction:(BOOL)isJavaScriptFormAction
+{
+    LOG(Redirect, "%@(%p) Client redirect to: %@, [self dataSource] = %p, lockHistory = %d, isJavaScriptFormAction = %d", [self name], self, URL, [self dataSource], (int)lockHistory, (int)isJavaScriptFormAction);
+
+    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                                willPerformClientRedirectToURL:URL
+                                                         delay:seconds
+                                                      fireDate:date
+                                                      forFrame:self];
+    // If a "quick" redirect comes in an, we set a special mode so we treat the next
+    // load as part of the same navigation.
+
+    if (![self dataSource] || isJavaScriptFormAction) {
+        // If we don't have a dataSource, we have no "original" load on which to base a redirect,
+        // so we better just treat the redirect as a normal load.
+        _private->quickRedirectComing = NO;
+        LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
+    } else {
+        _private->quickRedirectComing = lockHistory;
+        LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
+    }
+}
+
+- (void)_clientRedirectCancelled:(BOOL)cancelWithLoadInProgress
+{
+    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
+                               didCancelClientRedirectForFrame:self];
+    if (!cancelWithLoadInProgress)
+        _private->quickRedirectComing = NO;
+    LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
+}
+
+- (void)_saveScrollPositionToItem:(WebHistoryItem *)item
+{
+    if (item) {
+        NSView *clipView = [[[self frameView] documentView] superview];
+        // we might already be detached when this is called from detachFromParent, in which
+        // case we don't want to override real data earlier gathered with (0,0)
+        if (clipView) {
+            [item setScrollPoint:[clipView bounds].origin];
+        }
+    }
+}
+
+- (void)_restoreScrollPosition
+{
+    ASSERT([_private currentItem]);
+    [[[self frameView] documentView] scrollPoint:[[_private currentItem] scrollPoint]];
+}
+
+- (void)_scrollToTop
+{
+    [[[self frameView] documentView] scrollPoint: NSZeroPoint];
+}
+
+- (void)_textSizeMultiplierChanged
+{
+    NSView <WebDocumentView> *view = [[self frameView] documentView];
+    if ([view conformsToProtocol:@protocol(_web_WebDocumentTextSizing)]) {
+        [(NSView <_web_WebDocumentTextSizing> *)view _web_textSizeMultiplierChanged];
+    }
+
+    [[self childFrames] makeObjectsPerformSelector:@selector(_textSizeMultiplierChanged)];
+}
+
+- (void)_defersCallbacksChanged
+{
+    [[self provisionalDataSource] _defersCallbacksChanged];
+    [[self dataSource] _defersCallbacksChanged];
+}
+
+- (void)_viewWillMoveToHostWindow:(NSWindow *)hostWindow
+{
+    [[[self frameView] documentView] viewWillMoveToHostWindow:hostWindow];
+    [[self childFrames] makeObjectsPerformSelector:@selector(_viewWillMoveToHostWindow:) withObject:hostWindow];
+}
+
+- (void)_viewDidMoveToHostWindow
+{
+    [[[self frameView] documentView] viewDidMoveToHostWindow];
+    [[self childFrames] makeObjectsPerformSelector:@selector(_viewDidMoveToHostWindow)];
+}
+
+- (void)_reloadAllowingStaleDataWithOverrideEncoding:(NSString *)encoding
+{
+    WebDataSource *dataSource = [self dataSource];
+    if (dataSource == nil) {
+        return;
+    }
+
+    NSMutableURLRequest *request = [[dataSource request] mutableCopy];
+    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
+    WebDataSource *newDataSource = [[WebDataSource alloc] initWithRequest:request];
+    [request release];
+    
+    [newDataSource _setOverrideEncoding:encoding];
+
+    [self _loadDataSource:newDataSource withLoadType:WebFrameLoadTypeReloadAllowingStaleData formState:nil];
+    
+    [newDataSource release];
+}
+
+- (void)_addChild:(WebFrame *)child
+{
+    if (_private->children == nil)
+        _private->children = [[NSMutableArray alloc] init];
+    [_private->children addObject:child];
+
+    child->_private->parent = self;
+    [[child _bridge] setParent:_private->bridge];
+    [[child dataSource] _setOverrideEncoding:[[self dataSource] _overrideEncoding]];   
+}
+
+- (void)_removeChild:(WebFrame *)child
+{
+    [_private->children removeObject:child];
+    child->_private->parent = nil;
+}
+
+- (void)_addFramePathToString:(NSMutableString *)path
+{
+    if ([_private->name hasPrefix:@"<!--framePath "]) {
+        // we have a generated name - take the path from our name
+        NSRange ourPathRange = {14, [_private->name length] - 14 - 3};
+        [path appendString:[_private->name substringWithRange:ourPathRange]];
+    } else {
+        // we don't have a generated name - just add our simple name to the end
+        if (_private->parent) {
+            [_private->parent _addFramePathToString:path];
+        }
+        [path appendString:@"/"];
+        if (_private->name) {
+            [path appendString:_private->name];
+        }
+    }
+}
+
+// Generate a repeatable name for a child about to be added to us.  The name must be
+// unique within the frame tree.  The string we generate includes a "path" of names
+// from the root frame down to us.  For this path to be unique, each set of siblings must
+// contribute a unique name to the path, which can't collide with any HTML-assigned names.
+// We generate this path component by index in the child list along with an unlikely frame name.
+- (NSString *)_generateFrameName
+{
+    NSMutableString *path = [NSMutableString stringWithCapacity:256];
+    [path insertString:@"<!--framePath " atIndex:0];
+    [self _addFramePathToString:path];
+    // The new child's path component is all but the 1st char and the last 3 chars
+    [path appendFormat:@"/<!--frame%d-->-->", _private->children ? [_private->children count] : 0];
+    return path;
+}
+
+// If we bailed out of a b/f navigation, we need to set the b/f cursor back to the current
+// item, because we optimistically move it right away at the start of the operation
+- (void)_resetBackForwardListToCurrent {
+    WebFrameLoadType loadType = [self _loadType];
+    if ((loadType == WebFrameLoadTypeForward
+        || loadType == WebFrameLoadTypeBack
+        || loadType == WebFrameLoadTypeIndexedBackForward)
+        && [_private currentItem]
+        && self == [[self webView] mainFrame])
+    {
+        [[[self webView] backForwardList] goToItem:[_private currentItem]];
+    }
+}
+
+- (WebHistoryItem *)_itemForSavingDocState
+{
+    // For a standard page load, we will have a previous item set, which will be used to
+    // store the form state.  However, in some cases we will have no previous item, and
+    // the current item is the right place to save the state.  One example is when we
+    // detach a bunch of frames because we are navigating from a site with frames to
+    // another site.  Another is when saving the frame state of a frame that is not the
+    // target of the current navigation (if we even decide to save with that granularity).
+
+    // Because of previousItem's "masking" of currentItem for this purpose, it's important
+    // that previousItem be cleared at the end of a page transition.  We leverage the
+    // checkLoadComplete recursion to achieve this goal.
+
+    WebHistoryItem *result = [_private previousItem] ? [_private previousItem] : [_private currentItem];
+    return result;
+}
+
+- (WebHistoryItem *)_itemForRestoringDocState
+{
+    switch ([self _loadType]) {
+        case WebFrameLoadTypeReload:
+        case WebFrameLoadTypeReloadAllowingStaleData:
+        case WebFrameLoadTypeSame:
+            // Don't restore any form state on reload or loadSame
+            return nil;
+        case WebFrameLoadTypeBack:
+        case WebFrameLoadTypeForward:
+        case WebFrameLoadTypeIndexedBackForward:
+        case WebFrameLoadTypeInternal:
+        case WebFrameLoadTypeOnLoadEvent:
+        case WebFrameLoadTypeStandard:
+            return [_private currentItem];
+    }
+    ASSERT_NOT_REACHED();
+    return nil;
+}
+
+// Walk the frame tree, telling all frames to save their form state into their current
+// history item.
+- (void)_saveDocumentAndScrollState
+{
+    [_private->bridge saveDocumentState];
+    [self _saveScrollPositionToItem:[_private currentItem]];
+
+    NSArray *frames = [self childFrames];
+    int count = [frames count];
+    int i;
+    for (i = 0; i < count; i++) {
+        [[frames objectAtIndex:i] _saveDocumentAndScrollState];
+    }
+}
+
+// Called after the FormsDelegate is done processing willSubmitForm:
+-(void)_continueAfterWillSubmitForm:(WebPolicyAction)policy
+{
+    if (_private->listener) {
+        [_private->listener _invalidate];
+        [_private->listener release];
+        _private->listener = nil;
+    }
+    [_private->provisionalDataSource _startLoading];
+}
+
+-(void)_continueLoadRequestAfterNavigationPolicy:(NSURLRequest *)request formState:(WebFormState *)formState
+{
+    ASSERT(_private->policyDataSource);
+    
+    if (!request) {
+        [self _setPolicyDataSource:nil];
+        return;
+    }
+
+    WebFrameLoadType loadType = _private->policyLoadType;
+    
+    [self stopLoading];
+    [self _setLoadType:loadType];
+    [self _setProvisionalDataSource:_private->policyDataSource];
+
+    [self _setPolicyDataSource:nil];
+    
+    // We tell the documentView provisionalDataSourceChanged:
+    // once it has been created by the WebView.
+    
+    [self _setState: WebFrameStateProvisional];
+    
+    if (self == [[self webView] mainFrame])
+        LOG(DocumentLoad, "loading %@", [[[self provisionalDataSource] request] URL]);
+
+    WebHistoryItem *item = [_private provisionalItem];
+    if ((loadType == WebFrameLoadTypeForward ||
+        loadType == WebFrameLoadTypeBack ||
+        loadType == WebFrameLoadTypeIndexedBackForward) &&
+        [item hasPageCache]){
+        NSDictionary *pageCache = [[_private provisionalItem] pageCache];
+        if ([pageCache objectForKey:WebCorePageCacheStateKey]){
+            LOG (PageCache, "Restoring page from back/forward cache, %@\n", [[_private provisionalItem] URL]);
+            [_private->provisionalDataSource _startLoading: pageCache];
+            return;
+        }
+    }
+
+    if (formState) {
+        // It's a bit of a hack to reuse the WebPolicyDecisionListener for the continuation
+        // mechanism across the willSubmitForm callout.
+        _private->listener = [[WebPolicyDecisionListener alloc] _initWithTarget:self action:@selector(_continueAfterWillSubmitForm:)];
+        [[[self webView] _formDelegate] frame:self sourceFrame:[formState sourceFrame] willSubmitForm:[formState form] withValues:[formState values] submissionListener:_private->listener];
+    } 
+    else {
+        [self _continueAfterWillSubmitForm:WebPolicyUse];
+    }
+}
+
+- (void)_loadDataSource:(WebDataSource *)newDataSource withLoadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState
+{
+    ASSERT([self webView] != nil);
+
+    // Unfortunately the view must be non-nil, this is ultimately due
+    // to KDE parser requiring a KHTMLView.  Once we settle on a final
+    // KDE drop we should fix this dependency.
+
+    ASSERT([self frameView] != nil);
+
+    _private->policyLoadType = loadType;
+
+    WebFrame *parentFrame = [self parentFrame];
+    if (parentFrame) {
+        [newDataSource _setOverrideEncoding:[[parentFrame dataSource] _overrideEncoding]];
+    }
+    [newDataSource _setWebView:[self webView]];
+    [newDataSource _setJustOpenedForTargetedLink:_private->justOpenedForTargetedLink];
+    _private->justOpenedForTargetedLink = NO;
+
+    [self _setPolicyDataSource:newDataSource];
+
+    [self _checkNavigationPolicyForRequest:[newDataSource request]
+                                dataSource:newDataSource
+                                 formState:formState
+                                   andCall:self
+                              withSelector:@selector(_continueLoadRequestAfterNavigationPolicy:formState:)];
+}
+
+- (void)_setJustOpenedForTargetedLink:(BOOL)justOpened
+{
+    _private->justOpenedForTargetedLink = justOpened;
+}
+
+- (void)_setProvisionalDataSource: (WebDataSource *)d
+{
+    if (_private->provisionalDataSource != _private->dataSource) {
+	[_private->provisionalDataSource _setWebFrame:nil];
+    }
+    [_private setProvisionalDataSource: d];
+    [d _setWebFrame:self];
+}
+
+// used to decide to use loadType=Same
+- (BOOL)_shouldTreatURLAsSameAsCurrent:(NSURL *)URL
+{
+    WebHistoryItem *item = [_private currentItem];
+    NSString* URLString = [URL _web_originalDataAsString];
+    return [URLString isEqual:[item URLString]] || [URLString isEqual:[item originalURLString]];
+}    
+
+- (void)_loadRequest:(NSURLRequest *)request inFrameNamed:(NSString *)frameName
+{
+    if (frameName == nil) {
+	[self loadRequest:request];
+	return;
+    }
+
+    WebFrame *frame = [self findFrameNamed:frameName];
+    
+    if (frame != nil) {
+	[frame loadRequest:request];
+	return;
+    }
+
+    NSDictionary *action = [self _actionInformationForNavigationType:WebNavigationTypeOther event:nil originalURL:[request URL]];
+    [self _checkNewWindowPolicyForRequest:request action:(NSDictionary *)action frameName:frameName formState:nil andCall:self withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
+}
+
+// Returns the next frame in our parent's children array, or nil
+- (WebFrame *)_nextSibling
+{
+    if (_private->parent) {
+        NSArray *parentsKids = _private->parent->_private->children;
+        unsigned selfIndex = [parentsKids indexOfObjectIdenticalTo:self];
+        ASSERT(selfIndex != NSNotFound);
+        if (selfIndex < [parentsKids count]-1) {
+            return [parentsKids objectAtIndex:selfIndex+1];
+        }
+    }
+    return nil;		// no parent, or no more later siblings
+}
+
+// Returns the previous frame in our parent's children array, or nil
+- (WebFrame *)_previousSibling
+{
+    if (_private->parent) {
+        NSArray *parentsKids = _private->parent->_private->children;
+        unsigned selfIndex = [parentsKids indexOfObjectIdenticalTo:self];
+        ASSERT(selfIndex != NSNotFound);
+        if (selfIndex > 0) {
+            return [parentsKids objectAtIndex:selfIndex-1];
+        }
+    }
+    return nil;		// no parent, or no more earlier siblings
+}
+
+// Returns the last child of us and any children, or nil
+- (WebFrame *)_lastChild
+{
+    if (_private->children && [_private->children count]) {
+        WebFrame *ourLastKid = [_private->children lastObject];
+        WebFrame *kidsLastKid = [ourLastKid _lastChild];
+        return kidsLastKid ? kidsLastKid : ourLastKid;
+    }
+    return nil;		// no kids
+}
+
+// Return next frame to be traversed, visiting children after parent
+- (WebFrame *)_nextFrameWithWrap:(BOOL)wrapFlag
+{
+    if (_private->children && [_private->children count]) {
+        return [_private->children objectAtIndex:0];
+    } else if (_private->parent) {
+        WebFrame *frame;
+        for (frame = self; frame->_private->parent; frame = frame->_private->parent) {
+            WebFrame *nextSibling = [frame _nextSibling];
+            if (nextSibling) {
+                return nextSibling;
+            }
+        }
+        return wrapFlag ? frame : nil;		// made it all the way to the top
+    } else {
+        return wrapFlag ? self : nil;		// self is the top and we have no kids
+    }
+}
+
+// Return previous frame to be traversed, exact reverse order of _nextFrame
+- (WebFrame *)_previousFrameWithWrap:(BOOL)wrapFlag
+{
+    WebFrame *prevSibling = [self _previousSibling];
+    if (prevSibling) {
+        WebFrame *prevSiblingLastChild = [prevSibling _lastChild];
+        return prevSiblingLastChild ? prevSiblingLastChild : prevSibling;
+    } else if (_private->parent) {
+        return _private->parent;
+    } else {
+        // no siblings, no parent, self==top
+        if (wrapFlag) {
+            WebFrame *selfLastChild = [self _lastChild];
+            return selfLastChild ? selfLastChild : self;
+        } else {
+            // top view is always the last one in this ordering, so prev is nil without wrap
+            return nil;
+        }
+    }
+}
+
+- (void)_setShouldCreateRenderers:(BOOL)f
+{
+    [_private->bridge setShouldCreateRenderers:f];
+}
+
+- (BOOL)_shouldCreateRenderers
+{
+    return [_private->bridge shouldCreateRenderers];
+}
+
+- (int)_numPendingOrLoadingRequests:(BOOL)recurse
+{
+    int num;
+
+    if (!recurse)
+        return [[self _bridge] numPendingOrLoadingRequests];
+
+    num = [[self _bridge] numPendingOrLoadingRequests];
+    NSArray *children = [self childFrames];
+    int i, count = [children count];
+    WebFrame *child;
+    for (i = 0; i < count; i++){
+        child = [children objectAtIndex: 0];
+        num += [child _numPendingOrLoadingRequests:recurse];
+    }
+    return num;
+}
+
+- (NSColor *)_bodyBackgroundColor
+{
+    return [_private->bridge bodyBackgroundColor];
+}
+
+ at end
+
+ at implementation WebFormState : NSObject
+
+- (id)initWithForm:(NSObject <WebDOMElement> *)form values:(NSDictionary *)values sourceFrame:(WebFrame *)sourceFrame
+{
+    [super init];
+    _form = [form retain];
+    _values = [values copy];
+    _sourceFrame = [sourceFrame retain];
+    return self;
+}
+
+- (void)dealloc
+{
+    [_form release];
+    [_values release];
+    [_sourceFrame release];
+    [super dealloc];
+}
+
+- (id <WebDOMElement>)form
+{
+    return _form;
+}
+
+- (NSDictionary *)values
+{
+    return _values;
+}
+
+- (WebFrame *)sourceFrame
+{
+    return _sourceFrame;
+}
+
+ at end
+
 @implementation WebFrame
 
 - init
diff --git a/WebKit/WebView.subproj/WebFramePrivate.m b/WebKit/WebView.subproj/WebFramePrivate.m
deleted file mode 100644
index db77487..0000000
--- a/WebKit/WebView.subproj/WebFramePrivate.m
+++ /dev/null
@@ -1,2345 +0,0 @@
-/*
-    WebFramePrivate.m
-    
-    Copyright 2001, 2002, Apple Computer, Inc. All rights reserved.
-*/
-
-#import <WebKit/WebFramePrivate.h>
-
-#import <WebKit/WebBackForwardList.h>
-#import <WebKit/WebBridge.h>
-#import <WebKit/WebDataProtocol.h>
-#import <WebKit/WebDataSource.h>
-#import <WebKit/WebDataSourcePrivate.h>
-#import <WebKit/WebDefaultUIDelegate.h>
-#import <WebKit/WebDocument.h>
-#import <WebKit/WebDocumentInternal.h>
-#import <WebKit/WebDynamicScrollBarsView.h>
-#import <WebKit/WebFormDelegate.h>
-#import <WebKit/WebFrameLoadDelegate.h>
-#import <WebKit/WebFrameViewPrivate.h>
-#import <WebKit/WebHistoryPrivate.h>
-#import <WebKit/WebHistoryItemPrivate.h>
-#import <WebKit/WebHTMLRepresentation.h>
-#import <WebKit/WebHTMLView.h>
-#import <WebKit/WebHTMLViewPrivate.h>
-#import <WebKit/WebKitLogging.h>
-#import <WebKit/WebKitErrors.h>
-#import <WebKit/WebKitErrorsPrivate.h>
-#import <WebKit/WebNSURLExtras.h>
-#import <WebKit/WebPolicyDelegatePrivate.h>
-#import <WebKit/WebPreferencesPrivate.h>
-#import <WebKit/WebUIDelegate.h>
-#import <WebKit/WebViewPrivate.h>
-
-#import <Foundation/NSError_NSURLExtras.h>
-#import <Foundation/NSString_NSURLExtras.h>
-#import <Foundation/NSURLConnection.h>
-#import <Foundation/NSURLRequest.h>
-#import <Foundation/NSURLRequestPrivate.h>
-#import <Foundation/NSURLResponse.h>
-
-#import <objc/objc-runtime.h>
-
-#ifndef NDEBUG
-static const char * const stateNames[] = {
-    "WebFrameStateProvisional",
-    "WebFrameStateCommittedPage",
-    "WebFrameStateLayoutAcceptable",
-    "WebFrameStateComplete"
-};
-#endif
-
-/*
-Here is the current behavior matrix for four types of navigations:
-
-Standard Nav:
-
- Restore form state:   YES
- Restore scroll and focus state:  YES
- WF Cache policy: NSURLRequestUseProtocolCachePolicy
- Add to back/forward list: YES
- 
-Back/Forward:
-
- Restore form state:   YES
- Restore scroll and focus state:  YES
- WF Cache policy: NSURLRequestReturnCacheDataElseLoad
- Add to back/forward list: NO
-
-Reload (meaning only the reload button):
-
- Restore form state:   NO
- Restore scroll and focus state:  YES
- WF Cache policy: NSURLRequestReloadIgnoringCacheData
- Add to back/forward list: NO
-
-Repeat load of the same URL (by any other means of navigation other than the reload button, including hitting return in the location field):
-
- Restore form state:   NO
- Restore scroll and focus state:  NO, reset to initial conditions
- WF Cache policy: NSURLRequestReloadIgnoringCacheData
- Add to back/forward list: NO
-*/
-
-NSString *WebPageCacheEntryDateKey = @"WebPageCacheEntryDateKey";
-NSString *WebPageCacheDataSourceKey = @"WebPageCacheDataSourceKey";
-NSString *WebPageCacheDocumentViewKey = @"WebPageCacheDocumentViewKey";
-
- at interface NSObject (WebExtraPerformMethod)
-
-- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2 withObject:(id)object3;
-
- at end
-
- at implementation NSObject (WebExtraPerformMethod)
-
-- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2 withObject:(id)object3
-{
-    return objc_msgSend(self, aSelector, object1, object2, object3);
-}
-
- at end
-
-
-// One day we might want to expand the use of this kind of class such that we'd receive one
-// over the bridge, and possibly hand it on through to the FormsDelegate.
-// Today it is just used internally to keep some state as we make our way through a bunch
-// layers while doing a load.
- at interface WebFormState : NSObject
-{
-    NSObject <WebDOMElement> *_form;
-    NSDictionary *_values;
-    WebFrame *_sourceFrame;
-}
-- (id)initWithForm:(NSObject <WebDOMElement> *)form values:(NSDictionary *)values sourceFrame:(WebFrame *)sourceFrame;
-- (id <WebDOMElement>)form;
-- (NSDictionary *)values;
-- (WebFrame *)sourceFrame;
- at end
-
- at interface WebFrame (ForwardDecls)
-- (void)_loadRequest:(NSURLRequest *)request triggeringAction:(NSDictionary *)action loadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState;
-
-- (NSDictionary *)_actionInformationForLoadType:(WebFrameLoadType)loadType isFormSubmission:(BOOL)isFormSubmission event:(NSEvent *)event originalURL:(NSURL *)URL;
-
-- (void)_saveScrollPositionToItem:(WebHistoryItem *)item;
-- (void)_restoreScrollPosition;
-- (void)_scrollToTop;
-
-- (WebHistoryItem *)_createItem: (BOOL)useOriginal;
-- (WebHistoryItem *)_createItemTreeWithTargetFrame:(WebFrame *)targetFrame clippedAtTarget:(BOOL)doClip;
-
-- (void)_resetBackForwardListToCurrent;
- at end
-
- at implementation WebFramePrivate
-
-- init
-{
-    self = [super init];
-    if (!self) {
-        return nil;
-    }
-    
-    state = WebFrameStateComplete;
-    loadType = WebFrameLoadTypeStandard;
-    
-    return self;
-}
-
-- (void)dealloc
-{
-    ASSERT(scheduledLayoutTimer == nil);
-
-    [webFrameView _setWebView:nil];
-    [dataSource _setWebView:nil];
-    [provisionalDataSource _setWebView:nil];
-
-    [name release];
-    [webFrameView release];
-    [dataSource release];
-    [provisionalDataSource release];
-    [bridge release];
-    [children release];
-
-    [currentItem release];
-    [provisionalItem release];
-    [previousItem release];
-    
-    ASSERT(listener == nil);
-    ASSERT(policyRequest == nil);
-    ASSERT(policyFrameName == nil);
-    ASSERT(policyTarget == nil);
-    ASSERT(policyFormState == nil);
-    ASSERT(policyDataSource == nil);
-
-    [super dealloc];
-}
-
-- (NSString *)name { return name; }
-- (void)setName:(NSString *)n 
-{
-    NSString *newName = [n copy];
-    [name release];
-    name = newName;
-}
-
-- (WebFrameView *)webFrameView { return webFrameView; }
-- (void)setWebFrameView: (WebFrameView *)v 
-{ 
-    [v retain];
-    [webFrameView release];
-    webFrameView = v;
-}
-
-- (WebDataSource *)dataSource { return dataSource; }
-- (void)setDataSource: (WebDataSource *)d
-{
-    [d retain];
-    [dataSource release];
-    dataSource = d;
-}
-
-- (WebView *)webView { return webView; }
-- (void)setWebView: (WebView *)wv
-{
-    webView = wv; // not retained (yet)
-}
-
-- (WebDataSource *)provisionalDataSource { return provisionalDataSource; }
-- (void)setProvisionalDataSource: (WebDataSource *)d
-{
-    ASSERT(!d || !provisionalDataSource);
-    [d retain];
-    [provisionalDataSource release];
-    provisionalDataSource = d;
-}
-
-- (WebFrameLoadType)loadType { return loadType; }
-- (void)setLoadType: (WebFrameLoadType)t
-{
-    loadType = t;
-}
-
-- (WebHistoryItem *)provisionalItem { return provisionalItem; }
-- (void)setProvisionalItem: (WebHistoryItem *)item
-{
-    [item retain];
-    [provisionalItem release];
-    provisionalItem = item;
-}
-
-- (WebHistoryItem *)previousItem { return previousItem; }
-- (void)setPreviousItem:(WebHistoryItem *)item
-{
-    [item retain];
-    [previousItem release];
-    previousItem = item;
-}
-
-- (WebHistoryItem *)currentItem { return currentItem; }
-- (void)setCurrentItem:(WebHistoryItem *)item
-{
-    [item retain];
-    [currentItem release];
-    currentItem = item;
-}
-
- at end
-
- at implementation WebFrame (WebPrivate)
-
-- (void)_setWebView:(WebView *)v
-{
-    // To set to nil, we have to use _detachFromParent, not this.
-    ASSERT(v);
-    [_private setWebView:v];
-}
-
-// helper method used in various nav cases below
-- (void)_addBackForwardItemClippedAtTarget:(BOOL)doClip
-{
-    if (![WebDataProtocol _webIsDataProtocolURL:[[[[[self webView] mainFrame] dataSource] response] URL]]) {
-        WebHistoryItem *bfItem = [[[self webView] mainFrame] _createItemTreeWithTargetFrame:self clippedAtTarget:doClip];
-        LOG (BackForward, "for frame %@, adding item  %@\n", [self name], bfItem);
-        [[[self webView] backForwardList] addItem:bfItem];
-    }
-}
-
-- (WebHistoryItem *)_createItem: (BOOL)useOriginal
-{
-    WebDataSource *dataSrc = [self dataSource];
-    NSURLRequest *request;
-    NSURL *URL;
-    WebHistoryItem *bfItem;
-
-    if (useOriginal && 1) {
-        request = [dataSrc _originalRequest];
-    }
-    else {
-        request = [dataSrc request];
-    }
-    URL = [request URL];
-
-    LOG (History, "creating item for %@", request);
-    
-    // Frames that have never successfully loaded any content
-    // may have no URL at all. Currently our history code can't
-    // deal with such things, so we nip that in the bud here.
-    // Later we may want to learn to live with nil for URL.
-    // See bug 3368236 and related bugs for more information.
-    if (URL == nil) {
-        URL = [NSURL URLWithString:@"about:blank"];
-    }
-
-    bfItem = [[[WebHistoryItem alloc] initWithURL:URL target:[self name] parent:[[self parentFrame] name] title:[dataSrc pageTitle]] autorelease];
-    [dataSrc _addBackForwardItem:bfItem];
-    [bfItem setOriginalURLString:[[[dataSrc _originalRequest] URL] _web_originalDataAsString]];
-
-    // save form state if this is a POST
-    if ([[request HTTPMethod] _web_isCaseInsensitiveEqualToString:@"POST"]) {
-        [bfItem setFormData:[request HTTPBody]];
-        [bfItem setFormContentType:[request HTTPContentType]];
-        [bfItem setFormReferrer:[request HTTPReferrer]];
-    }
-
-    // Set the item for which we will save document state
-    [_private setPreviousItem:[_private currentItem]];
-    [_private setCurrentItem:bfItem];
-
-    return bfItem;
-}
-
-/*
-    In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree.  The item that was the target of the user's navigation is designated as the "targetItem".  When this method is called with doClip=YES we're able to create the whole tree except for the target's children, which will be loaded in the future.  That part of the tree will be filled out as the child loads are committed.
-*/
-- (WebHistoryItem *)_createItemTreeWithTargetFrame:(WebFrame *)targetFrame clippedAtTarget:(BOOL)doClip
-{
-    WebHistoryItem *bfItem = [self _createItem: [self parentFrame]?YES:NO];
-
-    [self _saveScrollPositionToItem:[_private previousItem]];
-    if (!(doClip && self == targetFrame)) {
-        // save frame state for items that aren't loading (khtml doesn't save those)
-        [_private->bridge saveDocumentState];
-
-        if (_private->children) {
-            unsigned i;
-            for (i = 0; i < [_private->children count]; i++) {
-                WebFrame *child = [_private->children objectAtIndex:i];
-                WebHistoryItem *childItem = [child _createItemTreeWithTargetFrame:targetFrame clippedAtTarget:doClip];
-                [bfItem addChildItem:childItem];
-            }
-        }
-    }
-    if (self == targetFrame) {
-        [bfItem setIsTargetItem:YES];
-    }
-    return bfItem;
-}
-
-- (WebFrame *)_immediateChildFrameNamed:(NSString *)name
-{
-    int i;
-    for (i = [_private->children count]-1; i >= 0; i--) {
-        WebFrame *frame = [_private->children objectAtIndex:i];
-        if ([[frame name] isEqualToString:name]) {
-            return frame;
-        }
-    }
-    return nil;
-}
-
-- (void)_setName:(NSString *)name
-{
-    // It's wrong to name a frame "_blank".
-    if (![name isEqualToString:@"_blank"]) {
-	[_private setName:name];
-    }
-}
-
-- (WebFrame *)_descendantFrameNamed:(NSString *)name
-{
-    if ([[self name] isEqualToString: name]){
-        return self;
-    }
-
-    NSArray *children = [self childFrames];
-    WebFrame *frame;
-    unsigned i;
-
-    for (i = 0; i < [children count]; i++){
-        frame = [children objectAtIndex: i];
-        frame = [frame _descendantFrameNamed:name];
-        if (frame){
-            return frame;
-        }
-    }
-
-    return nil;
-}
-
-- (void)_detachChildren
-{
-    // Note we have to be careful to remove the kids as we detach each one,
-    // since detaching stops loading, which checks loadComplete, which runs the whole
-    // frame tree, at which point we don't want to trip on already detached kids.
-    if (_private->children) {
-        int i;
-        for (i = [_private->children count]-1; i >=0; i--) {
-            [[_private->children objectAtIndex:i] _detachFromParent];
-            [_private->children removeObjectAtIndex:i];
-        }
-        [_private->children release];
-        _private->children = nil;
-    }
-}
-
-- (void)_closeOldDataSources
-{
-    if (_private->children) {
-        int i;
-        for (i = [_private->children count]-1; i >=0; i--) {
-            [[_private->children objectAtIndex:i] _closeOldDataSources];
-        }
-    }
-    if (_private->dataSource) {
-        [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView willCloseFrame:self];
-    }
-}
-
-- (void)_detachFromParent
-{
-    WebBridge *bridge = _private->bridge;
-    _private->bridge = nil;
-
-    NSTimer *timer = _private->scheduledLayoutTimer;
-    _private->scheduledLayoutTimer = nil;
-    
-    [self stopLoading];
-    [self _saveScrollPositionToItem:[_private currentItem]];
-
-    [bridge closeURL];
-
-    [self _detachChildren];
-
-    [_private setWebView:nil];
-    [_private->webFrameView _setWebView:nil];
-    [_private->dataSource _setWebView:nil];
-    [_private->provisionalDataSource _setWebView:nil];
-
-    [self _setDataSource:nil];
-    [_private setWebFrameView:nil];
-
-    [bridge close];
-    
-    [bridge release];
-
-    [timer invalidate];
-    [timer release];
-}
-
-- (void)_setDataSource:(WebDataSource *)ds
-{
-    if (ds == nil && _private->dataSource == nil) {
-	return;
-    }
-
-    ASSERT(ds != _private->dataSource);
-
-    if (_private->dataSource) {
-        // Make sure that any work that is triggered by resigning first reponder can get done.
-        // The main example where this came up is the textDidEndEditing that is sent to the
-        // FormsDelegate (3223413).  We need to do this before _detachChildren, since that will
-        // remove the views as a side-effect of freeing the bridge, at which point we can't
-        // post the FormDelegate messages.
-        //
-        // Note that this can also take FirstResponder away from a child of our frameView that
-        // is not in a child frame's view.  This is OK because we are in the process
-        // of loading new content, which will blow away all editors in this top frame, and if
-        // a non-editor is firstReponder it will not be affected by endEditingFor:.
-        // Potentially one day someone could write a DocView whose editors were not all
-        // replaced by loading new content, but that does not apply currently.
-        NSView *frameView = [self frameView];
-        NSWindow *window = [frameView window];
-        NSResponder *firstResp = [window firstResponder];
-        if ([firstResp isKindOfClass:[NSView class]]
-            && [(NSView *)firstResp isDescendantOf:frameView])
-        {
-            [window endEditingFor:firstResp];
-        }
-
-        [self _detachChildren];
-
-        [_private->dataSource _setWebFrame:nil];
-    } else {
-        ASSERT(!_private->children);
-    }
-
-    [_private setDataSource:ds];
-    [ds _setWebView:[self webView]];
-    [ds _setWebFrame:self];
-}
-
-- (void)_setLoadType: (WebFrameLoadType)t
-{
-    [_private setLoadType: t];
-}
-
-- (WebFrameLoadType)_loadType
-{
-    return [_private loadType];
-}
-
-- (void)_scheduleLayout:(NSTimeInterval)inSeconds
-{
-    // FIXME: Maybe this should have the code to move up the deadline if the new interval brings the time even closer.
-    if (_private->scheduledLayoutTimer == nil) {
-        _private->scheduledLayoutTimer = [[NSTimer scheduledTimerWithTimeInterval:inSeconds target:self selector:@selector(_timedLayout:) userInfo:nil repeats:FALSE] retain];
-    }
-}
-
-- (void)_timedLayout:(id)userInfo
-{
-    LOG(Timing, "%@:  state = %s", [self name], stateNames[_private->state]);
-
-    NSTimer *timer = _private->scheduledLayoutTimer;
-    _private->scheduledLayoutTimer = nil;
-    
-    if (_private->state >= WebFrameStateLayoutAcceptable) {
-        NSView <WebDocumentView> *documentView = [[self frameView] documentView];
-        
-        if ([self webView])
-            LOG(Timing, "%@:  performing timed layout, %f seconds since start of document load", [self name], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
-            
-        [documentView setNeedsLayout: YES];
-
-        if ([documentView isKindOfClass: [NSView class]]) {
-            NSView *dview = (NSView *)documentView;
-            
-            NSRect frame = [dview frame];
-            
-            if (frame.size.width == 0 || frame.size.height == 0){
-                // We must do the layout now, rather than depend on
-                // display to do a lazy layout because the view
-                // may be recently initialized with a zero size
-                // and the AppKit will optimize out any drawing.
-                
-                // Force a layout now.  At this point we could
-                // check to see if any CSS is pending and delay
-                // the layout further to avoid the flash of unstyled
-                // content.             
-                [documentView layout];
-            }
-        }
-          
-        [documentView setNeedsDisplay: YES];
-    }
-    else {
-        if ([self webView])
-            LOG(Timing, "%@:  NOT performing timed layout (not needed), %f seconds since start of document load", [self name], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
-    }
-
-    [timer release];
-}
-
-
-- (void)_transitionToLayoutAcceptable
-{
-    switch ([self _state]) {
-        case WebFrameStateCommittedPage:
-        {
-            [self _setState: WebFrameStateLayoutAcceptable];
-                    
-            // Start a timer to guarantee that we get an initial layout after
-            // X interval, even if the document and resources are not completely
-            // loaded.
-            BOOL timedDelayEnabled = [[WebPreferences standardPreferences] _initialTimedLayoutEnabled];
-            if (timedDelayEnabled) {
-                NSTimeInterval defaultTimedDelay = [[WebPreferences standardPreferences] _initialTimedLayoutDelay];
-                double timeSinceStart;
-
-                // If the delay getting to the commited state exceeds the initial layout delay, go
-                // ahead and schedule a layout.
-                timeSinceStart = (CFAbsoluteTimeGetCurrent() - [[self dataSource] _loadingStartedTime]);
-                if (timeSinceStart > (double)defaultTimedDelay) {
-                    LOG(Timing, "performing early layout because commit time, %f, exceeded initial layout interval %f", timeSinceStart, defaultTimedDelay);
-                    [self _timedLayout: nil];
-                }
-                else {
-                    NSTimeInterval timedDelay = defaultTimedDelay - timeSinceStart;
-                    
-                    LOG(Timing, "registering delayed layout after %f seconds, time since start %f", timedDelay, timeSinceStart);
-                    [self _scheduleLayout: timedDelay];
-                }
-            }
-            return;
-        }
-
-        case WebFrameStateProvisional:
-        case WebFrameStateComplete:
-        case WebFrameStateLayoutAcceptable:
-            return;
-    }
-    ASSERT_NOT_REACHED();
-}
-
-- (void)_makeDocumentView
-{
-    NSView <WebDocumentView> *documentView = [_private->webFrameView _makeDocumentViewForDataSource:_private->dataSource];
-    if (!documentView) {
-        return;
-    }
-
-    // FIXME: We could save work and not do this for a top-level view that is not a WebHTMLView.
-    WebFrameView *v = _private->webFrameView;
-    [_private->bridge createKHTMLViewWithNSView:documentView marginWidth:[v _marginWidth] marginHeight:[v _marginHeight]];
-    [_private->bridge installInFrame:[v _scrollView]];
-
-    // Call setDataSource on the document view after it has been placed in the view hierarchy.
-    // This what we for the top-level view, so should do this for views in subframes as well.
-    [documentView setDataSource:_private->dataSource];
-}
-
-- (void)_transitionToCommitted: (NSDictionary *)pageCache
-{
-    ASSERT([self webView] != nil);
-
-    switch ([self _state]) {
-        case WebFrameStateProvisional:
-        {
-	    [[[[self frameView] _scrollView] contentView] setCopiesOnScroll:YES];
-
-            WebFrameLoadType loadType = [self _loadType];
-            if (loadType == WebFrameLoadTypeForward ||
-                loadType == WebFrameLoadTypeBack ||
-                loadType == WebFrameLoadTypeIndexedBackForward)
-            {
-                // Once committed, we want to use current item for saving DocState, and
-                // the provisional item for restoring state.
-                // Note previousItem must be set before we close the URL, which will
-                // happen when the data source is made non-provisional below
-                [_private setPreviousItem:[_private currentItem]];
-                ASSERT([_private provisionalItem]);
-                [_private setCurrentItem:[_private provisionalItem]];
-                [_private setProvisionalItem:nil];
-            }
-
-            // Set the committed data source on the frame.
-            [self _setDataSource:_private->provisionalDataSource];
-                
-            [self _setProvisionalDataSource: nil];
-
-            [self _setState: WebFrameStateCommittedPage];
-        
-            // Handle adding the URL to the back/forward list.
-            WebDataSource *ds = [self dataSource];
-            WebHistoryItem *entry = nil;
-            NSString *ptitle = [ds pageTitle];
-
-            switch (loadType) {
-            case WebFrameLoadTypeForward:
-            case WebFrameLoadTypeBack:
-            case WebFrameLoadTypeIndexedBackForward:
-                if ([[self webView] backForwardList]) {
-                    // Must grab the current scroll position before disturbing it
-                    [self _saveScrollPositionToItem:[_private previousItem]];
-                    
-                    // Create a document view for this document, or used the cached view.
-                    if (pageCache){
-                        NSView <WebDocumentView> *cachedView = [pageCache objectForKey: WebPageCacheDocumentViewKey];
-                        ASSERT(cachedView != nil);
-                        [[self frameView] _setDocumentView: cachedView];
-                    }
-                    else
-                        [self _makeDocumentView];
-                        
-                    // FIXME - I'm not sure this call does anything.  Should be dealt with as
-                    // part of 3024377
-                    [self _restoreScrollPosition];
-                }
-                break;
-
-            case WebFrameLoadTypeReload:
-            case WebFrameLoadTypeSame:
-            {
-                WebHistoryItem *currItem = [_private currentItem];
-                LOG(PageCache, "Clearing back/forward cache, %@\n", [currItem URL]);
-                // FIXME: rjw sez this cache clearing is no longer needed
-                [currItem setHasPageCache:NO];
-                if (loadType == WebFrameLoadTypeReload) {
-                    [self _saveScrollPositionToItem:currItem];
-                }
-                // Update the last visited time.  Mostly interesting for URL autocompletion
-                // statistics.
-                NSURL *URL = [[[ds _originalRequest] URL] _webkit_canonicalize];
-                WebHistoryItem *oldItem = [[WebHistory optionalSharedHistory] itemForURL:URL];
-                if (oldItem) {
-                    [oldItem _setLastVisitedTimeInterval:[NSDate timeIntervalSinceReferenceDate]];
-                }
-                [self _makeDocumentView];
-                break;
-            }
-
-            // FIXME - just get rid of this case, and merge WebFrameLoadTypeReloadAllowingStaleData with the above case
-            case WebFrameLoadTypeReloadAllowingStaleData:
-                [self _makeDocumentView];
-                break;
-                
-            case WebFrameLoadTypeStandard:
-                if (![ds _isClientRedirect]) {
-                    // Add item to history.
-		    NSURL *URL = [[[ds _originalRequest] URL] _webkit_canonicalize];
-		    if (![URL _web_isEmpty] && ![WebDataProtocol _webIsDataProtocolURL:URL] ){
-			entry = [[WebHistory optionalSharedHistory] addItemForURL:URL];
-			if (ptitle)
-			    [entry setTitle: ptitle];
-                        [self _addBackForwardItemClippedAtTarget:YES];
-		    }
-
-                } else {
-                    // update the URL in the BF list that we made before the redirect
-                    [[_private currentItem] setURL:[[ds request] URL]];
-                }
-                [self _makeDocumentView];
-                break;
-                
-            case WebFrameLoadTypeOnLoadEvent:
-            case WebFrameLoadTypeInternal:
-                // Add an item to the item tree for this frame
-                ASSERT(![ds _isClientRedirect]);
-                WebHistoryItem *parentItem = [[self parentFrame]->_private currentItem];
-                // The only case where parentItem==nil should be when a parent frame loaded an
-                // empty URL, which doesn't set up a current item in that parent.
-                if (parentItem) {
-                    [parentItem addChildItem:[self _createItem: YES]];
-                }
-                [self _makeDocumentView];
-                break;
-
-            // FIXME Remove this check when dummy ds is removed.  An exception should be thrown
-            // if we're in the WebFrameLoadTypeUninitialized state.
-            default:
-                ASSERT_NOT_REACHED();
-            }
-
-            
-            // Tell the client we've committed this URL.
-            ASSERT([[self frameView] documentView] != nil);
-            [[self webView] _didCommitLoadForFrame: self];
-            [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView didCommitLoadForFrame:self];
-            
-            // If we have a title let the WebView know about it.
-            if (ptitle) {
-                [entry setTitle:ptitle];
-                [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                                                           didReceiveTitle:ptitle
-                                                                  forFrame:self];
-            }
-            break;
-        }
-        
-        case WebFrameStateCommittedPage:
-        case WebFrameStateLayoutAcceptable:
-        case WebFrameStateComplete:
-        default:
-        {
-            ASSERT_NOT_REACHED();
-        }
-    }
-
-
-    if (pageCache){
-        [[self dataSource] _setPrimaryLoadComplete: YES];
-        [self _isLoadComplete];
-    }
-}
-
-- (BOOL)_canCachePage
-{
-    return [[[self webView] backForwardList] _usesPageCache];
-}
-
-- (void)_purgePageCache
-{
-    // This method implements the rule for purging the page cache.
-    unsigned sizeLimit = [[[self webView] backForwardList] pageCacheSize];
-    unsigned pagesCached = 0;
-    WebBackForwardList *backForwardList = [[self webView] backForwardList];
-    NSArray *backList = [backForwardList backListWithLimit: 999999];
-    WebHistoryItem *oldestItem = nil;
-    
-    unsigned i;
-    for (i = 0; i < [backList count]; i++){
-        WebHistoryItem *item = [backList objectAtIndex: i];
-        if ([item hasPageCache]){
-            if (oldestItem == nil)
-                oldestItem = item;
-            pagesCached++;
-        }
-    }
-    
-    // Snapback items are never directly purged here.
-    if (pagesCached >= sizeLimit && ![oldestItem alwaysAttemptToUsePageCache]){
-        LOG(PageCache, "Purging back/forward cache, %@\n", [oldestItem URL]);
-        [oldestItem setHasPageCache: NO];
-    }
-}
-
-- (WebFrameState)_state
-{
-    return _private->state;
-}
-
-static CFAbsoluteTime _timeOfLastCompletedLoad;
-+ (CFAbsoluteTime)_timeOfLastCompletedLoad
-{
-    return _timeOfLastCompletedLoad;
-}
-
-- (void)_createPageCacheForItem:(WebHistoryItem *)item
-{
-    NSMutableDictionary *pageCache;
-
-    [item setHasPageCache: YES];
-    pageCache = [item pageCache];
-    [[self dataSource] _setStoredInPageCache: YES];
-    [pageCache setObject: [NSDate date]  forKey: WebPageCacheEntryDateKey];
-    [pageCache setObject: [self dataSource] forKey: WebPageCacheDataSourceKey];
-    [pageCache setObject: [[self frameView] documentView] forKey: WebPageCacheDocumentViewKey];
-    [_private->bridge saveDocumentToPageCache];
-}
-
-- (void)_setState: (WebFrameState)newState
-{
-    LOG(Loading, "%@:  transition from %s to %s", [self name], stateNames[_private->state], stateNames[newState]);
-    if ([self webView])
-        LOG(Timing, "%@:  transition from %s to %s, %f seconds since start of document load", [self name], stateNames[_private->state], stateNames[newState], CFAbsoluteTimeGetCurrent() - [[[[self webView] mainFrame] dataSource] _loadingStartedTime]);
-    
-    if (newState == WebFrameStateComplete && self == [[self webView] mainFrame]){
-        LOG(DocumentLoad, "completed %@ (%f seconds)", [[[self dataSource] request] URL], CFAbsoluteTimeGetCurrent() - [[self dataSource] _loadingStartedTime]);
-    }
-    
-    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
-                    [NSNumber numberWithInt:_private->state], WebPreviousFrameState,
-                    [NSNumber numberWithInt:newState], WebCurrentFrameState, nil];
-                    
-    [[NSNotificationCenter defaultCenter] postNotificationName:WebFrameStateChangedNotification object:self userInfo:userInfo];
-    
-    _private->state = newState;
-    
-    if (_private->state == WebFrameStateProvisional) {
-	[_private->bridge provisionalLoadStarted];
-    
-        // FIXME: This is OK as long as no one resizes the window,
-        // but in the case where someone does, it means garbage outside
-        // the occupied part of the scroll view.
-        [[[self frameView] _scrollView] setDrawsBackground:NO];
-
-        // Cache the page, if possible.
-        // Don't write to the cache if in the middle of a redirect, since we will want to
-        // store the final page we end up on.
-        // No point writing to the cache on a reload or loadSame, since we will just write
-        // over it again when we leave that page.
-        WebHistoryItem *item = [_private currentItem];
-        WebFrameLoadType loadType = [self _loadType];
-        if ([self _canCachePage]
-            && [_private->bridge canCachePage]
-            && item
-            && !_private->quickRedirectComing
-            && loadType != WebFrameLoadTypeReload 
-            && loadType != WebFrameLoadTypeReloadAllowingStaleData
-            && loadType != WebFrameLoadTypeSame
-            && ![[self dataSource] isLoading]
-            && ![[self dataSource] _isStopping]
-            && [[[self dataSource] representation] isKindOfClass: [WebHTMLRepresentation class]])
-        {
-            if (![item pageCache]){
-                LOG(PageCache, "Saving page to back/forward cache, %@\n", [[self dataSource] _URL]);
-
-                // Add the items to this page's cache.
-                [self _createPageCacheForItem:item];
-
-                // See if any page caches need to be purged after the addition of this
-                // new page cache.
-                [self _purgePageCache];
-            }
-        }
-        else {
-            LOG(PageCache, "NOT saving page to back/forward cache, %@\n", [[self dataSource] _URL]);
-        }
-    }
-    
-    if (_private->state == WebFrameStateComplete) {
-        NSScrollView *sv = [[self frameView] _scrollView];
-        [sv setDrawsBackground:YES];
-        NSTimer *timer = _private->scheduledLayoutTimer;
-        _private->scheduledLayoutTimer = nil;
-        [_private setPreviousItem:nil];
-        _timeOfLastCompletedLoad = CFAbsoluteTimeGetCurrent();
-        [timer invalidate];
-        [timer release];
-    }
-}
-
-// Called after we send an openURL:... down to WebCore.
-- (void)_opened
-{
-    if ([[self dataSource] _loadingFromPageCache]){
-        // Force a layout to update view size and thereby update scrollbars.
-        NSView <WebDocumentView> *view = [[self frameView] documentView];
-        if ([view isKindOfClass:[WebHTMLView class]]) {
-            [(WebHTMLView *)view setNeedsToApplyStyles:YES];
-        }
-        [view setNeedsLayout: YES];
-        [view layout];
-        [self _restoreScrollPosition];
-        
-        NSArray *responses = [[self dataSource] _responses];
-        NSURLResponse *response;
-        int i, count = [responses count];
-        for (i = 0; i < count; i++){
-            response = [responses objectAtIndex: i];
-            [_private->bridge objectLoadedFromCacheWithURL:[response URL]
-                    response: response
-                    size: [response expectedContentLength]];
-        }
-        
-        // Release the resources kept in the page cache.  They will be
-        // reset when we leave this page.  The core side of the page cache
-        // will have already been invalidated by the bridge to prevent
-        // premature release.
-        [[_private currentItem] setHasPageCache: NO];
-    }
-}
-
-- (void)_isLoadComplete
-{
-    ASSERT([self webView] != nil);
-
-    switch ([self _state]) {
-        case WebFrameStateProvisional:
-        {
-            WebDataSource *pd = [self provisionalDataSource];
-            
-            LOG(Loading, "%@:  checking complete in WebFrameStateProvisional", [self name]);
-            // If we've received any errors we may be stuck in the provisional state and actually
-            // complete.
-            if ([pd _mainDocumentError]) {
-                // Check all children first.
-                LOG(Loading, "%@:  checking complete, current state WebFrameStateProvisional", [self name]);
-                [self _resetBackForwardListToCurrent];
-                if (![pd isLoading]) {
-                    LOG(Loading, "%@:  checking complete in WebFrameStateProvisional, load done", [self name]);
-
-                    [[self webView] _didFailProvisionalLoadWithError:[pd _mainDocumentError] forFrame:self];
-                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                                          didFailProvisionalLoadWithError:[pd _mainDocumentError]
-                                                                 forFrame:self];
-
-                    // We know the provisional data source didn't cut the muster, release it.
-                    [_private->provisionalDataSource _stopLoading];
-                    [self _setProvisionalDataSource:nil];
-                    
-                    [self _setState:WebFrameStateComplete];
-                    return;
-                }
-            }
-            return;
-        }
-        
-        case WebFrameStateCommittedPage:
-        case WebFrameStateLayoutAcceptable:
-        {
-            WebDataSource *ds = [self dataSource];
-            
-            //LOG(Loading, "%@:  checking complete, current state WEBFRAMESTATE_COMMITTED", [self name]);
-            if (![ds isLoading]) {
-                WebFrameView *thisView = [self frameView];
-                NSView <WebDocumentView> *thisDocumentView = [thisView documentView];
-                ASSERT(thisDocumentView != nil);
-
-                // FIXME: need to avoid doing this in the non-HTML case or the bridge may assert.
-                // Should instead make sure the bridge/part is in the proper state even for
-                // non-HTML content, or make a call to the document and let it deal with the bridge.
-
-                [self _setState:WebFrameStateComplete];
-                if ([ds _isDocumentHTML]) {
-                    [_private->bridge end];
-                }
-
-                // FIXME: Is this subsequent work important if we already navigated away?
-                // Maybe there are bugs because of that, or extra work we can skip because
-                // the new page is ready.
-
-                // Unfortunately we have to get our parent to adjust the frames in this
-                // frameset so this frame's geometry is set correctly.  This should
-                // be a reasonably inexpensive operation.
-                WebDataSource *parentDS = [[self parentFrame] dataSource];
-                if ([[parentDS _bridge] isFrameSet]){
-                    WebFrameView *parentWebFrameView = [[self parentFrame] frameView];
-                    if ([parentDS _isDocumentHTML])
-                        [(WebHTMLView *)[parentWebFrameView documentView] _adjustFrames];
-                }
-
-                // Tell the just loaded document to layout.  This may be necessary
-                // for non-html content that needs a layout message.
-                if (!([[self dataSource] _isDocumentHTML])) {
-                    [thisDocumentView setNeedsLayout:YES];
-                    [thisDocumentView layout];
-                    [thisDocumentView setNeedsDisplay:YES];
-                }
-                 
-                // If the user had a scroll point scroll to it.  This will override
-                // the anchor point.  After much discussion it was decided by folks
-                // that the user scroll point should override the anchor point.
-                if ([[self webView] backForwardList]) {
-                    switch ([self _loadType]) {
-                    case WebFrameLoadTypeForward:
-                    case WebFrameLoadTypeBack:
-                    case WebFrameLoadTypeIndexedBackForward:
-                    case WebFrameLoadTypeReload:
-                        [self _restoreScrollPosition];
-                        break;
-
-                    case WebFrameLoadTypeOnLoadEvent:
-                    case WebFrameLoadTypeStandard:
-                    case WebFrameLoadTypeInternal:
-                    case WebFrameLoadTypeReloadAllowingStaleData:
-                    case WebFrameLoadTypeSame:
-                        // Do nothing.
-                        break;
-
-                    default:
-                        ASSERT_NOT_REACHED();
-                        break;
-                    }
-                }
-
-                [[self webView] _progressCompleted];
-                
-                if ([ds _mainDocumentError]) {
-                    [[self webView] _didFailLoadWithError:[ds _mainDocumentError] forFrame:self];
-                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                                                     didFailLoadWithError:[ds _mainDocumentError]
-                                                                 forFrame:self];
-                } else {
-                    [[self webView] _didFinishLoadForFrame:self];
-                    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                                                    didFinishLoadForFrame:self];
-                }
- 
-                return;
-            }
-            // A resource was loaded, but the entire frame isn't complete.  Schedule a
-            // layout.
-            else {
-                if ([self _state] == WebFrameStateLayoutAcceptable) {
-                    BOOL resourceTimedDelayEnabled = [[WebPreferences standardPreferences] _resourceTimedLayoutEnabled];
-                    if (resourceTimedDelayEnabled) {
-                        NSTimeInterval timedDelay = [[WebPreferences standardPreferences] _resourceTimedLayoutDelay];
-                        [self _scheduleLayout:timedDelay];
-                    }
-                }
-            }
-            return;
-        }
-        
-        case WebFrameStateComplete:
-        {
-            LOG(Loading, "%@:  checking complete, current state WebFrameStateComplete", [self name]);
-            // Even if already complete, we might have set a previous item on a frame that
-            // didn't do any data loading on the past transaction.  Make sure to clear these out.
-            [_private setPreviousItem:nil];
-            return;
-        }
-    }
-    
-    // Yikes!  Serious horkage.
-    ASSERT_NOT_REACHED();
-}
-
-+ (void)_recursiveCheckCompleteFromFrame: (WebFrame *)fromFrame
-{
-    int i, count;
-    NSArray *childFrames;
-    
-    childFrames = [fromFrame childFrames];
-    count = [childFrames count];
-    for (i = 0; i < count; i++) {
-        WebFrame *childFrame;
-        
-        childFrame = [childFrames objectAtIndex: i];
-        [WebFrame _recursiveCheckCompleteFromFrame: childFrame];
-        [childFrame _isLoadComplete];
-    }
-    [fromFrame _isLoadComplete];
-}
-
-// Called every time a resource is completely loaded, or an error is received.
-- (void)_checkLoadComplete
-{
-    ASSERT([self webView] != nil);
-
-    // Now walk the frame tree to see if any frame that may have initiated a load is done.
-    [WebFrame _recursiveCheckCompleteFromFrame: [[self webView] mainFrame]];
-}
-
-- (WebBridge *)_bridge
-{
-    return _private->bridge;
-}
-
-- (void)_handleUnimplementablePolicyWithErrorCode:(int)code forURL:(NSURL *)URL
-{
-    NSError *error = [NSError _webKitErrorWithDomain:WebKitErrorDomain code:code URL:URL];
-    WebView *wv = [self webView];
-    [[wv _policyDelegateForwarder] webView:wv unableToImplementPolicyWithError:error frame:self];    
-}
-
-- (void)_clearProvisionalDataSource
-{
-    [self _setProvisionalDataSource:nil];
-}
-
-// helper method that determines whether the subframes described by the item's subitems
-// match our own current frameset
-- (BOOL)_childFramesMatchItem:(WebHistoryItem *)item
-{
-    NSArray *childItems = [item children];
-    int numChildItems = childItems ? [childItems count] : 0;
-    int numChildFrames = _private->children ? [_private->children count] : 0;
-    if (numChildFrames != numChildItems) {
-        return NO;
-    } else {
-        int i;
-        for (i = 0; i < numChildItems; i++) {
-            NSString *itemTargetName = [[childItems objectAtIndex:i] target];
-            //Search recursive here?
-            if (![self _immediateChildFrameNamed:itemTargetName]) {
-                return NO; // couldn't match the i'th itemTarget
-            }
-        }
-        return YES; // found matches for all itemTargets
-    }
-}
-
-- (BOOL)_shouldReloadForCurrent:(NSURL *)currentURL andDestination:(NSURL *)destinationURL
-{
-    return !(([currentURL fragment] || [destinationURL fragment]) &&
-    [[currentURL _webkit_URLByRemovingFragment] isEqual: [destinationURL _webkit_URLByRemovingFragment]]);
-}
-
-// Walk the frame tree and ensure that the URLs match the URLs in the item.
-- (BOOL)_URLsMatchItem:(WebHistoryItem *)item
-{
-    NSURL *currentURL = [[[self dataSource] request] URL];
-
-    if (![[[item URL] _webkit_URLByRemovingFragment] isEqual:[currentURL _webkit_URLByRemovingFragment]])
-        return NO;
-    
-    NSArray *childItems = [item children];
-    WebHistoryItem *childItem;
-    WebFrame *childFrame;
-    int i, count = [childItems count];
-    for (i = 0; i < count; i++){
-        childItem = [childItems objectAtIndex:i];
-        childFrame = [self _immediateChildFrameNamed:[childItem target]];
-        if (![childFrame _URLsMatchItem: childItem])
-            return NO;
-    }
-    
-    return YES;
-}
-
-// loads content into this frame, as specified by item
-- (void)_loadItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)loadType
-{
-    NSURL *itemURL = [item URL];
-    NSURL *itemOriginalURL = [NSURL _web_URLWithDataAsString:[item originalURLString]];
-    NSURL *currentURL = [[[self dataSource] request] URL];
-    NSData *formData = [item formData];
-
-    // Are we navigating to an anchor within the page?
-    // Note if we have child frames we do a real reload, since the child frames might not
-    // match our current frame structure, or they might not have the right content.  We could
-    // check for all that as an additional optimization.
-    // We also do not do anchor-style navigation if we're posting a form.
-    
-    // FIXME: These checks don't match the ones in _loadURL:referrer:loadType:target:triggeringEvent:isFormSubmission:
-    // Perhaps they should.
-    if (!formData && ![self _shouldReloadForCurrent:itemURL andDestination:currentURL] && [self _URLsMatchItem:item] )
-    {
-#if 0
-        // FIXME:  We need to normalize the code paths for anchor navigation.  Something
-        // like the following line of code should be done, but also accounting for correct
-        // updates to the back/forward list and scroll position.
-        // rjw 4/9/03 See 3223929.
-        [self _loadURL:itemURL referrer:[[[self dataSource] request] HTTPReferrer] loadType:loadType target:nil triggeringEvent:nil form:nil formValues:nil];
-#endif
-        // must do this maintenance here, since we don't go through a real page reload
-        [self _saveScrollPositionToItem:[_private currentItem]];
-        // FIXME: form state might want to be saved here too
-
-        // FIXME: Perhaps we can use scrollToAnchorWithURL here instead and remove the older scrollToAnchor:?
-        NSString *anchor = [[item URLString] _web_URLFragment];
-        if (anchor)
-            [[_private->dataSource _bridge] scrollToAnchor: anchor];
-    
-        // must do this maintenance here, since we don't go through a real page reload
-        [_private setCurrentItem:item];
-        [self _restoreScrollPosition];
-
-        // Fake the URL change by updating the datasource's request.  This will no longer
-        // be necessary if we do the better fix described above.
-        NSMutableURLRequest *hackedRequest = [[[self dataSource] request] mutableCopy];
-        [hackedRequest setURL: itemURL];
-        [[self dataSource] __setRequest: [[hackedRequest copy] autorelease]];
-        [hackedRequest release];
-        
-        [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                               didChangeLocationWithinPageForFrame:self];
-    } else {
-        // Remember this item so we can traverse any child items as child frames load
-        [_private setProvisionalItem:item];
-
-        WebDataSource *newDataSource;
-        BOOL inPageCache = NO;
-        
-        // Check if we'll be using the page cache.  We only use the page cache
-        // if one exists and it is less than _backForwardCacheExpirationInterval
-        // seconds old.  If the cache is expired it gets flushed here.
-        if ([item hasPageCache]){
-            NSDictionary *pageCache = [item pageCache];
-            NSDate *cacheDate = [pageCache objectForKey: WebPageCacheEntryDateKey];
-            NSTimeInterval delta = [[NSDate date] timeIntervalSinceDate: cacheDate];
-
-            if (delta <= [[WebPreferences standardPreferences] _backForwardCacheExpirationInterval]){
-                newDataSource = [pageCache objectForKey: WebPageCacheDataSourceKey];
-                [self _loadDataSource:newDataSource withLoadType:loadType formState:nil];   
-                inPageCache = YES;
-            }         
-            else {
-                LOG (PageCache, "Not restoring page from back/forward cache because cache entry has expired, %@ (%3.5f > %3.5f seconds)\n", [[_private provisionalItem] URL], delta, [[WebPreferences standardPreferences] _backForwardCacheExpirationInterval]);
-                [item setHasPageCache: NO];
-            }
-        }
-        
-        if (!inPageCache) {
-            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:itemURL];
-            [self _addExtraFieldsToRequest:request alwaysFromRequest: (formData != nil)?YES:NO];
-
-            // If this was a repost that failed the page cache, we might try to repost the form.
-            NSDictionary *action;
-            if (formData) {
-                [request setHTTPMethod:@"POST"];
-                [request setHTTPBody:formData];
-                [request setHTTPContentType:[item formContentType]];
-                [request setHTTPReferrer:[item formReferrer]];
-
-                // Slight hack to test if the WF cache contains the page we're going to.  We want
-                // to know this before talking to the policy delegate, since it affects whether we
-                // show the DoYouReallyWantToRepost nag.
-                //
-                // This trick has a small bug (3123893) where we might find a cache hit, but then
-                // have the item vanish when we try to use it in the ensuing nav.  This should be
-                // extremely rare, but in that case the user will get an error on the navigation.
-                [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
-                NSURLResponse *synchResponse = nil;
-                [NSURLConnection sendSynchronousRequest:request returningResponse:&synchResponse error:nil];
-                if (synchResponse == nil) { 
-                    // Not in WF cache
-                    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
-                    action = [self _actionInformationForNavigationType:WebNavigationTypeFormResubmitted event:nil originalURL:itemURL];
-                } else {
-                    // We can use the cache, don't use navType=resubmit
-                    action = [self _actionInformationForLoadType:loadType isFormSubmission:NO event:nil originalURL:itemURL];
-                }
-            } else {
-                switch (loadType) {
-                    case WebFrameLoadTypeReload:
-                        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
-                        break;
-                    case WebFrameLoadTypeBack:
-                    case WebFrameLoadTypeForward:
-                    case WebFrameLoadTypeIndexedBackForward:
-			if (![[itemURL scheme] isEqual:@"https"]) {
-			    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
-			}
-                        break;
-                    case WebFrameLoadTypeOnLoadEvent:
-                    case WebFrameLoadTypeStandard:
-                    case WebFrameLoadTypeInternal:
-                        // no-op: leave as protocol default
-                        // FIXME:  I wonder if we ever hit this case
-                        break;
-                    case WebFrameLoadTypeSame:
-                    case WebFrameLoadTypeReloadAllowingStaleData:
-                    default:
-                        ASSERT_NOT_REACHED();
-                }
-
-                action = [self _actionInformationForLoadType:loadType isFormSubmission:NO event:nil originalURL:itemOriginalURL];
-            }
-
-            [self _loadRequest:request triggeringAction:action loadType:loadType formState:nil];
-            [request release];
-        }
-    }
-}
-
-// The general idea here is to traverse the frame tree and the item tree in parallel,
-// tracking whether each frame already has the content the item requests.  If there is
-// a match (by URL), we just restore scroll position and recurse.  Otherwise we must
-// reload that frame, and all its kids.
-- (void)_recursiveGoToItem:(WebHistoryItem *)item fromItem:(WebHistoryItem *)fromItem withLoadType:(WebFrameLoadType)type
-{
-    NSURL *itemURL = [item URL];
-    NSURL *currentURL = [[[self dataSource] request] URL];
-
-    // Always reload the target frame of the item we're going to.  This ensures that we will
-    // do -some- load for the transition, which means a proper notification will be posted
-    // to the app.
-    // The exact URL has to match, including fragment.  We want to go through the _load
-    // method, even if to do a within-page navigation.
-    // The current frame tree and the frame tree snapshot in the item have to match.
-    if (![item isTargetItem] &&
-        [itemURL isEqual:currentURL] &&
-	(([self name] == nil && [item target] == nil) ||[[self name] isEqualToString:[item target]]) &&
-        [self _childFramesMatchItem:item])
-    {
-        // This content is good, so leave it alone and look for children that need reloading
-
-        // Save form state (works from currentItem, since prevItem is nil)
-        ASSERT(![_private previousItem]);
-        [_private->bridge saveDocumentState];
-        [self _saveScrollPositionToItem:[_private currentItem]];
-        
-        [_private setCurrentItem:item];
-
-        // Restore form state (works from currentItem)
-        [_private->bridge restoreDocumentState];
-        // Restore the scroll position (taken in favor of going back to the anchor)
-        [self _restoreScrollPosition];
-        
-        NSArray *childItems = [item children];
-        int numChildItems = childItems ? [childItems count] : 0;
-        int i;
-        for (i = numChildItems - 1; i >= 0; i--) {
-            WebHistoryItem *childItem = [childItems objectAtIndex:i];
-            NSString *childName = [childItem target];
-            WebHistoryItem *fromChildItem = [fromItem childItemWithName:childName];
-            ASSERT(fromChildItem || [fromItem isTargetItem]);
-            WebFrame *childFrame = [self _immediateChildFrameNamed:childName];
-            ASSERT(childFrame);
-            [childFrame _recursiveGoToItem:childItem fromItem:fromChildItem withLoadType:type];
-        }
-    } else {
-        // We need to reload the content
-        [self _loadItem:item withLoadType:type];
-    }
-}
-
-// Main funnel for navigating to a previous location (back/forward, non-search snap-back)
-// This includes recursion to handle loading into framesets properly
-- (void)_goToItem: (WebHistoryItem *)item withLoadType: (WebFrameLoadType)type
-{
-    ASSERT(!_private->parent);
-    WebBackForwardList *backForwardList = [[self webView] backForwardList];
-    WebHistoryItem *currItem = [backForwardList currentItem];
-    // Set the BF cursor before commit, which lets the user quickly click back/forward again.
-    // - plus, it only makes sense for the top level of the operation through the frametree,
-    // as opposed to happening for some/one of the page commits that might happen soon
-    [backForwardList goToItem:item];
-    [self _recursiveGoToItem:item fromItem:currItem withLoadType:type];
-}
-
-- (void)_loadRequest:(NSURLRequest *)request triggeringAction:(NSDictionary *)action loadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState
-{
-    WebDataSource *newDataSource = [[WebDataSource alloc] initWithRequest:request];
-    [newDataSource _setTriggeringAction:action];
-
-    [newDataSource _setOverrideEncoding:[[self dataSource] _overrideEncoding]];
-
-    [self _loadDataSource:newDataSource withLoadType:loadType formState:formState];
-
-    [newDataSource release];
-}
-
--(NSDictionary *)_actionInformationForNavigationType:(WebNavigationType)navigationType event:(NSEvent *)event originalURL:(NSURL *)URL
-{
-    switch ([event type]) {
-        case NSLeftMouseDown:
-        case NSRightMouseDown:
-        case NSOtherMouseDown:
-        case NSLeftMouseUp:
-        case NSRightMouseUp:
-        case NSOtherMouseUp:
-        {
-            NSView *topViewInEventWindow = [[event window] contentView];
-            NSView *viewContainingPoint = [topViewInEventWindow hitTest:[topViewInEventWindow convertPoint:[event locationInWindow] fromView:nil]];
-            while (viewContainingPoint != nil) {
-                if ([viewContainingPoint isKindOfClass:[WebHTMLView class]]) {
-                    break;
-                }
-                viewContainingPoint = [viewContainingPoint superview];
-            }
-            if (viewContainingPoint != nil) {
-                NSPoint point = [viewContainingPoint convertPoint:[event locationInWindow] fromView:nil];
-                NSDictionary *elementInfo = [(WebHTMLView *)viewContainingPoint _elementAtPoint:point];
-        
-                return [NSDictionary dictionaryWithObjectsAndKeys:
-                    [NSNumber numberWithInt:navigationType], WebActionNavigationTypeKey,
-                    elementInfo, WebActionElementKey,
-                    [NSNumber numberWithInt:[event buttonNumber]], WebActionButtonKey,
-                    [NSNumber numberWithInt:[event modifierFlags]], WebActionModifierFlagsKey,
-                    URL, WebActionOriginalURLKey,
-                    nil];
-            }
-        }
-        
-        // fall through
-        
-        default:
-            return [NSDictionary dictionaryWithObjectsAndKeys:
-                [NSNumber numberWithInt:navigationType], WebActionNavigationTypeKey,
-                URL, WebActionOriginalURLKey,
-                nil];
-    }
-}
-
--(NSDictionary *)_actionInformationForLoadType:(WebFrameLoadType)loadType isFormSubmission:(BOOL)isFormSubmission event:(NSEvent *)event originalURL:(NSURL *)URL
-{
-    WebNavigationType navType;
-    if (isFormSubmission) {
-        navType = WebNavigationTypeFormSubmitted;
-    } else if (event == nil) {
-        if (loadType == WebFrameLoadTypeReload) {
-            navType = WebNavigationTypeReload;
-        } else if (loadType == WebFrameLoadTypeForward
-                   || loadType == WebFrameLoadTypeBack
-                   || loadType == WebFrameLoadTypeIndexedBackForward) {
-            navType = WebNavigationTypeBackForward;
-        } else {
-            navType = WebNavigationTypeOther;
-        }
-    } else {
-        navType = WebNavigationTypeLinkClicked;
-    }
-    return [self _actionInformationForNavigationType:navType event:event originalURL:URL];
-}
-
-- (void)_invalidatePendingPolicyDecisionCallingDefaultAction:(BOOL)call
-{
-    [_private->listener _invalidate];
-    [_private->listener release];
-    _private->listener = nil;
-
-    NSURLRequest *request = _private->policyRequest;
-    NSString *frameName = _private->policyFrameName;
-    id target = _private->policyTarget;
-    SEL selector = _private->policySelector;
-    WebFormState *formState = _private->policyFormState;
-
-    _private->policyRequest = nil;
-    _private->policyFrameName = nil;
-    _private->policyTarget = nil;
-    _private->policySelector = nil;
-    _private->policyFormState = nil;
-
-    if (call) {
-	if (frameName) {
-	    [target performSelector:selector withObject:nil withObject:nil withObject:nil];
-	} else {
-	    [target performSelector:selector withObject:nil withObject:nil];
-	}
-    }
-
-    [request release];
-    [frameName release];
-    [target release];
-    [formState release];
-}
-
-- (void)_setPolicyDataSource:(WebDataSource *)dataSource
-{
-    [dataSource retain];
-    [_private->policyDataSource release];
-    _private->policyDataSource = dataSource;
-}
-
-- (void)_checkNewWindowPolicyForRequest:(NSURLRequest *)request action:(NSDictionary *)action frameName:(NSString *)frameName formState:(WebFormState *)formState andCall:(id)target withSelector:(SEL)selector
-{
-    WebPolicyDecisionListener *listener = [[WebPolicyDecisionListener alloc]
-        _initWithTarget:self action:@selector(_continueAfterNewWindowPolicy:)];
-
-    _private->policyRequest = [request retain];
-    _private->policyTarget = [target retain];
-    _private->policyFrameName = [frameName retain];
-    _private->policySelector = selector;
-    _private->listener = [listener retain];
-    _private->policyFormState = [formState retain];
-
-    WebView *wv = [self webView];
-    [[wv _policyDelegateForwarder] webView:wv
-            decidePolicyForNewWindowAction:action
-                                   request:request
-                              newFrameName:frameName
-                          decisionListener:listener];
-    
-    [listener release];
-}
-
--(void)_continueAfterNewWindowPolicy:(WebPolicyAction)policy
-{
-    NSURLRequest *request = [[_private->policyRequest retain] autorelease];
-    NSString *frameName = [[_private->policyFrameName retain] autorelease];
-    id target = [[_private->policyTarget retain] autorelease];
-    SEL selector = _private->policySelector;
-    WebFormState *formState = [[_private->policyFormState retain] autorelease];
-
-    // will release _private->policy* objects, hence the above retains
-    [self _invalidatePendingPolicyDecisionCallingDefaultAction:NO];
-
-    BOOL shouldContinue = NO;
-
-    switch (policy) {
-    case WebPolicyIgnore:
-        break;
-    case WebPolicyDownload:
-	// FIXME: should download full request
-        [[self webView] _downloadURL:[request URL]];
-        break;
-    case WebPolicyUse:
-	shouldContinue = YES;
-        break;
-    default:
-	ASSERT_NOT_REACHED();
-    }
-
-    [target performSelector:selector withObject:(shouldContinue ? request : nil) withObject:frameName withObject:formState];
-}
-
-- (void)_checkNavigationPolicyForRequest:(NSURLRequest *)request
-                              dataSource:(WebDataSource *)dataSource
-                               formState:(WebFormState *)formState
-                                 andCall:(id)target
-                            withSelector:(SEL)selector
-{
-    NSDictionary *action = [dataSource _triggeringAction];
-    if (action == nil) {
-        action = [self _actionInformationForNavigationType:WebNavigationTypeOther event:nil originalURL:[request URL]];
-        [dataSource _setTriggeringAction:action];
-    }
-
-    // Don't ask more than once for the same request or if we are loading an empty URL.
-    // This avoids confusion on the part of the client.
-    if ([request isEqual:[dataSource _lastCheckedRequest]] || [[request URL] _web_isEmpty]) {
-        [target performSelector:selector withObject:request withObject:nil];
-        return;
-    }
-
-    [dataSource _setLastCheckedRequest:request];
-
-    WebPolicyDecisionListener *listener = [[WebPolicyDecisionListener alloc] _initWithTarget:self action:@selector(_continueAfterNavigationPolicy:)];
-    
-    _private->policyRequest = [request retain];
-    _private->policyTarget = [target retain];
-    _private->policySelector = selector;
-    _private->listener = [listener retain];
-    _private->policyFormState = [formState retain];
-
-    WebView *wv = [self webView];
-    [[wv _policyDelegateForwarder] webView:wv
-           decidePolicyForNavigationAction:action
-                                   request:request
-                                     frame:self
-                          decisionListener:listener];
-    
-    [listener release];
-}
-
--(void)_continueAfterNavigationPolicy:(WebPolicyAction)policy
-{
-    NSURLRequest *request = [[_private->policyRequest retain] autorelease];
-    id target = [[_private->policyTarget retain] autorelease];
-    SEL selector = _private->policySelector;
-    WebFormState *formState = [[_private->policyFormState retain] autorelease];
-    
-    // will release _private->policy* objects, hence the above retains
-    [self _invalidatePendingPolicyDecisionCallingDefaultAction:NO];
-
-    BOOL shouldContinue = NO;
-
-    switch (policy) {
-    case WebPolicyIgnore:
-        break;
-    case WebPolicyDownload:
-	// FIXME: should download full request
-        [[self webView] _downloadURL:[request URL]];
-        break;
-    case WebPolicyUse:
-        if (![WebView _canHandleRequest:request]) {
-            [self _handleUnimplementablePolicyWithErrorCode:WebKitErrorCannotShowURL forURL:[request URL]];
-        } else {
-            shouldContinue = YES;
-        }
-        break;
-    default:
-	ASSERT_NOT_REACHED();
-    }
-
-    [target performSelector:selector withObject:(shouldContinue ? request : nil) withObject:formState];
-}
-
--(void)_continueFragmentScrollAfterNavigationPolicy:(NSURLRequest *)request formState:(WebFormState *)formState
-{
-    if (!request) {
-        return;
-    }
-
-    NSURL *URL = [request URL];
-    WebDataSource *dataSrc = [self dataSource];
-
-    BOOL isRedirect = _private->quickRedirectComing;
-    LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
-    _private->quickRedirectComing = NO;
-
-    [dataSrc _setURL:URL];
-    if (!isRedirect && ![self _shouldTreatURLAsSameAsCurrent:URL]) {
-        // NB: must happen after _setURL, since we add based on the current request.
-        // Must also happen before we openURL and displace the scroll position, since
-        // adding the BF item will save away scroll state.
-
-        // NB2:  If we were loading a long, slow doc, and the user anchor nav'ed before
-        // it was done, currItem is now set the that slow doc, and prevItem is whatever was
-        // before it.  Adding the b/f item will bump the slow doc down to prevItem, even
-        // though its load is not yet done.  I think this all works out OK, for one because
-        // we have already saved away the scroll and doc state for the long slow load,
-        // but it's not an obvious case.
-        [self _addBackForwardItemClippedAtTarget:NO];
-    }
-
-    [_private->bridge scrollToAnchorWithURL:URL];
-    
-    if (!isRedirect) {
-        // This will clear previousItem from the rest of the frame tree tree that didn't
-        // doing any loading.  We need to make a pass on this now, since for anchor nav
-        // we'll not go through a real load and reach Completed state
-        [self _checkLoadComplete];
-    }
-
-    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                      didChangeLocationWithinPageForFrame:self];
-}
-
-- (void)_addExtraFieldsToRequest:(NSMutableURLRequest *)request alwaysFromRequest: (BOOL)f
-{
-    [request setHTTPUserAgent:[[self webView] userAgentForURL:[request URL]]];
-    
-    // Don't set the cookie policy URL if it's already been set.
-    if ([request HTTPCookiePolicyBaseURL] == nil){
-        if (self == [[self webView] mainFrame] || f) {
-            [request setHTTPCookiePolicyBaseURL:[request URL]];
-        } else {
-            [request setHTTPCookiePolicyBaseURL:[[[[self webView] mainFrame] dataSource] _URL]];
-        }
-    }
-}
-
-
-
--(void)_continueLoadRequestAfterNewWindowPolicy:(NSURLRequest *)request frameName:(NSString *)frameName formState:(WebFormState *)formState
-{
-    if (!request) {
-        return;
-    }
-    
-    WebView *webView = nil;
-    WebView *currentWebView = [self webView];
-    id wd = [currentWebView UIDelegate];
-    if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
-	webView = [wd webView:currentWebView createWebViewWithRequest:nil];
-    else
-        webView = [[WebDefaultUIDelegate sharedUIDelegate] webView:currentWebView createWebViewWithRequest:nil];
-        
-    [webView _setTopLevelFrameName:frameName];
-    [[webView _UIDelegateForwarder] webViewShow:webView];
-    WebFrame *frame = [webView mainFrame];
-
-    [frame _loadRequest:request triggeringAction:nil loadType:WebFrameLoadTypeStandard formState:formState];
-}
-
-
-// main funnel for navigating via callback from WebCore (e.g., clicking a link, redirect)
-- (void)_loadURL:(NSURL *)URL referrer:(NSString *)referrer loadType:(WebFrameLoadType)loadType target:(NSString *)target triggeringEvent:(NSEvent *)event form:(NSObject <WebDOMElement> *)form formValues:(NSDictionary *)values
-{
-    BOOL isFormSubmission = (values != nil);
-
-    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
-    [request setHTTPReferrer:referrer];
-    [self _addExtraFieldsToRequest:request alwaysFromRequest: (event != nil || isFormSubmission)];
-    if (loadType == WebFrameLoadTypeReload) {
-        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
-    }
-
-    // I believe this is never called with LoadSame.  If it is, we probably want to set the cache
-    // policy of LoadFromOrigin, but I didn't test that.
-    ASSERT(loadType != WebFrameLoadTypeSame);
-
-    NSDictionary *action = [self _actionInformationForLoadType:loadType isFormSubmission:isFormSubmission event:event originalURL:URL];
-    WebFormState *formState = nil;
-    if (form && values) {
-        formState = [[WebFormState alloc] initWithForm:form values:values sourceFrame:self];
-    }
-
-    if (target != nil) {
-	WebFrame *targetFrame = [self findFrameNamed:target];
-	if (targetFrame != nil) {
-	    [targetFrame _loadURL:URL referrer:referrer loadType:loadType target:nil triggeringEvent:event form:form formValues:values];
-	} else {
-	    [self _checkNewWindowPolicyForRequest:request
-                                    action:action
-                                 frameName:target
-                                 formState:formState
-                                   andCall:self
-                              withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
-	}
-	[request release];
-	[formState release];
-	return;
-    }
-
-    WebDataSource *oldDataSource = [[self dataSource] retain];
-
-    BOOL sameURL = [self _shouldTreatURLAsSameAsCurrent:URL];
-
-    // Make sure to do scroll to anchor processing even if the URL is
-    // exactly the same so pages with '#' links and DHTML side effects
-    // work properly.
-    if (!isFormSubmission
-        && loadType != WebFrameLoadTypeReload
-        && loadType != WebFrameLoadTypeSame
-        && ![self _shouldReloadForCurrent:URL andDestination:[_private->bridge URL]]
-
-        // We don't want to just scroll if a link from within a
-        // frameset is trying to reload the frameset into _top.
-        && ![_private->bridge isFrameSet]) {
-        
-        // Just do anchor navigation within the existing content.
-        
-        // We don't do this if we are submitting a form, explicitly reloading,
-        // currently displaying a frameset, or if the new URL does not have a fragment.
-        // These rules are based on what KHTML was doing in KHTMLPart::openURL.
-        
-        
-        // FIXME: What about load types other than Standard and Reload?
-
-        [oldDataSource _setTriggeringAction:action];
-        [self _invalidatePendingPolicyDecisionCallingDefaultAction:YES];
-        [self _checkNavigationPolicyForRequest:request
-                                    dataSource:oldDataSource
-                                     formState:formState
-                                       andCall:self
-                                  withSelector:@selector(_continueFragmentScrollAfterNavigationPolicy:formState:)];
-    } else {
-        [self _loadRequest:request triggeringAction:action loadType:loadType formState:formState];
-        if (_private->quickRedirectComing) {
-            LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
-            _private->quickRedirectComing = NO;
-            
-            // need to transfer BF items from the dataSource that we're replacing
-            WebDataSource *newDataSource = [self provisionalDataSource];
-            [newDataSource _setIsClientRedirect:YES];
-            [newDataSource _addBackForwardItems:[oldDataSource _backForwardItems]];
-        } else if (sameURL) {
-            // Example of this case are sites that reload the same URL with a different cookie
-            // driving the generated content, or a master frame with links that drive a target
-            // frame, where the user has clicked on the same link repeatedly.
-            [self _setLoadType:WebFrameLoadTypeSame];
-        }            
-        [request release];
-    }
-
-    [oldDataSource release];
-    [formState release];
-}
-
-- (void)_loadURL:(NSURL *)URL intoChild:(WebFrame *)childFrame
-{
-    WebHistoryItem *parentItem = [_private currentItem];
-    NSArray *childItems = [parentItem children];
-    WebFrameLoadType loadType = [self _loadType];
-    WebFrameLoadType childLoadType = WebFrameLoadTypeInternal;
-    WebHistoryItem *childItem = nil;
-
-    // If we're moving in the backforward list, we might want to replace the content
-    // of this child frame with whatever was there at that point.
-    // Reload will maintain the frame contents, LoadSame will not.
-    if (childItems &&
-        (loadType == WebFrameLoadTypeForward
-         || loadType == WebFrameLoadTypeBack
-         || loadType == WebFrameLoadTypeIndexedBackForward
-         || loadType == WebFrameLoadTypeReload
-         || loadType == WebFrameLoadTypeReloadAllowingStaleData))
-    {
-        childItem = [parentItem childItemWithName:[childFrame name]];
-        if (childItem) {
-	    // Use the original URL to ensure we get all the side-effects, such as
-	    // onLoad handlers, of any redirects that happened. An example of where
-	    // this is needed is Radar 3213556.
-            URL = [NSURL _web_URLWithDataAsString:[childItem originalURLString]];
-            // These behaviors implied by these loadTypes should apply to the child frames
-            childLoadType = loadType;
-
-            if (loadType == WebFrameLoadTypeForward
-                || loadType == WebFrameLoadTypeBack
-                || loadType == WebFrameLoadTypeIndexedBackForward)
-            {
-                // For back/forward, remember this item so we can traverse any child items as child frames load
-                [childFrame->_private setProvisionalItem:childItem];
-            } else {
-                // For reload, just reinstall the current item, since a new child frame was created but we won't be creating a new BF item
-                [childFrame->_private setCurrentItem:childItem];
-            }
-        }
-    }
-
-    // FIXME: is this the right referrer?
-    [childFrame _loadURL:URL referrer:[[self _bridge] referrer] loadType:childLoadType target:nil triggeringEvent:nil form:nil formValues:nil];
-}
-
-- (void)_postWithURL:(NSURL *)URL referrer:(NSString *)referrer target:(NSString *)target data:(NSData *)data contentType:(NSString *)contentType triggeringEvent:(NSEvent *)event form:(NSObject <WebDOMElement> *)form formValues:(NSDictionary *)values
-{
-    // When posting, use the NSURLRequestReloadIgnoringCacheData load flag.
-    // This prevents a potential bug which may cause a page with a form that uses itself
-    // as an action to be returned from the cache without submitting.
-    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
-    [self _addExtraFieldsToRequest:request alwaysFromRequest: YES];
-    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
-    [request setHTTPMethod:@"POST"];
-    [request setHTTPBody:data];
-    [request setHTTPContentType:contentType];
-    [request setHTTPReferrer:referrer];
-
-    NSDictionary *action = [self _actionInformationForLoadType:WebFrameLoadTypeStandard isFormSubmission:YES event:event originalURL:URL];
-    WebFormState *formState = nil;
-    if (form && values) {
-        formState = [[WebFormState alloc] initWithForm:form values:values sourceFrame:self];
-    }
-
-    if (target != nil) {
-	WebFrame *targetFrame = [self findFrameNamed:target];
-
-	if (targetFrame != nil) {
-	    [targetFrame _loadRequest:request triggeringAction:action loadType:WebFrameLoadTypeStandard formState:formState];
-	} else {
-	    [self _checkNewWindowPolicyForRequest:request action:action frameName:target formState:formState andCall:self withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
-	}
-	[request release];
-	[formState release];
-	return;
-    }
-
-    [self _loadRequest:request triggeringAction:action loadType:WebFrameLoadTypeStandard formState:formState];
-
-    [request release];
-    [formState release];
-}
-
-- (void)_clientRedirectedTo:(NSURL *)URL delay:(NSTimeInterval)seconds fireDate:(NSDate *)date lockHistory:(BOOL)lockHistory isJavaScriptFormAction:(BOOL)isJavaScriptFormAction
-{
-    LOG(Redirect, "%@(%p) Client redirect to: %@, [self dataSource] = %p, lockHistory = %d, isJavaScriptFormAction = %d", [self name], self, URL, [self dataSource], (int)lockHistory, (int)isJavaScriptFormAction);
-
-    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                                willPerformClientRedirectToURL:URL
-                                                         delay:seconds
-                                                      fireDate:date
-                                                      forFrame:self];
-    // If a "quick" redirect comes in an, we set a special mode so we treat the next
-    // load as part of the same navigation.
-
-    if (![self dataSource] || isJavaScriptFormAction) {
-        // If we don't have a dataSource, we have no "original" load on which to base a redirect,
-        // so we better just treat the redirect as a normal load.
-        _private->quickRedirectComing = NO;
-        LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
-    } else {
-        _private->quickRedirectComing = lockHistory;
-        LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
-    }
-}
-
-- (void)_clientRedirectCancelled:(BOOL)cancelWithLoadInProgress
-{
-    [[[self webView] _frameLoadDelegateForwarder] webView:_private->webView
-                               didCancelClientRedirectForFrame:self];
-    if (!cancelWithLoadInProgress)
-        _private->quickRedirectComing = NO;
-    LOG(Redirect, "%@(%p) _private->quickRedirectComing = %d", [self name], self, (int)_private->quickRedirectComing);
-}
-
-- (void)_saveScrollPositionToItem:(WebHistoryItem *)item
-{
-    if (item) {
-        NSView *clipView = [[[self frameView] documentView] superview];
-        // we might already be detached when this is called from detachFromParent, in which
-        // case we don't want to override real data earlier gathered with (0,0)
-        if (clipView) {
-            [item setScrollPoint:[clipView bounds].origin];
-        }
-    }
-}
-
-- (void)_restoreScrollPosition
-{
-    ASSERT([_private currentItem]);
-    [[[self frameView] documentView] scrollPoint:[[_private currentItem] scrollPoint]];
-}
-
-- (void)_scrollToTop
-{
-    [[[self frameView] documentView] scrollPoint: NSZeroPoint];
-}
-
-- (void)_textSizeMultiplierChanged
-{
-    NSView <WebDocumentView> *view = [[self frameView] documentView];
-    if ([view conformsToProtocol:@protocol(_web_WebDocumentTextSizing)]) {
-        [(NSView <_web_WebDocumentTextSizing> *)view _web_textSizeMultiplierChanged];
-    }
-
-    [[self childFrames] makeObjectsPerformSelector:@selector(_textSizeMultiplierChanged)];
-}
-
-- (void)_defersCallbacksChanged
-{
-    [[self provisionalDataSource] _defersCallbacksChanged];
-    [[self dataSource] _defersCallbacksChanged];
-}
-
-- (void)_viewWillMoveToHostWindow:(NSWindow *)hostWindow
-{
-    [[[self frameView] documentView] viewWillMoveToHostWindow:hostWindow];
-    [[self childFrames] makeObjectsPerformSelector:@selector(_viewWillMoveToHostWindow:) withObject:hostWindow];
-}
-
-- (void)_viewDidMoveToHostWindow
-{
-    [[[self frameView] documentView] viewDidMoveToHostWindow];
-    [[self childFrames] makeObjectsPerformSelector:@selector(_viewDidMoveToHostWindow)];
-}
-
-- (void)_reloadAllowingStaleDataWithOverrideEncoding:(NSString *)encoding
-{
-    WebDataSource *dataSource = [self dataSource];
-    if (dataSource == nil) {
-        return;
-    }
-
-    NSMutableURLRequest *request = [[dataSource request] mutableCopy];
-    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
-    WebDataSource *newDataSource = [[WebDataSource alloc] initWithRequest:request];
-    [request release];
-    
-    [newDataSource _setOverrideEncoding:encoding];
-
-    [self _loadDataSource:newDataSource withLoadType:WebFrameLoadTypeReloadAllowingStaleData formState:nil];
-    
-    [newDataSource release];
-}
-
-- (void)_addChild:(WebFrame *)child
-{
-    if (_private->children == nil)
-        _private->children = [[NSMutableArray alloc] init];
-    [_private->children addObject:child];
-
-    child->_private->parent = self;
-    [[child _bridge] setParent:_private->bridge];
-    [[child dataSource] _setOverrideEncoding:[[self dataSource] _overrideEncoding]];   
-}
-
-- (void)_removeChild:(WebFrame *)child
-{
-    [_private->children removeObject:child];
-    child->_private->parent = nil;
-}
-
-- (void)_addFramePathToString:(NSMutableString *)path
-{
-    if ([_private->name hasPrefix:@"<!--framePath "]) {
-        // we have a generated name - take the path from our name
-        NSRange ourPathRange = {14, [_private->name length] - 14 - 3};
-        [path appendString:[_private->name substringWithRange:ourPathRange]];
-    } else {
-        // we don't have a generated name - just add our simple name to the end
-        if (_private->parent) {
-            [_private->parent _addFramePathToString:path];
-        }
-        [path appendString:@"/"];
-        if (_private->name) {
-            [path appendString:_private->name];
-        }
-    }
-}
-
-// Generate a repeatable name for a child about to be added to us.  The name must be
-// unique within the frame tree.  The string we generate includes a "path" of names
-// from the root frame down to us.  For this path to be unique, each set of siblings must
-// contribute a unique name to the path, which can't collide with any HTML-assigned names.
-// We generate this path component by index in the child list along with an unlikely frame name.
-- (NSString *)_generateFrameName
-{
-    NSMutableString *path = [NSMutableString stringWithCapacity:256];
-    [path insertString:@"<!--framePath " atIndex:0];
-    [self _addFramePathToString:path];
-    // The new child's path component is all but the 1st char and the last 3 chars
-    [path appendFormat:@"/<!--frame%d-->-->", _private->children ? [_private->children count] : 0];
-    return path;
-}
-
-// If we bailed out of a b/f navigation, we need to set the b/f cursor back to the current
-// item, because we optimistically move it right away at the start of the operation
-- (void)_resetBackForwardListToCurrent {
-    WebFrameLoadType loadType = [self _loadType];
-    if ((loadType == WebFrameLoadTypeForward
-        || loadType == WebFrameLoadTypeBack
-        || loadType == WebFrameLoadTypeIndexedBackForward)
-        && [_private currentItem]
-        && self == [[self webView] mainFrame])
-    {
-        [[[self webView] backForwardList] goToItem:[_private currentItem]];
-    }
-}
-
-- (WebHistoryItem *)_itemForSavingDocState
-{
-    // For a standard page load, we will have a previous item set, which will be used to
-    // store the form state.  However, in some cases we will have no previous item, and
-    // the current item is the right place to save the state.  One example is when we
-    // detach a bunch of frames because we are navigating from a site with frames to
-    // another site.  Another is when saving the frame state of a frame that is not the
-    // target of the current navigation (if we even decide to save with that granularity).
-
-    // Because of previousItem's "masking" of currentItem for this purpose, it's important
-    // that previousItem be cleared at the end of a page transition.  We leverage the
-    // checkLoadComplete recursion to achieve this goal.
-
-    WebHistoryItem *result = [_private previousItem] ? [_private previousItem] : [_private currentItem];
-    return result;
-}
-
-- (WebHistoryItem *)_itemForRestoringDocState
-{
-    switch ([self _loadType]) {
-        case WebFrameLoadTypeReload:
-        case WebFrameLoadTypeReloadAllowingStaleData:
-        case WebFrameLoadTypeSame:
-            // Don't restore any form state on reload or loadSame
-            return nil;
-        case WebFrameLoadTypeBack:
-        case WebFrameLoadTypeForward:
-        case WebFrameLoadTypeIndexedBackForward:
-        case WebFrameLoadTypeInternal:
-        case WebFrameLoadTypeOnLoadEvent:
-        case WebFrameLoadTypeStandard:
-            return [_private currentItem];
-    }
-    ASSERT_NOT_REACHED();
-    return nil;
-}
-
-// Walk the frame tree, telling all frames to save their form state into their current
-// history item.
-- (void)_saveDocumentAndScrollState
-{
-    [_private->bridge saveDocumentState];
-    [self _saveScrollPositionToItem:[_private currentItem]];
-
-    NSArray *frames = [self childFrames];
-    int count = [frames count];
-    int i;
-    for (i = 0; i < count; i++) {
-        [[frames objectAtIndex:i] _saveDocumentAndScrollState];
-    }
-}
-
-// Called after the FormsDelegate is done processing willSubmitForm:
--(void)_continueAfterWillSubmitForm:(WebPolicyAction)policy
-{
-    if (_private->listener) {
-        [_private->listener _invalidate];
-        [_private->listener release];
-        _private->listener = nil;
-    }
-    [_private->provisionalDataSource _startLoading];
-}
-
--(void)_continueLoadRequestAfterNavigationPolicy:(NSURLRequest *)request formState:(WebFormState *)formState
-{
-    ASSERT(_private->policyDataSource);
-    
-    if (!request) {
-        [self _setPolicyDataSource:nil];
-        return;
-    }
-
-    WebFrameLoadType loadType = _private->policyLoadType;
-    
-    [self stopLoading];
-    [self _setLoadType:loadType];
-    [self _setProvisionalDataSource:_private->policyDataSource];
-
-    [self _setPolicyDataSource:nil];
-    
-    // We tell the documentView provisionalDataSourceChanged:
-    // once it has been created by the WebView.
-    
-    [self _setState: WebFrameStateProvisional];
-    
-    if (self == [[self webView] mainFrame])
-        LOG(DocumentLoad, "loading %@", [[[self provisionalDataSource] request] URL]);
-
-    WebHistoryItem *item = [_private provisionalItem];
-    if ((loadType == WebFrameLoadTypeForward ||
-        loadType == WebFrameLoadTypeBack ||
-        loadType == WebFrameLoadTypeIndexedBackForward) &&
-        [item hasPageCache]){
-        NSDictionary *pageCache = [[_private provisionalItem] pageCache];
-        if ([pageCache objectForKey:WebCorePageCacheStateKey]){
-            LOG (PageCache, "Restoring page from back/forward cache, %@\n", [[_private provisionalItem] URL]);
-            [_private->provisionalDataSource _startLoading: pageCache];
-            return;
-        }
-    }
-
-    if (formState) {
-        // It's a bit of a hack to reuse the WebPolicyDecisionListener for the continuation
-        // mechanism across the willSubmitForm callout.
-        _private->listener = [[WebPolicyDecisionListener alloc] _initWithTarget:self action:@selector(_continueAfterWillSubmitForm:)];
-        [[[self webView] _formDelegate] frame:self sourceFrame:[formState sourceFrame] willSubmitForm:[formState form] withValues:[formState values] submissionListener:_private->listener];
-    } 
-    else {
-        [self _continueAfterWillSubmitForm:WebPolicyUse];
-    }
-}
-
-- (void)_loadDataSource:(WebDataSource *)newDataSource withLoadType:(WebFrameLoadType)loadType formState:(WebFormState *)formState
-{
-    ASSERT([self webView] != nil);
-
-    // Unfortunately the view must be non-nil, this is ultimately due
-    // to KDE parser requiring a KHTMLView.  Once we settle on a final
-    // KDE drop we should fix this dependency.
-
-    ASSERT([self frameView] != nil);
-
-    _private->policyLoadType = loadType;
-
-    WebFrame *parentFrame = [self parentFrame];
-    if (parentFrame) {
-        [newDataSource _setOverrideEncoding:[[parentFrame dataSource] _overrideEncoding]];
-    }
-    [newDataSource _setWebView:[self webView]];
-    [newDataSource _setJustOpenedForTargetedLink:_private->justOpenedForTargetedLink];
-    _private->justOpenedForTargetedLink = NO;
-
-    [self _setPolicyDataSource:newDataSource];
-
-    [self _checkNavigationPolicyForRequest:[newDataSource request]
-                                dataSource:newDataSource
-                                 formState:formState
-                                   andCall:self
-                              withSelector:@selector(_continueLoadRequestAfterNavigationPolicy:formState:)];
-}
-
-- (void)_setJustOpenedForTargetedLink:(BOOL)justOpened
-{
-    _private->justOpenedForTargetedLink = justOpened;
-}
-
-- (void)_setProvisionalDataSource: (WebDataSource *)d
-{
-    if (_private->provisionalDataSource != _private->dataSource) {
-	[_private->provisionalDataSource _setWebFrame:nil];
-    }
-    [_private setProvisionalDataSource: d];
-    [d _setWebFrame:self];
-}
-
-// used to decide to use loadType=Same
-- (BOOL)_shouldTreatURLAsSameAsCurrent:(NSURL *)URL
-{
-    WebHistoryItem *item = [_private currentItem];
-    NSString* URLString = [URL _web_originalDataAsString];
-    return [URLString isEqual:[item URLString]] || [URLString isEqual:[item originalURLString]];
-}    
-
-- (void)_loadRequest:(NSURLRequest *)request inFrameNamed:(NSString *)frameName
-{
-    if (frameName == nil) {
-	[self loadRequest:request];
-	return;
-    }
-
-    WebFrame *frame = [self findFrameNamed:frameName];
-    
-    if (frame != nil) {
-	[frame loadRequest:request];
-	return;
-    }
-
-    NSDictionary *action = [self _actionInformationForNavigationType:WebNavigationTypeOther event:nil originalURL:[request URL]];
-    [self _checkNewWindowPolicyForRequest:request action:(NSDictionary *)action frameName:frameName formState:nil andCall:self withSelector:@selector(_continueLoadRequestAfterNewWindowPolicy:frameName:formState:)];
-}
-
-// Returns the next frame in our parent's children array, or nil
-- (WebFrame *)_nextSibling
-{
-    if (_private->parent) {
-        NSArray *parentsKids = _private->parent->_private->children;
-        unsigned selfIndex = [parentsKids indexOfObjectIdenticalTo:self];
-        ASSERT(selfIndex != NSNotFound);
-        if (selfIndex < [parentsKids count]-1) {
-            return [parentsKids objectAtIndex:selfIndex+1];
-        }
-    }
-    return nil;		// no parent, or no more later siblings
-}
-
-// Returns the previous frame in our parent's children array, or nil
-- (WebFrame *)_previousSibling
-{
-    if (_private->parent) {
-        NSArray *parentsKids = _private->parent->_private->children;
-        unsigned selfIndex = [parentsKids indexOfObjectIdenticalTo:self];
-        ASSERT(selfIndex != NSNotFound);
-        if (selfIndex > 0) {
-            return [parentsKids objectAtIndex:selfIndex-1];
-        }
-    }
-    return nil;		// no parent, or no more earlier siblings
-}
-
-// Returns the last child of us and any children, or nil
-- (WebFrame *)_lastChild
-{
-    if (_private->children && [_private->children count]) {
-        WebFrame *ourLastKid = [_private->children lastObject];
-        WebFrame *kidsLastKid = [ourLastKid _lastChild];
-        return kidsLastKid ? kidsLastKid : ourLastKid;
-    }
-    return nil;		// no kids
-}
-
-// Return next frame to be traversed, visiting children after parent
-- (WebFrame *)_nextFrameWithWrap:(BOOL)wrapFlag
-{
-    if (_private->children && [_private->children count]) {
-        return [_private->children objectAtIndex:0];
-    } else if (_private->parent) {
-        WebFrame *frame;
-        for (frame = self; frame->_private->parent; frame = frame->_private->parent) {
-            WebFrame *nextSibling = [frame _nextSibling];
-            if (nextSibling) {
-                return nextSibling;
-            }
-        }
-        return wrapFlag ? frame : nil;		// made it all the way to the top
-    } else {
-        return wrapFlag ? self : nil;		// self is the top and we have no kids
-    }
-}
-
-// Return previous frame to be traversed, exact reverse order of _nextFrame
-- (WebFrame *)_previousFrameWithWrap:(BOOL)wrapFlag
-{
-    WebFrame *prevSibling = [self _previousSibling];
-    if (prevSibling) {
-        WebFrame *prevSiblingLastChild = [prevSibling _lastChild];
-        return prevSiblingLastChild ? prevSiblingLastChild : prevSibling;
-    } else if (_private->parent) {
-        return _private->parent;
-    } else {
-        // no siblings, no parent, self==top
-        if (wrapFlag) {
-            WebFrame *selfLastChild = [self _lastChild];
-            return selfLastChild ? selfLastChild : self;
-        } else {
-            // top view is always the last one in this ordering, so prev is nil without wrap
-            return nil;
-        }
-    }
-}
-
-- (void)_setShouldCreateRenderers:(BOOL)f
-{
-    [_private->bridge setShouldCreateRenderers:f];
-}
-
-- (BOOL)_shouldCreateRenderers
-{
-    return [_private->bridge shouldCreateRenderers];
-}
-
-- (int)_numPendingOrLoadingRequests:(BOOL)recurse
-{
-    int num;
-
-    if (!recurse)
-        return [[self _bridge] numPendingOrLoadingRequests];
-
-    num = [[self _bridge] numPendingOrLoadingRequests];
-    NSArray *children = [self childFrames];
-    int i, count = [children count];
-    WebFrame *child;
-    for (i = 0; i < count; i++){
-        child = [children objectAtIndex: 0];
-        num += [child _numPendingOrLoadingRequests:recurse];
-    }
-    return num;
-}
-
-- (NSColor *)_bodyBackgroundColor
-{
-    return [_private->bridge bodyBackgroundColor];
-}
-
- at end
-
- at implementation WebFormState : NSObject
-
-- (id)initWithForm:(NSObject <WebDOMElement> *)form values:(NSDictionary *)values sourceFrame:(WebFrame *)sourceFrame
-{
-    [super init];
-    _form = [form retain];
-    _values = [values copy];
-    _sourceFrame = [sourceFrame retain];
-    return self;
-}
-
-- (void)dealloc
-{
-    [_form release];
-    [_values release];
-    [_sourceFrame release];
-    [super dealloc];
-}
-
-- (id <WebDOMElement>)form
-{
-    return _form;
-}
-
-- (NSDictionary *)values
-{
-    return _values;
-}
-
-- (WebFrame *)sourceFrame
-{
-    return _sourceFrame;
-}
-
- at end
diff --git a/WebKit/WebView.subproj/WebFrameView.m b/WebKit/WebView.subproj/WebFrameView.m
index 9cbd272..b980514 100644
--- a/WebKit/WebView.subproj/WebFrameView.m
+++ b/WebKit/WebView.subproj/WebFrameView.m
@@ -24,6 +24,7 @@
 #import <WebKit/WebTextView.h>
 #import <WebKit/WebViewFactory.h>
 #import <WebKit/WebViewPrivate.h>
+#import <WebKit/WebAssertions.h>
 
 #import <Foundation/NSDictionary_NSURLExtras.h>
 #import <Foundation/NSURLRequest.h>
@@ -32,6 +33,371 @@ enum {
     SpaceKey = 0x0020
 };
 
+ at implementation WebFrameViewPrivate
+
+- init
+{
+    [super init];
+    
+    marginWidth = -1;
+    marginHeight = -1;
+    
+    return self;
+}
+
+- (void)dealloc
+{
+    [frameScrollView release];
+    [draggingTypes release];
+    [super dealloc];
+}
+
+ at end
+
+ at implementation WebFrameView (WebPrivate)
+
+// Note that the WebVew is not retained.
+- (WebView *)_webView
+{
+    return _private->webView;
+}
+
+
+- (void)_setMarginWidth: (int)w
+{
+    _private->marginWidth = w;
+}
+
+- (int)_marginWidth
+{
+    return _private->marginWidth;
+}
+
+- (void)_setMarginHeight: (int)h
+{
+    _private->marginHeight = h;
+}
+
+- (int)_marginHeight
+{
+    return _private->marginHeight;
+}
+
+- (void)_setDocumentView:(NSView *)view
+{
+    WebDynamicScrollBarsView *sv = (WebDynamicScrollBarsView *)[self _scrollView];
+    
+    [sv setSuppressLayout: YES];
+    
+    // Always start out with arrow.  New docView can then change as needed, but doesn't have to
+    // clean up after the previous docView.  Also TextView will set cursor when added to view
+    // tree, so must do this before setDocumentView:.
+    [sv setDocumentCursor:[NSCursor arrowCursor]];
+
+    [sv setDocumentView: view];
+    [sv setSuppressLayout: NO];
+}
+
+-(NSView <WebDocumentView> *)_makeDocumentViewForDataSource:(WebDataSource *)dataSource
+{
+    NSString *MIMEType = [[dataSource response] MIMEType];
+    
+    Class viewClass = [[self class] _viewClassForMIMEType:MIMEType];
+    NSView <WebDocumentView> *documentView = viewClass ? [[viewClass alloc] init] : nil;
+    [self _setDocumentView:documentView];
+    [documentView release];
+    
+    return documentView;
+}
+
+- (void)_setWebView:(WebView *)webView
+{
+    // Not retained because the WebView owns the WebFrame, which owns the WebFrameView.
+    _private->webView = webView;    
+}
+
+- (NSScrollView *)_scrollView
+{
+    return _private->frameScrollView;
+}
+
+
+- (NSClipView *)_contentView
+{
+    return [[self _scrollView] contentView];
+}
+
+- (void)_scrollVerticallyBy: (float)delta
+{
+    NSPoint point = [[self _contentView] bounds].origin;
+    point.y += delta;
+    [[self _contentView] scrollPoint: point];
+}
+
+- (void)_scrollHorizontallyBy: (float)delta
+{
+    NSPoint point = [[self _contentView] bounds].origin;
+    point.x += delta;
+    [[self _contentView] scrollPoint: point];
+}
+
+- (float)_verticalKeyboardScrollAmount
+{
+    // verticalLineScroll is quite small, to make scrolling from the scroll bar
+    // arrows relatively smooth. But this seemed too small for scrolling with
+    // the arrow keys, so we bump up the number here. Cheating? Perhaps.
+    return [[self _scrollView] verticalLineScroll] * 4;
+}
+
+- (float)_horizontalKeyboardScrollAmount
+{
+    // verticalLineScroll is quite small, to make scrolling from the scroll bar
+    // arrows relatively smooth. But this seemed too small for scrolling with
+    // the arrow keys, so we bump up the number here. Cheating? Perhaps.
+    return [[self _scrollView] horizontalLineScroll] * 4;
+}
+
+- (void)_pageVertically:(BOOL)up
+{
+    float pageOverlap = [self _verticalKeyboardScrollAmount];
+    float delta = [[self _contentView] bounds].size.height;
+    
+    delta = (delta < pageOverlap) ? delta / 2.0 : delta - pageOverlap;
+
+    if (up) {
+        delta = -delta;
+    }
+
+    [self _scrollVerticallyBy: delta];
+}
+
+- (void)_pageHorizontally: (BOOL)left
+{
+    float pageOverlap = [self _horizontalKeyboardScrollAmount];
+    float delta = [[self _contentView] bounds].size.width;
+    
+    delta = (delta < pageOverlap) ? delta / 2.0 : delta - pageOverlap;
+
+    if (left) {
+        delta = -delta;
+    }
+
+    [self _scrollHorizontallyBy: delta];
+}
+
+- (void)_scrollLineVertically: (BOOL)up
+{
+    float delta = [self _verticalKeyboardScrollAmount];
+
+    if (up) {
+        delta = -delta;
+    }
+
+    [self _scrollVerticallyBy: delta];
+}
+
+- (void)_scrollLineHorizontally: (BOOL)left
+{
+    float delta = [self _horizontalKeyboardScrollAmount];
+
+    if (left) {
+        delta = -delta;
+    }
+
+    [self _scrollHorizontallyBy: delta];
+}
+
+- (void)scrollPageUp:(id)sender
+{
+    // After hitting the top, tell our parent to scroll
+    float oldY = [[self _contentView] bounds].origin.y;
+    [self _pageVertically:YES];
+    if (oldY == [[self _contentView] bounds].origin.y) {
+        [[self nextResponder] tryToPerform:@selector(scrollPageUp:) with:nil];
+    }
+}
+
+- (void)scrollPageDown:(id)sender
+{
+    // After hitting the bottom, tell our parent to scroll
+    float oldY = [[self _contentView] bounds].origin.y;
+    [self _pageVertically:NO];
+    if (oldY == [[self _contentView] bounds].origin.y) {
+        [[self nextResponder] tryToPerform:@selector(scrollPageDown:) with:nil];
+    }
+}
+
+- (void)_pageLeft
+{
+    [self _pageHorizontally:YES];
+}
+
+- (void)_pageRight
+{
+    [self _pageHorizontally:NO];
+}
+
+- (void)_scrollToTopLeft
+{
+    [[self _contentView] scrollPoint: NSMakePoint(0, 0)];
+}
+
+- (void)_scrollToBottomLeft
+{
+    [[self _contentView] scrollPoint: NSMakePoint(0, [[[self _scrollView] documentView] bounds].size.height)];
+}
+
+- (void)scrollLineUp:(id)sender
+{
+    [self _scrollLineVertically: YES];
+}
+
+- (void)scrollLineDown:(id)sender
+{
+    [self _scrollLineVertically: NO];
+}
+
+- (void)_lineLeft
+{
+    [self _scrollLineHorizontally: YES];
+}
+
+- (void)_lineRight
+{
+    [self _scrollLineHorizontally: NO];
+}
+
+static NSMutableDictionary *viewTypes;
+
++ (NSMutableDictionary *)_viewTypesAllowImageTypeOmission:(BOOL)allowImageTypeOmission
+{
+    static BOOL addedImageTypes;
+
+    if (!viewTypes) {
+        viewTypes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
+            [WebHTMLView class], @"text/html",
+	    [WebHTMLView class], @"text/xml",
+	    [WebHTMLView class], @"application/xml",
+	    [WebHTMLView class], @"application/xhtml+xml",
+            [WebTextView class], @"text/",
+            [WebTextView class], @"application/x-javascript",
+            nil];
+    }
+
+    if (!addedImageTypes && !allowImageTypeOmission) {
+        NSEnumerator *enumerator = [[WebImageView supportedImageMIMETypes] objectEnumerator];
+        ASSERT(enumerator != nil);
+        NSString *mime;
+        while ((mime = [enumerator nextObject]) != nil) {
+            // Don't clobber previously-registered user image types
+            if ([viewTypes objectForKey:mime] == nil) {
+                [viewTypes setObject:[WebImageView class] forKey:mime];
+            }
+        }
+        addedImageTypes = YES;
+    }
+    
+    return viewTypes;
+}
+
++ (BOOL)_canShowMIMETypeAsHTML:(NSString *)MIMEType
+{
+    return ([viewTypes objectForKey:MIMEType] == [WebHTMLView class]);
+}
+
+
++ (Class)_viewClassForMIMEType:(NSString *)MIMEType
+{
+    // Getting the image types is slow, so don't do it until we have to.
+    Class c = [[self _viewTypesAllowImageTypeOmission:YES] _web_objectForMIMEType:MIMEType];
+    if (c == nil) {
+        c = [[self _viewTypesAllowImageTypeOmission:NO] _web_objectForMIMEType:MIMEType];
+    }
+    return c;
+}
+
+- (void)_goBack
+{
+    [_private->webView goBack];
+}
+
+- (void)_goForward
+{
+    [_private->webView goForward];
+}
+
+- (BOOL)_isMainFrame
+{
+    return [_private->webView mainFrame] == [self webFrame];
+}
+
+- (void)_tile
+{
+    NSRect scrollViewFrame = [self bounds];
+    // The border drawn by WebFrameView is 1 pixel on the left and right,
+    // two pixels on top and bottom.  Shrink the scroll view to accomodate
+    // the border.
+    if ([self _shouldDrawBorder]){
+        scrollViewFrame = NSInsetRect (scrollViewFrame, 1, 2);
+    }
+    [_private->frameScrollView setFrame:scrollViewFrame];
+}
+
+- (void)_drawBorder
+{
+    if ([self _shouldDrawBorder]){
+        NSRect vRect = [self frame];
+            
+        // Left, black
+        [[NSColor blackColor] set];
+        NSRectFill(NSMakeRect(0,0,1,vRect.size.height));
+        
+        // Top, light gray, black
+        [[NSColor lightGrayColor] set];
+        NSRectFill(NSMakeRect(0,0,vRect.size.width,1));
+        [[NSColor whiteColor] set];
+        NSRectFill(NSMakeRect(1,1,vRect.size.width-2,1));
+        
+        // Right, light gray
+        [[NSColor lightGrayColor] set];
+        NSRectFill(NSMakeRect(vRect.size.width-1,1,1,vRect.size.height-2));
+        
+        // Bottom, light gray, white
+        [[NSColor blackColor] set];
+        NSRectFill(NSMakeRect(0,vRect.size.height-1,vRect.size.width,1));
+        [[NSColor lightGrayColor] set];
+        NSRectFill(NSMakeRect(1,vRect.size.height-2,vRect.size.width-2,1));
+    }
+}
+
+- (BOOL)_shouldDrawBorder
+{
+    if (!_private->hasBorder)
+        return NO;
+        
+    // Only draw a border for frames that request a border and the frame does
+    // not contain a frameset.  Additionally we should (post-panther) not draw
+    // a border (left, right, top or bottom) if the frame edge abutts the window frame.
+    NSView *docV = [self documentView];
+    if ([docV isKindOfClass:[WebHTMLView class]]){
+        if ([[(WebHTMLView *)docV _bridge] isFrameSet]){
+            return NO;
+        }
+    }
+    return YES;
+}
+
+- (void)_setHasBorder:(BOOL)hasBorder
+{
+    if (_private->hasBorder == hasBorder) {
+        return;
+    }
+    _private->hasBorder = hasBorder;
+    [self _tile];
+}
+
+ at end
+
 @implementation WebFrameView
 
 - initWithFrame: (NSRect) frame
diff --git a/WebKit/WebView.subproj/WebFrameViewPrivate.m b/WebKit/WebView.subproj/WebFrameViewPrivate.m
deleted file mode 100644
index ef8b336..0000000
--- a/WebKit/WebView.subproj/WebFrameViewPrivate.m
+++ /dev/null
@@ -1,383 +0,0 @@
-/*	WebFrameViewPrivate.m
-	Copyright 2001, Apple, Inc. All rights reserved.
-*/
-
-#import <WebKit/WebFrameViewPrivate.h>
-
-#import <WebKit/WebBridge.h>
-#import <WebKit/WebDataSource.h>
-#import <WebKit/WebDocument.h>
-#import <WebKit/WebDynamicScrollBarsView.h>
-#import <WebKit/WebHTMLViewPrivate.h>
-#import <WebKit/WebImageView.h>
-#import <WebKit/WebTextView.h>
-#import <WebKit/WebViewPrivate.h>
-
-#import <Foundation/NSDictionary_NSURLExtras.h>
-#import <Foundation/NSURLResponse.h>
-#import <WebKit/WebAssertions.h>
-
- at implementation WebFrameViewPrivate
-
-- init
-{
-    [super init];
-    
-    marginWidth = -1;
-    marginHeight = -1;
-    
-    return self;
-}
-
-- (void)dealloc
-{
-    [frameScrollView release];
-    [draggingTypes release];
-    [super dealloc];
-}
-
- at end
-
- at implementation WebFrameView (WebPrivate)
-
-// Note that the WebVew is not retained.
-- (WebView *)_webView
-{
-    return _private->webView;
-}
-
-
-- (void)_setMarginWidth: (int)w
-{
-    _private->marginWidth = w;
-}
-
-- (int)_marginWidth
-{
-    return _private->marginWidth;
-}
-
-- (void)_setMarginHeight: (int)h
-{
-    _private->marginHeight = h;
-}
-
-- (int)_marginHeight
-{
-    return _private->marginHeight;
-}
-
-- (void)_setDocumentView:(NSView *)view
-{
-    WebDynamicScrollBarsView *sv = (WebDynamicScrollBarsView *)[self _scrollView];
-    
-    [sv setSuppressLayout: YES];
-    
-    // Always start out with arrow.  New docView can then change as needed, but doesn't have to
-    // clean up after the previous docView.  Also TextView will set cursor when added to view
-    // tree, so must do this before setDocumentView:.
-    [sv setDocumentCursor:[NSCursor arrowCursor]];
-
-    [sv setDocumentView: view];
-    [sv setSuppressLayout: NO];
-}
-
--(NSView <WebDocumentView> *)_makeDocumentViewForDataSource:(WebDataSource *)dataSource
-{
-    NSString *MIMEType = [[dataSource response] MIMEType];
-    
-    Class viewClass = [[self class] _viewClassForMIMEType:MIMEType];
-    NSView <WebDocumentView> *documentView = viewClass ? [[viewClass alloc] init] : nil;
-    [self _setDocumentView:documentView];
-    [documentView release];
-    
-    return documentView;
-}
-
-- (void)_setWebView:(WebView *)webView
-{
-    // Not retained because the WebView owns the WebFrame, which owns the WebFrameView.
-    _private->webView = webView;    
-}
-
-- (NSScrollView *)_scrollView
-{
-    return _private->frameScrollView;
-}
-
-
-- (NSClipView *)_contentView
-{
-    return [[self _scrollView] contentView];
-}
-
-- (void)_scrollVerticallyBy: (float)delta
-{
-    NSPoint point = [[self _contentView] bounds].origin;
-    point.y += delta;
-    [[self _contentView] scrollPoint: point];
-}
-
-- (void)_scrollHorizontallyBy: (float)delta
-{
-    NSPoint point = [[self _contentView] bounds].origin;
-    point.x += delta;
-    [[self _contentView] scrollPoint: point];
-}
-
-- (float)_verticalKeyboardScrollAmount
-{
-    // verticalLineScroll is quite small, to make scrolling from the scroll bar
-    // arrows relatively smooth. But this seemed too small for scrolling with
-    // the arrow keys, so we bump up the number here. Cheating? Perhaps.
-    return [[self _scrollView] verticalLineScroll] * 4;
-}
-
-- (float)_horizontalKeyboardScrollAmount
-{
-    // verticalLineScroll is quite small, to make scrolling from the scroll bar
-    // arrows relatively smooth. But this seemed too small for scrolling with
-    // the arrow keys, so we bump up the number here. Cheating? Perhaps.
-    return [[self _scrollView] horizontalLineScroll] * 4;
-}
-
-- (void)_pageVertically:(BOOL)up
-{
-    float pageOverlap = [self _verticalKeyboardScrollAmount];
-    float delta = [[self _contentView] bounds].size.height;
-    
-    delta = (delta < pageOverlap) ? delta / 2.0 : delta - pageOverlap;
-
-    if (up) {
-        delta = -delta;
-    }
-
-    [self _scrollVerticallyBy: delta];
-}
-
-- (void)_pageHorizontally: (BOOL)left
-{
-    float pageOverlap = [self _horizontalKeyboardScrollAmount];
-    float delta = [[self _contentView] bounds].size.width;
-    
-    delta = (delta < pageOverlap) ? delta / 2.0 : delta - pageOverlap;
-
-    if (left) {
-        delta = -delta;
-    }
-
-    [self _scrollHorizontallyBy: delta];
-}
-
-- (void)_scrollLineVertically: (BOOL)up
-{
-    float delta = [self _verticalKeyboardScrollAmount];
-
-    if (up) {
-        delta = -delta;
-    }
-
-    [self _scrollVerticallyBy: delta];
-}
-
-- (void)_scrollLineHorizontally: (BOOL)left
-{
-    float delta = [self _horizontalKeyboardScrollAmount];
-
-    if (left) {
-        delta = -delta;
-    }
-
-    [self _scrollHorizontallyBy: delta];
-}
-
-- (void)scrollPageUp:(id)sender
-{
-    // After hitting the top, tell our parent to scroll
-    float oldY = [[self _contentView] bounds].origin.y;
-    [self _pageVertically:YES];
-    if (oldY == [[self _contentView] bounds].origin.y) {
-        [[self nextResponder] tryToPerform:@selector(scrollPageUp:) with:nil];
-    }
-}
-
-- (void)scrollPageDown:(id)sender
-{
-    // After hitting the bottom, tell our parent to scroll
-    float oldY = [[self _contentView] bounds].origin.y;
-    [self _pageVertically:NO];
-    if (oldY == [[self _contentView] bounds].origin.y) {
-        [[self nextResponder] tryToPerform:@selector(scrollPageDown:) with:nil];
-    }
-}
-
-- (void)_pageLeft
-{
-    [self _pageHorizontally:YES];
-}
-
-- (void)_pageRight
-{
-    [self _pageHorizontally:NO];
-}
-
-- (void)_scrollToTopLeft
-{
-    [[self _contentView] scrollPoint: NSMakePoint(0, 0)];
-}
-
-- (void)_scrollToBottomLeft
-{
-    [[self _contentView] scrollPoint: NSMakePoint(0, [[[self _scrollView] documentView] bounds].size.height)];
-}
-
-- (void)scrollLineUp:(id)sender
-{
-    [self _scrollLineVertically: YES];
-}
-
-- (void)scrollLineDown:(id)sender
-{
-    [self _scrollLineVertically: NO];
-}
-
-- (void)_lineLeft
-{
-    [self _scrollLineHorizontally: YES];
-}
-
-- (void)_lineRight
-{
-    [self _scrollLineHorizontally: NO];
-}
-
-static NSMutableDictionary *viewTypes;
-
-+ (NSMutableDictionary *)_viewTypesAllowImageTypeOmission:(BOOL)allowImageTypeOmission
-{
-    static BOOL addedImageTypes;
-
-    if (!viewTypes) {
-        viewTypes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
-            [WebHTMLView class], @"text/html",
-	    [WebHTMLView class], @"text/xml",
-	    [WebHTMLView class], @"application/xml",
-	    [WebHTMLView class], @"application/xhtml+xml",
-            [WebTextView class], @"text/",
-            [WebTextView class], @"application/x-javascript",
-            nil];
-    }
-
-    if (!addedImageTypes && !allowImageTypeOmission) {
-        NSEnumerator *enumerator = [[WebImageView supportedImageMIMETypes] objectEnumerator];
-        ASSERT(enumerator != nil);
-        NSString *mime;
-        while ((mime = [enumerator nextObject]) != nil) {
-            // Don't clobber previously-registered user image types
-            if ([viewTypes objectForKey:mime] == nil) {
-                [viewTypes setObject:[WebImageView class] forKey:mime];
-            }
-        }
-        addedImageTypes = YES;
-    }
-    
-    return viewTypes;
-}
-
-+ (BOOL)_canShowMIMETypeAsHTML:(NSString *)MIMEType
-{
-    return ([viewTypes objectForKey:MIMEType] == [WebHTMLView class]);
-}
-
-
-+ (Class)_viewClassForMIMEType:(NSString *)MIMEType
-{
-    // Getting the image types is slow, so don't do it until we have to.
-    Class c = [[self _viewTypesAllowImageTypeOmission:YES] _web_objectForMIMEType:MIMEType];
-    if (c == nil) {
-        c = [[self _viewTypesAllowImageTypeOmission:NO] _web_objectForMIMEType:MIMEType];
-    }
-    return c;
-}
-
-- (void)_goBack
-{
-    [_private->webView goBack];
-}
-
-- (void)_goForward
-{
-    [_private->webView goForward];
-}
-
-- (BOOL)_isMainFrame
-{
-    return [_private->webView mainFrame] == [self webFrame];
-}
-
-- (void)_tile
-{
-    NSRect scrollViewFrame = [self bounds];
-    // The border drawn by WebFrameView is 1 pixel on the left and right,
-    // two pixels on top and bottom.  Shrink the scroll view to accomodate
-    // the border.
-    if ([self _shouldDrawBorder]){
-        scrollViewFrame = NSInsetRect (scrollViewFrame, 1, 2);
-    }
-    [_private->frameScrollView setFrame:scrollViewFrame];
-}
-
-- (void)_drawBorder
-{
-    if ([self _shouldDrawBorder]){
-        NSRect vRect = [self frame];
-            
-        // Left, black
-        [[NSColor blackColor] set];
-        NSRectFill(NSMakeRect(0,0,1,vRect.size.height));
-        
-        // Top, light gray, black
-        [[NSColor lightGrayColor] set];
-        NSRectFill(NSMakeRect(0,0,vRect.size.width,1));
-        [[NSColor whiteColor] set];
-        NSRectFill(NSMakeRect(1,1,vRect.size.width-2,1));
-        
-        // Right, light gray
-        [[NSColor lightGrayColor] set];
-        NSRectFill(NSMakeRect(vRect.size.width-1,1,1,vRect.size.height-2));
-        
-        // Bottom, light gray, white
-        [[NSColor blackColor] set];
-        NSRectFill(NSMakeRect(0,vRect.size.height-1,vRect.size.width,1));
-        [[NSColor lightGrayColor] set];
-        NSRectFill(NSMakeRect(1,vRect.size.height-2,vRect.size.width-2,1));
-    }
-}
-
-- (BOOL)_shouldDrawBorder
-{
-    if (!_private->hasBorder)
-        return NO;
-        
-    // Only draw a border for frames that request a border and the frame does
-    // not contain a frameset.  Additionally we should (post-panther) not draw
-    // a border (left, right, top or bottom) if the frame edge abutts the window frame.
-    NSView *docV = [self documentView];
-    if ([docV isKindOfClass:[WebHTMLView class]]){
-        if ([[(WebHTMLView *)docV _bridge] isFrameSet]){
-            return NO;
-        }
-    }
-    return YES;
-}
-
-- (void)_setHasBorder:(BOOL)hasBorder
-{
-    if (_private->hasBorder == hasBorder) {
-        return;
-    }
-    _private->hasBorder = hasBorder;
-    [self _tile];
-}
-
- at end
diff --git a/WebKit/WebView.subproj/WebHTMLView.m b/WebKit/WebView.subproj/WebHTMLView.m
index 12c7cde..0c2b5b6 100644
--- a/WebKit/WebView.subproj/WebHTMLView.m
+++ b/WebKit/WebView.subproj/WebHTMLView.m
@@ -30,11 +30,814 @@
 
 #import <AppKit/NSAccessibility.h>
 
+#import <WebKit/WebImageRenderer.h>
+#import <WebKit/WebKitNSStringExtras.h>
+#import <WebKit/WebNSImageExtras.h>
+#import <WebKit/WebNSURLExtras.h>
+#import <WebKit/WebPreferences.h>
+#import <WebKit/WebStringTruncator.h>
+
+
+// These are a little larger than typical because dragging links is a fairly
+// advanced feature that can confuse non-power-users
+#define DragHysteresis  		10.0
+#define TextDragHysteresis  		3.0
+#define TextDragDelay			0.15
+
+#define AUTOSCROLL_INTERVAL             0.1
+
+#define DRAG_LABEL_BORDER_X		4.0
+#define DRAG_LABEL_BORDER_Y		2.0
+#define DRAG_LABEL_RADIUS		5.0
+#define DRAG_LABEL_BORDER_Y_OFFSET              2.0
+
+#define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP	120.0
+#define MAX_DRAG_LABEL_WIDTH                    320.0
+
+#define DRAG_LINK_LABEL_FONT_SIZE   11.0
+#define DRAG_LINK_URL_FONT_SIZE   10.0
+
+static BOOL forceRealHitTest = NO;
+
 @interface WebHTMLView (WebHTMLViewPrivate)
 - (void)_setPrinting:(BOOL)printing pageWidth:(float)pageWidth adjustViewSize:(BOOL)adjustViewSize;
 - (void)_updateTextSizeMultiplier;
 @end
 
+// Any non-zero value will do, but using somethign recognizable might help us debug some day.
+#define TRACKING_RECT_TAG 0xBADFACE
+
+
+ at interface NSView (AppKitSecretsIKnowAbout)
+- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView testDirtyRect:(BOOL)testDirtyRect;
+- (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
+- (NSRect)_dirtyRect;
+- (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
+ at end
+
+ at interface NSView (WebHTMLViewPrivate)
+- (void)_web_setPrintingModeRecursive;
+- (void)_web_clearPrintingModeRecursive;
+- (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
+ at end
+
+ at interface NSMutableDictionary (WebHTMLViewPrivate)
+- (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
+ at end
+
+ at implementation WebHTMLViewPrivate
+
+- (void)dealloc
+{
+    ASSERT(autoscrollTimer == nil);
+    
+    [pluginController destroyAllPlugins];
+    
+    [mouseDownEvent release];
+    [draggingImageURL release];
+    [pluginController release];
+    [toolTip release];
+    
+    [super dealloc];
+}
+
+ at end
+
+
+ at implementation WebHTMLView (WebPrivate)
+
+- (void)_adjustFrames
+{
+    // Ick!  khtml set the frame size during layout and
+    // the frame origins during drawing!  So we have to 
+    // layout and do a draw with rendering disabled to
+    // correclty adjust the frames.
+    [[self _bridge] adjustFrames:[self frame]];
+}
+
+- (void)_reset
+{
+    [WebImageRenderer stopAnimationsInView:self];
+}
+
+- (WebView *)_webView
+{
+    // We used to use the view hierarchy exclusively here, but that won't work
+    // right when the first viewDidMoveToSuperview call is done, and this wil.
+    return [[self _frame] webView];
+}
+
+- (WebFrame *)_frame
+{
+    WebFrameView *webFrameView = [self _web_parentWebFrameView];
+    return [webFrameView webFrame];
+}
+
+// Required so view can access the part's selection.
+- (WebBridge *)_bridge
+{
+    return [[self _frame] _bridge];
+}
+
++ (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
+{
+    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
+        location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
+        modifierFlags:[flagsChangedEvent modifierFlags]
+        timestamp:[flagsChangedEvent timestamp]
+        windowNumber:[flagsChangedEvent windowNumber]
+        context:[flagsChangedEvent context]
+        eventNumber:0 clickCount:0 pressure:0];
+
+    // Pretend it's a mouse move.
+    [[NSNotificationCenter defaultCenter]
+        postNotificationName:NSMouseMovedNotification object:self
+        userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
+}
+
+- (void)_updateMouseoverWithFakeEvent
+{
+    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
+        location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
+        modifierFlags:[[NSApp currentEvent] modifierFlags]
+        timestamp:[NSDate timeIntervalSinceReferenceDate]
+        windowNumber:[[self window] windowNumber]
+        context:[[NSApp currentEvent] context]
+        eventNumber:0 clickCount:0 pressure:0];
+    
+    [self _updateMouseoverWithEvent:fakeEvent];
+}
+
+- (void)_frameOrBoundsChanged
+{
+    if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
+        [self setNeedsLayout:YES];
+        [self setNeedsDisplay:YES];
+    }
+
+    SEL selector = @selector(_updateMouseoverWithFakeEvent);
+    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
+    [self performSelector:selector withObject:nil afterDelay:0];
+}
+
+- (NSDictionary *)_elementAtPoint:(NSPoint)point
+{
+    NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
+    NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
+
+    // Convert URL strings to NSURLs
+    [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
+    [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
+    
+    WebFrameView *webFrameView = [self _web_parentWebFrameView];
+    ASSERT(webFrameView);
+    WebFrame *webFrame = [webFrameView webFrame];
+    
+    if (webFrame) {
+        NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
+        if ([frameName length] == 0) {
+            [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
+        } else {
+            WebFrame *wf = [webFrame findFrameNamed:frameName];
+            if (wf != nil)
+                [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
+            else
+                [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
+        }
+    
+        [elementInfo setObject:webFrame forKey:WebElementFrameKey];
+    }
+    
+    return [elementInfo autorelease];
+}
+
+- (void)_setAsideSubviews
+{
+    ASSERT(!_private->subviewsSetAside);
+    ASSERT(_private->savedSubviews == nil);
+    _private->savedSubviews = _subviews;
+    _subviews = nil;
+    _private->subviewsSetAside = YES;
+ }
+ 
+ - (void)_restoreSubviews
+ {
+    ASSERT(_private->subviewsSetAside);
+    ASSERT(_subviews == nil);
+    _subviews = _private->savedSubviews;
+    _private->savedSubviews = nil;
+    _private->subviewsSetAside = NO;
+}
+
+// Don't let AppKit even draw subviews. We take care of that.
+- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView testDirtyRect:(BOOL)testDirtyRect
+{
+    // This helps when we print as part of a larger print process.
+    // If the WebHTMLView itself is what we're printing, then we will never have to do this.
+    BOOL wasInPrintingMode = _private->printing;
+    BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
+    if (wasInPrintingMode != isPrinting) {
+        if (isPrinting) {
+            [self _web_setPrintingModeRecursive];
+        } else {
+            [self _web_clearPrintingModeRecursive];
+        }
+    }
+
+    [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
+
+    [self _setAsideSubviews];
+    [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
+        rectIsVisibleRectForView:visibleView testDirtyRect:testDirtyRect];
+    [self _restoreSubviews];
+
+    if (wasInPrintingMode != isPrinting) {
+        if (wasInPrintingMode) {
+            [self _web_setPrintingModeRecursive];
+        } else {
+            [self _web_clearPrintingModeRecursive];
+        }
+    }
+}
+
+// Don't let AppKit even draw subviews. We take care of that.
+- (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
+{
+    BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
+
+    BOOL wasInPrintingMode = _private->printing;
+    BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
+
+    if (needToSetAsideSubviews) {
+        // This helps when we print as part of a larger print process.
+        // If the WebHTMLView itself is what we're printing, then we will never have to do this.
+        if (wasInPrintingMode != isPrinting) {
+            if (isPrinting) {
+                [self _web_setPrintingModeRecursive];
+            } else {
+                [self _web_clearPrintingModeRecursive];
+            }
+        }
+
+        [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
+
+        [self _setAsideSubviews];
+    }
+    
+    [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
+    
+    if (needToSetAsideSubviews) {
+        if (wasInPrintingMode != isPrinting) {
+            if (wasInPrintingMode) {
+                [self _web_setPrintingModeRecursive];
+            } else {
+                [self _web_clearPrintingModeRecursive];
+            }
+        }
+
+        [self _restoreSubviews];
+    }
+}
+
+- (BOOL)_insideAnotherHTMLView
+{
+    NSView *view = self;
+    while ((view = [view superview])) {
+        if ([view isKindOfClass:[WebHTMLView class]]) {
+            return YES;
+        }
+    }
+    return NO;
+}
+
+- (void)scrollPoint:(NSPoint)point
+{
+    // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
+    // If we get called during the handling of a key down event, we assume the call came from
+    // NSTextView, and ignore it and use our own code to decide how to page up and page down
+    // We are smarter about how far to scroll, and we have "superview scrolling" logic.
+    NSEvent *event = [[self window] currentEvent];
+    if ([event type] == NSKeyDown) {
+        const unichar pageUp = NSPageUpFunctionKey;
+        if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
+            [self tryToPerform:@selector(scrollPageUp:) with:nil];
+            return;
+        }
+        const unichar pageDown = NSPageDownFunctionKey;
+        if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
+            [self tryToPerform:@selector(scrollPageDown:) with:nil];
+            return;
+        }
+    }
+    
+    [super scrollPoint:point];
+}
+
+- (NSView *)hitTest:(NSPoint)point
+{
+    // WebHTMLView objects handle all left mouse clicks for objects inside them.
+    // That does not include left mouse clicks with the control key held down.
+    BOOL captureHitsOnSubviews;
+    if (forceRealHitTest) {
+        captureHitsOnSubviews = NO;
+    } else {
+        NSEvent *event = [[self window] currentEvent];
+        captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
+    }
+    if (!captureHitsOnSubviews) {
+        return [super hitTest:point];
+    }
+    if ([[self superview] mouse:point inRect:[self frame]]) {
+        return self;
+    }
+    return nil;
+}
+
+static WebHTMLView *lastHitView = nil;
+
+- (void)_clearLastHitViewIfSelf
+{
+    if (lastHitView == self) {
+	lastHitView = nil;
+    }
+}
+
+- (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
+{
+    ASSERT(_private->trackingRectOwner == nil);
+    _private->trackingRectOwner = owner;
+    _private->trackingRectUserData = data;
+    return TRACKING_RECT_TAG;
+}
+
+- (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
+{
+    ASSERT(tag == TRACKING_RECT_TAG);
+    return [self addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
+}
+
+- (void)removeTrackingRect:(NSTrackingRectTag)tag
+{
+    ASSERT(tag == TRACKING_RECT_TAG);
+    if (_private != nil) {
+        ASSERT(_private->trackingRectOwner != nil);
+        _private->trackingRectOwner = nil;
+    }
+}
+
+- (void)_sendToolTipMouseExited
+{
+    // Nothing matters except window, trackingNumber, and userData.
+    NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
+        location:NSMakePoint(0, 0)
+        modifierFlags:0
+        timestamp:0
+        windowNumber:[[self window] windowNumber]
+        context:NULL
+        eventNumber:0
+        trackingNumber:TRACKING_RECT_TAG
+        userData:_private->trackingRectUserData];
+    [_private->trackingRectOwner mouseExited:fakeEvent];
+}
+
+- (void)_sendToolTipMouseEntered
+{
+    // Nothing matters except window, trackingNumber, and userData.
+    NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
+        location:NSMakePoint(0, 0)
+        modifierFlags:0
+        timestamp:0
+        windowNumber:[[self window] windowNumber]
+        context:NULL
+        eventNumber:0
+        trackingNumber:TRACKING_RECT_TAG
+        userData:_private->trackingRectUserData];
+    [_private->trackingRectOwner mouseEntered:fakeEvent];
+}
+
+- (void)_setToolTip:(NSString *)string
+{
+    NSString *toolTip = [string length] == 0 ? nil : string;
+    NSString *oldToolTip = _private->toolTip;
+    if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
+        return;
+    }
+    if (oldToolTip) {
+        [self _sendToolTipMouseExited];
+        [oldToolTip release];
+    }
+    _private->toolTip = [toolTip copy];
+    if (toolTip) {
+        if (_private->toolTipTag) {
+            [self removeToolTip:_private->toolTipTag];
+        }
+        NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
+        _private->toolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
+        [self _sendToolTipMouseEntered];
+    }
+}
+
+- (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
+{
+    return [[_private->toolTip copy] autorelease];
+}
+
+- (void)_updateMouseoverWithEvent:(NSEvent *)event
+{
+    WebHTMLView *view = nil;
+    if ([event window] == [self window]) {
+        forceRealHitTest = YES;
+        NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
+        forceRealHitTest = NO;
+        while (hitView) {
+            if ([hitView isKindOfClass:[WebHTMLView class]]) {
+                view = (WebHTMLView *)hitView;
+                break;
+            }
+            hitView = [hitView superview];
+        }
+    }
+
+    if (lastHitView != view && lastHitView != nil) {
+	// If we are moving out of a view (or frame), let's pretend the mouse moved
+	// all the way out of that view. But we have to account for scrolling, because
+	// khtml doesn't understand our clipping.
+	NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
+	float yScroll = visibleRect.origin.y;
+	float xScroll = visibleRect.origin.x;
+
+	event = [NSEvent mouseEventWithType:NSMouseMoved
+			 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
+			 modifierFlags:[[NSApp currentEvent] modifierFlags]
+			 timestamp:[NSDate timeIntervalSinceReferenceDate]
+			 windowNumber:[[self window] windowNumber]
+			 context:[[NSApp currentEvent] context]
+			 eventNumber:0 clickCount:0 pressure:0];
+	[[lastHitView _bridge] mouseMoved:event];
+    }
+
+    lastHitView = view;
+    
+    NSDictionary *element;
+    if (view == nil) {
+        element = nil;
+    } else {
+        [[view _bridge] mouseMoved:event];
+
+        NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
+        element = [view _elementAtPoint:point];
+    }
+
+    // Have the web view send a message to the delegate so it can do status bar display.
+    [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
+
+    // Set a tool tip; it won't show up right away but will if the user pauses.
+    [self _setToolTip:[element objectForKey:WebCoreElementTitleKey]];
+}
+
++ (NSArray *)_pasteboardTypes
+{
+    return [NSArray arrayWithObjects:
+#if SUPPORT_HTML_PBOARD
+        NSHTMLPboardType,
+#endif
+        NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
+}
+
+- (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
+{
+    [pasteboard declareTypes:[[self class] _pasteboardTypes] owner:nil];
+
+#if SUPPORT_HTML_PBOARD
+    // Put HTML on the pasteboard.
+    [pasteboard setData:??? forType:NSHTMLPboardType];
+#endif
+
+    // Put attributed string on the pasteboard (RTF format).
+    NSAttributedString *attributedString = [self selectedAttributedString];
+    NSRange range = NSMakeRange(0, [attributedString length]);
+    NSData *attributedData = [attributedString RTFFromRange:range documentAttributes:nil];
+    [pasteboard setData:attributedData forType:NSRTFPboardType];
+
+    attributedData = [attributedString RTFDFromRange:range documentAttributes:nil];
+    [pasteboard setData:attributedData forType:NSRTFDPboardType];
+    
+    // Put plain string on the pasteboard.
+    [pasteboard setString:[self selectedString] forType:NSStringPboardType];
+}
+
+
+-(NSImage *)_dragImageForLinkElement:(NSDictionary *)element
+{
+    NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
+
+    BOOL drawURLString = YES;
+    BOOL clipURLString = NO, clipLabelString = NO;
+    
+    NSString *label = [element objectForKey: WebElementLinkLabelKey];
+    NSString *urlString = [linkURL _web_userVisibleString];
+    
+    if (!label) {
+	drawURLString = NO;
+	label = urlString;
+    }
+    
+    NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
+                                                   toHaveTrait:NSBoldFontMask];
+    NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
+    NSSize labelSize;
+    labelSize.width = [label _web_widthWithFont: labelFont];
+    labelSize.height = [labelFont ascender] - [labelFont descender];
+    if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
+        labelSize.width = MAX_DRAG_LABEL_WIDTH;
+        clipLabelString = YES;
+    }
+    
+    NSSize imageSize, urlStringSize;
+    imageSize.width += labelSize.width + DRAG_LABEL_BORDER_X * 2;
+    imageSize.height += labelSize.height + DRAG_LABEL_BORDER_Y * 2;
+    if (drawURLString) {
+	urlStringSize.width = [urlString _web_widthWithFont: urlFont];
+        urlStringSize.height = [urlFont ascender] - [urlFont descender];
+	imageSize.height += urlStringSize.height;
+	if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
+	    imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
+	    clipURLString = YES;
+	} else {
+	    imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
+	}
+    }
+    NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
+    [dragImage lockFocus];
+    
+    [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
+    
+    // Drag a rectangle with rounded corners/
+    NSBezierPath *path = [NSBezierPath bezierPath];
+    [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
+    [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
+    [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
+    [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
+    
+    [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
+    [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
+    [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
+    [path fill];
+        
+    NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
+    NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
+    if (drawURLString) {
+	if (clipURLString)
+	    urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
+
+        [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
+             withTopColor:topColor bottomColor:bottomColor font:urlFont];
+    }
+
+    if (clipLabelString)
+	    label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
+    [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
+             withTopColor:topColor bottomColor:bottomColor font:labelFont];
+    
+    [dragImage unlockFocus];
+    
+    return dragImage;
+}
+
+- (void)_handleMouseDragged:(NSEvent *)event
+{
+    // If the frame has a provisional data source, this view may be released.
+    // Don't allow drag because drag callbacks will reference this released view.
+    if ([[self _frame] provisionalDataSource]) {
+	return;
+    }
+
+    NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
+    NSDictionary *element = [self _elementAtPoint:mouseDownPoint];
+
+    NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
+    NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
+    BOOL isSelectedText = [[element objectForKey:WebElementIsSelectedKey] boolValue];
+
+    [_private->draggingImageURL release];
+    _private->draggingImageURL = nil;
+
+    // We must have started over something draggable:
+    ASSERT((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
+           (!imageURL && linkURL) || isSelectedText); 
+
+    NSPoint mouseDraggedPoint = [self convertPoint:[event locationInWindow] fromView:nil];
+    float deltaX = ABS(mouseDraggedPoint.x - mouseDownPoint.x);
+    float deltaY = ABS(mouseDraggedPoint.y - mouseDownPoint.y);
+    
+    // Drag hysteresis hasn't been met yet but we don't want to do other drag actions like selection.
+    if (((imageURL || linkURL) && deltaX < DragHysteresis && deltaY < DragHysteresis) ||
+        (isSelectedText && deltaX < TextDragHysteresis && deltaY < TextDragHysteresis)) {
+	return;
+    }
+    
+    if (imageURL) {
+	_private->draggingImageURL = [imageURL retain];
+        WebImageRenderer *image = [element objectForKey:WebElementImageKey];
+        ASSERT([image isKindOfClass:[WebImageRenderer class]]);
+        [self _web_dragPromisedImage:image
+                                rect:[[element objectForKey:WebElementImageRectKey] rectValue]
+                                 URL:linkURL ? linkURL : imageURL
+                               title:[element objectForKey:WebElementImageAltStringKey]
+                               event:_private->mouseDownEvent];
+        
+    } else if (linkURL) {
+        NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
+        NSString *label = [element objectForKey:WebElementLinkLabelKey];
+        [pasteboard _web_writeURL:linkURL andTitle:label withOwner:self];
+        NSImage *dragImage = [self _dragImageForLinkElement:element];
+        NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
+        [self dragImage:dragImage
+                     at:NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height)
+                 offset:offset
+                  event:event
+             pasteboard:pasteboard
+                 source:self
+              slideBack:NO];
+        
+    } else if (isSelectedText) {
+        NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
+        [self _writeSelectionToPasteboard:pasteboard];
+        NSImage *selectionImage = [[self _bridge] selectionImage];
+        [selectionImage _web_dissolveToFraction:WebDragImageAlpha];
+        NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
+        [self dragImage:selectionImage
+                     at:NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect))
+                 offset:NSMakeSize(mouseDownPoint.x, mouseDownPoint.y)
+                  event:_private->mouseDownEvent
+             pasteboard:pasteboard
+                 source:self
+              slideBack:YES];
+    } else {
+        ERROR("Attempt to drag unknown element");
+    }
+}
+
+- (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
+{
+    // FIXME: this really needs to be based on a timer
+    [self autoscroll:event];
+}
+
+- (BOOL)_mayStartDragWithMouseDragged:(NSEvent *)mouseDraggedEvent
+{
+    NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
+    NSDictionary *mouseDownElement = [self _elementAtPoint:mouseDownPoint];
+
+    NSURL *imageURL = [mouseDownElement objectForKey: WebElementImageURLKey];
+
+    if ((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
+        (!imageURL && [mouseDownElement objectForKey: WebElementLinkURLKey]) ||
+        ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
+         ([mouseDraggedEvent timestamp] - [_private->mouseDownEvent timestamp]) > TextDragDelay)) {
+        return YES;
+    }
+
+    return NO;
+}
+
+- (WebPluginController *)_pluginController
+{
+    return _private->pluginController;
+}
+
+- (void)_web_setPrintingModeRecursive
+{
+    [self _setPrinting:YES pageWidth:0 adjustViewSize:NO];
+    [super _web_setPrintingModeRecursive];
+}
+
+- (void)_web_clearPrintingModeRecursive
+{
+    [self _setPrinting:NO pageWidth:0 adjustViewSize:NO];
+    [super _web_clearPrintingModeRecursive];
+}
+
+- (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
+{
+    ASSERT(!_private->subviewsSetAside);
+    displayRect = NSIntersectionRect(displayRect, [self bounds]);
+
+    if (!testDirtyRect || [self needsDisplay]) {
+        if (testDirtyRect) {
+            NSRect dirtyRect = [self _dirtyRect];
+            displayRect = NSIntersectionRect(displayRect, dirtyRect);
+        }
+        if (!NSIsEmptyRect(displayRect)) {
+            if ([[self _bridge] needsLayout])
+                _private->needsLayout = YES;
+            if (_private->needsToApplyStyles || _private->needsLayout)
+                [self layout];
+        }
+    }
+
+    [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
+}
+
+- (NSRect)_selectionRect
+{
+    return [[self _bridge] selectionRect];
+}
+
+- (void)_startAutoscrollTimer
+{
+    if (_private->autoscrollTimer == nil) {
+        _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
+            target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
+    }
+}
+
+- (void)_stopAutoscrollTimer
+{
+    NSTimer *timer = _private->autoscrollTimer;
+    _private->autoscrollTimer = nil;
+    [timer invalidate];
+    [timer release];
+}
+
+- (void)_autoscroll
+{
+    NSEvent *mouseUpEvent = [NSApp nextEventMatchingMask:NSLeftMouseUpMask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:NO];
+    if (mouseUpEvent) {
+        return;
+    }
+
+    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
+        location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
+        modifierFlags:[[NSApp currentEvent] modifierFlags]
+        timestamp:[NSDate timeIntervalSinceReferenceDate]
+        windowNumber:[[self window] windowNumber]
+        context:[[NSApp currentEvent] context]
+        eventNumber:0 clickCount:0 pressure:0];
+    [self mouseDragged:fakeEvent];
+}
+
+ at end
+
+ at implementation NSView (WebHTMLViewPrivate)
+
+- (void)_web_setPrintingModeRecursive
+{
+    [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
+}
+
+- (void)_web_clearPrintingModeRecursive
+{
+    [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
+}
+
+- (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
+{
+    unsigned index, count;
+    for (index = 0, count = [_subviews count]; index < count; index++) {
+        NSView *subview = [_subviews objectAtIndex:index];
+        NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
+        [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
+    }
+}
+
+ at end
+
+ at implementation NSMutableDictionary (WebHTMLViewPrivate)
+
+- (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
+{
+    if (object == nil) {
+        [self removeObjectForKey:key];
+    } else {
+        [self setObject:object forKey:key];
+    }
+}
+
+ at end
+
+// The following is a workaround for
+// <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
+// The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
+// Since the category will be searched before the real class, we'll prevent the flag from being
+// set on the tool tip panel.
+
+ at interface NSToolTipPanel : NSPanel
+ at end
+
+ at interface NSToolTipPanel (WebHTMLViewPrivate)
+ at end
+
+ at implementation NSToolTipPanel (WebHTMLViewPrivate)
+
+- (void)setAcceptsMouseMovedEvents:(BOOL)flag
+{
+    // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
+}
+
+ at end
+
+
 @interface WebHTMLView (TextSizing) <_web_WebDocumentTextSizing>
 @end
 
@@ -42,10 +845,6 @@
 - (void)_web_makePluginViewsPerformSelector:(SEL)selector withObject:(id)object;
 @end
 
- at interface NSView (AppKitSecretsIKnowAbout)
-- (void)_setDrawsOwnDescendants:(BOOL)drawsOwnDescendants;
- at end
-
 @implementation WebHTMLView
 
 + (void)initialize
diff --git a/WebKit/WebView.subproj/WebHTMLViewPrivate.m b/WebKit/WebView.subproj/WebHTMLViewPrivate.m
deleted file mode 100644
index 77b381a..0000000
--- a/WebKit/WebView.subproj/WebHTMLViewPrivate.m
+++ /dev/null
@@ -1,820 +0,0 @@
-/*	
-    WebHTMLViewPrivate.m
-    Copyright 2002, Apple, Inc. All rights reserved.
-*/
-
-#import <WebKit/WebHTMLViewPrivate.h>
-
-#import <AppKit/NSResponder_Private.h>
-
-#import <WebKit/WebAssertions.h>
-#import <WebKit/WebBridge.h>
-#import <WebKit/WebFramePrivate.h>
-#import <WebKit/WebFrameViewPrivate.h>
-#import <WebKit/WebImageRenderer.h>
-#import <WebKit/WebKitNSStringExtras.h>
-#import <WebKit/WebNSImageExtras.h>
-#import <WebKit/WebNSPasteboardExtras.h>
-#import <WebKit/WebNSURLExtras.h>
-#import <WebKit/WebNSViewExtras.h>
-#import <WebKit/WebPluginController.h>
-#import <WebKit/WebPreferences.h>
-#import <WebKit/WebStringTruncator.h>
-#import <WebKit/WebViewPrivate.h>
-
-// These are a little larger than typical because dragging links is a fairly
-// advanced feature that can confuse non-power-users
-#define DragHysteresis  		10.0
-#define TextDragHysteresis  		3.0
-#define TextDragDelay			0.15
-
-#define AUTOSCROLL_INTERVAL             0.1
-
-#define DRAG_LABEL_BORDER_X		4.0
-#define DRAG_LABEL_BORDER_Y		2.0
-#define DRAG_LABEL_RADIUS		5.0
-#define DRAG_LABEL_BORDER_Y_OFFSET              2.0
-
-#define MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP	120.0
-#define MAX_DRAG_LABEL_WIDTH                    320.0
-
-#define DRAG_LINK_LABEL_FONT_SIZE   11.0
-#define DRAG_LINK_URL_FONT_SIZE   10.0
-
-static BOOL forceRealHitTest = NO;
-
- at interface WebHTMLView (WebHTMLViewPrivate)
-- (void)_setPrinting:(BOOL)printing pageWidth:(float)pageWidth adjustViewSize:(BOOL)adjustViewSize;
- at end
-
-// Any non-zero value will do, but using somethign recognizable might help us debug some day.
-#define TRACKING_RECT_TAG 0xBADFACE
-
-
- at interface NSView (AppKitSecretsIKnowAbout)
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView testDirtyRect:(BOOL)testDirtyRect;
-- (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect;
-- (NSRect)_dirtyRect;
- at end
-
- at interface NSView (WebHTMLViewPrivate)
-- (void)_web_setPrintingModeRecursive;
-- (void)_web_clearPrintingModeRecursive;
-- (void)_web_layoutIfNeededRecursive:(NSRect)rect testDirtyRect:(bool)testDirtyRect;
- at end
-
- at interface NSMutableDictionary (WebHTMLViewPrivate)
-- (void)_web_setObjectIfNotNil:(id)object forKey:(id)key;
- at end
-
- at implementation WebHTMLViewPrivate
-
-- (void)dealloc
-{
-    ASSERT(autoscrollTimer == nil);
-    
-    [pluginController destroyAllPlugins];
-    
-    [mouseDownEvent release];
-    [draggingImageURL release];
-    [pluginController release];
-    [toolTip release];
-    
-    [super dealloc];
-}
-
- at end
-
-
- at implementation WebHTMLView (WebPrivate)
-
-- (void)_adjustFrames
-{
-    // Ick!  khtml set the frame size during layout and
-    // the frame origins during drawing!  So we have to 
-    // layout and do a draw with rendering disabled to
-    // correclty adjust the frames.
-    [[self _bridge] adjustFrames:[self frame]];
-}
-
-- (void)_reset
-{
-    [WebImageRenderer stopAnimationsInView:self];
-}
-
-- (WebView *)_webView
-{
-    // We used to use the view hierarchy exclusively here, but that won't work
-    // right when the first viewDidMoveToSuperview call is done, and this wil.
-    return [[self _frame] webView];
-}
-
-- (WebFrame *)_frame
-{
-    WebFrameView *webFrameView = [self _web_parentWebFrameView];
-    return [webFrameView webFrame];
-}
-
-// Required so view can access the part's selection.
-- (WebBridge *)_bridge
-{
-    return [[self _frame] _bridge];
-}
-
-+ (void)_postFlagsChangedEvent:(NSEvent *)flagsChangedEvent
-{
-    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
-        location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]]
-        modifierFlags:[flagsChangedEvent modifierFlags]
-        timestamp:[flagsChangedEvent timestamp]
-        windowNumber:[flagsChangedEvent windowNumber]
-        context:[flagsChangedEvent context]
-        eventNumber:0 clickCount:0 pressure:0];
-
-    // Pretend it's a mouse move.
-    [[NSNotificationCenter defaultCenter]
-        postNotificationName:NSMouseMovedNotification object:self
-        userInfo:[NSDictionary dictionaryWithObject:fakeEvent forKey:@"NSEvent"]];
-}
-
-- (void)_updateMouseoverWithFakeEvent
-{
-    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved
-        location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
-        modifierFlags:[[NSApp currentEvent] modifierFlags]
-        timestamp:[NSDate timeIntervalSinceReferenceDate]
-        windowNumber:[[self window] windowNumber]
-        context:[[NSApp currentEvent] context]
-        eventNumber:0 clickCount:0 pressure:0];
-    
-    [self _updateMouseoverWithEvent:fakeEvent];
-}
-
-- (void)_frameOrBoundsChanged
-{
-    if (!NSEqualSizes(_private->lastLayoutSize, [(NSClipView *)[self superview] documentVisibleRect].size)) {
-        [self setNeedsLayout:YES];
-        [self setNeedsDisplay:YES];
-    }
-
-    SEL selector = @selector(_updateMouseoverWithFakeEvent);
-    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];
-    [self performSelector:selector withObject:nil afterDelay:0];
-}
-
-- (NSDictionary *)_elementAtPoint:(NSPoint)point
-{
-    NSDictionary *elementInfoWC = [[self _bridge] elementAtPoint:point];
-    NSMutableDictionary *elementInfo = [elementInfoWC mutableCopy];
-
-    // Convert URL strings to NSURLs
-    [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementLinkURLKey]] forKey:WebElementLinkURLKey];
-    [elementInfo _web_setObjectIfNotNil:[NSURL _web_URLWithDataAsString:[elementInfoWC objectForKey:WebElementImageURLKey]] forKey:WebElementImageURLKey];
-    
-    WebFrameView *webFrameView = [self _web_parentWebFrameView];
-    ASSERT(webFrameView);
-    WebFrame *webFrame = [webFrameView webFrame];
-    
-    if (webFrame) {
-        NSString *frameName = [elementInfoWC objectForKey:WebElementLinkTargetFrameKey];
-        if ([frameName length] == 0) {
-            [elementInfo setObject:webFrame forKey:WebElementLinkTargetFrameKey];
-        } else {
-            WebFrame *wf = [webFrame findFrameNamed:frameName];
-            if (wf != nil)
-                [elementInfo setObject:wf forKey:WebElementLinkTargetFrameKey];
-            else
-                [elementInfo removeObjectForKey:WebElementLinkTargetFrameKey];
-        }
-    
-        [elementInfo setObject:webFrame forKey:WebElementFrameKey];
-    }
-    
-    return [elementInfo autorelease];
-}
-
-- (void)_setAsideSubviews
-{
-    ASSERT(!_private->subviewsSetAside);
-    ASSERT(_private->savedSubviews == nil);
-    _private->savedSubviews = _subviews;
-    _subviews = nil;
-    _private->subviewsSetAside = YES;
- }
- 
- - (void)_restoreSubviews
- {
-    ASSERT(_private->subviewsSetAside);
-    ASSERT(_subviews == nil);
-    _subviews = _private->savedSubviews;
-    _private->savedSubviews = nil;
-    _private->subviewsSetAside = NO;
-}
-
-// Don't let AppKit even draw subviews. We take care of that.
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)rect isVisibleRect:(BOOL)isVisibleRect rectIsVisibleRectForView:(NSView *)visibleView testDirtyRect:(BOOL)testDirtyRect
-{
-    // This helps when we print as part of a larger print process.
-    // If the WebHTMLView itself is what we're printing, then we will never have to do this.
-    BOOL wasInPrintingMode = _private->printing;
-    BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
-    if (wasInPrintingMode != isPrinting) {
-        if (isPrinting) {
-            [self _web_setPrintingModeRecursive];
-        } else {
-            [self _web_clearPrintingModeRecursive];
-        }
-    }
-
-    [self _web_layoutIfNeededRecursive: rect testDirtyRect:YES];
-
-    [self _setAsideSubviews];
-    [super _recursiveDisplayRectIfNeededIgnoringOpacity:rect isVisibleRect:isVisibleRect
-        rectIsVisibleRectForView:visibleView testDirtyRect:testDirtyRect];
-    [self _restoreSubviews];
-
-    if (wasInPrintingMode != isPrinting) {
-        if (wasInPrintingMode) {
-            [self _web_setPrintingModeRecursive];
-        } else {
-            [self _web_clearPrintingModeRecursive];
-        }
-    }
-}
-
-// Don't let AppKit even draw subviews. We take care of that.
-- (void)_recursiveDisplayAllDirtyWithLockFocus:(BOOL)needsLockFocus visRect:(NSRect)visRect
-{
-    BOOL needToSetAsideSubviews = !_private->subviewsSetAside;
-
-    BOOL wasInPrintingMode = _private->printing;
-    BOOL isPrinting = ![NSGraphicsContext currentContextDrawingToScreen];
-
-    if (needToSetAsideSubviews) {
-        // This helps when we print as part of a larger print process.
-        // If the WebHTMLView itself is what we're printing, then we will never have to do this.
-        if (wasInPrintingMode != isPrinting) {
-            if (isPrinting) {
-                [self _web_setPrintingModeRecursive];
-            } else {
-                [self _web_clearPrintingModeRecursive];
-            }
-        }
-
-        [self _web_layoutIfNeededRecursive: visRect testDirtyRect:NO];
-
-        [self _setAsideSubviews];
-    }
-    
-    [super _recursiveDisplayAllDirtyWithLockFocus:needsLockFocus visRect:visRect];
-    
-    if (needToSetAsideSubviews) {
-        if (wasInPrintingMode != isPrinting) {
-            if (wasInPrintingMode) {
-                [self _web_setPrintingModeRecursive];
-            } else {
-                [self _web_clearPrintingModeRecursive];
-            }
-        }
-
-        [self _restoreSubviews];
-    }
-}
-
-- (BOOL)_insideAnotherHTMLView
-{
-    NSView *view = self;
-    while ((view = [view superview])) {
-        if ([view isKindOfClass:[WebHTMLView class]]) {
-            return YES;
-        }
-    }
-    return NO;
-}
-
-- (void)scrollPoint:(NSPoint)point
-{
-    // Since we can't subclass NSTextView to do what we want, we have to second guess it here.
-    // If we get called during the handling of a key down event, we assume the call came from
-    // NSTextView, and ignore it and use our own code to decide how to page up and page down
-    // We are smarter about how far to scroll, and we have "superview scrolling" logic.
-    NSEvent *event = [[self window] currentEvent];
-    if ([event type] == NSKeyDown) {
-        const unichar pageUp = NSPageUpFunctionKey;
-        if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageUp length:1]].length == 1) {
-            [self tryToPerform:@selector(scrollPageUp:) with:nil];
-            return;
-        }
-        const unichar pageDown = NSPageDownFunctionKey;
-        if ([[event characters] rangeOfString:[NSString stringWithCharacters:&pageDown length:1]].length == 1) {
-            [self tryToPerform:@selector(scrollPageDown:) with:nil];
-            return;
-        }
-    }
-    
-    [super scrollPoint:point];
-}
-
-- (NSView *)hitTest:(NSPoint)point
-{
-    // WebHTMLView objects handle all left mouse clicks for objects inside them.
-    // That does not include left mouse clicks with the control key held down.
-    BOOL captureHitsOnSubviews;
-    if (forceRealHitTest) {
-        captureHitsOnSubviews = NO;
-    } else {
-        NSEvent *event = [[self window] currentEvent];
-        captureHitsOnSubviews = [event type] == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask) == 0;
-    }
-    if (!captureHitsOnSubviews) {
-        return [super hitTest:point];
-    }
-    if ([[self superview] mouse:point inRect:[self frame]]) {
-        return self;
-    }
-    return nil;
-}
-
-static WebHTMLView *lastHitView = nil;
-
-- (void)_clearLastHitViewIfSelf
-{
-    if (lastHitView == self) {
-	lastHitView = nil;
-    }
-}
-
-- (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
-{
-    ASSERT(_private->trackingRectOwner == nil);
-    _private->trackingRectOwner = owner;
-    _private->trackingRectUserData = data;
-    return TRACKING_RECT_TAG;
-}
-
-- (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
-{
-    ASSERT(tag == TRACKING_RECT_TAG);
-    return [self addTrackingRect:rect owner:owner userData:data assumeInside:assumeInside];
-}
-
-- (void)removeTrackingRect:(NSTrackingRectTag)tag
-{
-    ASSERT(tag == TRACKING_RECT_TAG);
-    if (_private != nil) {
-        ASSERT(_private->trackingRectOwner != nil);
-        _private->trackingRectOwner = nil;
-    }
-}
-
-- (void)_sendToolTipMouseExited
-{
-    // Nothing matters except window, trackingNumber, and userData.
-    NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited
-        location:NSMakePoint(0, 0)
-        modifierFlags:0
-        timestamp:0
-        windowNumber:[[self window] windowNumber]
-        context:NULL
-        eventNumber:0
-        trackingNumber:TRACKING_RECT_TAG
-        userData:_private->trackingRectUserData];
-    [_private->trackingRectOwner mouseExited:fakeEvent];
-}
-
-- (void)_sendToolTipMouseEntered
-{
-    // Nothing matters except window, trackingNumber, and userData.
-    NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered
-        location:NSMakePoint(0, 0)
-        modifierFlags:0
-        timestamp:0
-        windowNumber:[[self window] windowNumber]
-        context:NULL
-        eventNumber:0
-        trackingNumber:TRACKING_RECT_TAG
-        userData:_private->trackingRectUserData];
-    [_private->trackingRectOwner mouseEntered:fakeEvent];
-}
-
-- (void)_setToolTip:(NSString *)string
-{
-    NSString *toolTip = [string length] == 0 ? nil : string;
-    NSString *oldToolTip = _private->toolTip;
-    if ((toolTip == nil || oldToolTip == nil) ? toolTip == oldToolTip : [toolTip isEqualToString:oldToolTip]) {
-        return;
-    }
-    if (oldToolTip) {
-        [self _sendToolTipMouseExited];
-        [oldToolTip release];
-    }
-    _private->toolTip = [toolTip copy];
-    if (toolTip) {
-        if (_private->toolTipTag) {
-            [self removeToolTip:_private->toolTipTag];
-        }
-        NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000);
-        _private->toolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL];
-        [self _sendToolTipMouseEntered];
-    }
-}
-
-- (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
-{
-    return [[_private->toolTip copy] autorelease];
-}
-
-- (void)_updateMouseoverWithEvent:(NSEvent *)event
-{
-    WebHTMLView *view = nil;
-    if ([event window] == [self window]) {
-        forceRealHitTest = YES;
-        NSView *hitView = [[[self window] contentView] hitTest:[event locationInWindow]];
-        forceRealHitTest = NO;
-        while (hitView) {
-            if ([hitView isKindOfClass:[WebHTMLView class]]) {
-                view = (WebHTMLView *)hitView;
-                break;
-            }
-            hitView = [hitView superview];
-        }
-    }
-
-    if (lastHitView != view && lastHitView != nil) {
-	// If we are moving out of a view (or frame), let's pretend the mouse moved
-	// all the way out of that view. But we have to account for scrolling, because
-	// khtml doesn't understand our clipping.
-	NSRect visibleRect = [[[[lastHitView _frame] frameView] _scrollView] documentVisibleRect];
-	float yScroll = visibleRect.origin.y;
-	float xScroll = visibleRect.origin.x;
-
-	event = [NSEvent mouseEventWithType:NSMouseMoved
-			 location:NSMakePoint(-1 - xScroll, -1 - yScroll )
-			 modifierFlags:[[NSApp currentEvent] modifierFlags]
-			 timestamp:[NSDate timeIntervalSinceReferenceDate]
-			 windowNumber:[[self window] windowNumber]
-			 context:[[NSApp currentEvent] context]
-			 eventNumber:0 clickCount:0 pressure:0];
-	[[lastHitView _bridge] mouseMoved:event];
-    }
-
-    lastHitView = view;
-    
-    NSDictionary *element;
-    if (view == nil) {
-        element = nil;
-    } else {
-        [[view _bridge] mouseMoved:event];
-
-        NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
-        element = [view _elementAtPoint:point];
-    }
-
-    // Have the web view send a message to the delegate so it can do status bar display.
-    [[self _webView] _mouseDidMoveOverElement:element modifierFlags:[event modifierFlags]];
-
-    // Set a tool tip; it won't show up right away but will if the user pauses.
-    [self _setToolTip:[element objectForKey:WebCoreElementTitleKey]];
-}
-
-+ (NSArray *)_pasteboardTypes
-{
-    return [NSArray arrayWithObjects:
-#if SUPPORT_HTML_PBOARD
-        NSHTMLPboardType,
-#endif
-        NSRTFPboardType, NSRTFDPboardType, NSStringPboardType, nil];
-}
-
-- (void)_writeSelectionToPasteboard:(NSPasteboard *)pasteboard
-{
-    [pasteboard declareTypes:[[self class] _pasteboardTypes] owner:nil];
-
-#if SUPPORT_HTML_PBOARD
-    // Put HTML on the pasteboard.
-    [pasteboard setData:??? forType:NSHTMLPboardType];
-#endif
-
-    // Put attributed string on the pasteboard (RTF format).
-    NSAttributedString *attributedString = [self selectedAttributedString];
-    NSRange range = NSMakeRange(0, [attributedString length]);
-    NSData *attributedData = [attributedString RTFFromRange:range documentAttributes:nil];
-    [pasteboard setData:attributedData forType:NSRTFPboardType];
-
-    attributedData = [attributedString RTFDFromRange:range documentAttributes:nil];
-    [pasteboard setData:attributedData forType:NSRTFDPboardType];
-    
-    // Put plain string on the pasteboard.
-    [pasteboard setString:[self selectedString] forType:NSStringPboardType];
-}
-
-
--(NSImage *)_dragImageForLinkElement:(NSDictionary *)element
-{
-    NSURL *linkURL = [element objectForKey: WebElementLinkURLKey];
-
-    BOOL drawURLString = YES;
-    BOOL clipURLString = NO, clipLabelString = NO;
-    
-    NSString *label = [element objectForKey: WebElementLinkLabelKey];
-    NSString *urlString = [linkURL _web_userVisibleString];
-    
-    if (!label) {
-	drawURLString = NO;
-	label = urlString;
-    }
-    
-    NSFont *labelFont = [[NSFontManager sharedFontManager] convertFont:[NSFont systemFontOfSize:DRAG_LINK_LABEL_FONT_SIZE]
-                                                   toHaveTrait:NSBoldFontMask];
-    NSFont *urlFont = [NSFont systemFontOfSize: DRAG_LINK_URL_FONT_SIZE];
-    NSSize labelSize;
-    labelSize.width = [label _web_widthWithFont: labelFont];
-    labelSize.height = [labelFont ascender] - [labelFont descender];
-    if (labelSize.width > MAX_DRAG_LABEL_WIDTH){
-        labelSize.width = MAX_DRAG_LABEL_WIDTH;
-        clipLabelString = YES;
-    }
-    
-    NSSize imageSize, urlStringSize;
-    imageSize.width += labelSize.width + DRAG_LABEL_BORDER_X * 2;
-    imageSize.height += labelSize.height + DRAG_LABEL_BORDER_Y * 2;
-    if (drawURLString) {
-	urlStringSize.width = [urlString _web_widthWithFont: urlFont];
-        urlStringSize.height = [urlFont ascender] - [urlFont descender];
-	imageSize.height += urlStringSize.height;
-	if (urlStringSize.width > MAX_DRAG_LABEL_WIDTH) {
-	    imageSize.width = MAX(MAX_DRAG_LABEL_WIDTH + DRAG_LABEL_BORDER_X * 2, MIN_DRAG_LABEL_WIDTH_BEFORE_CLIP);
-	    clipURLString = YES;
-	} else {
-	    imageSize.width = MAX(labelSize.width + DRAG_LABEL_BORDER_X * 2, urlStringSize.width + DRAG_LABEL_BORDER_X * 2);
-	}
-    }
-    NSImage *dragImage = [[[NSImage alloc] initWithSize: imageSize] autorelease];
-    [dragImage lockFocus];
-    
-    [[NSColor colorWithCalibratedRed: 0.7 green: 0.7 blue: 0.7 alpha: 0.8] set];
-    
-    // Drag a rectangle with rounded corners/
-    NSBezierPath *path = [NSBezierPath bezierPath];
-    [path appendBezierPathWithOvalInRect: NSMakeRect(0,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
-    [path appendBezierPathWithOvalInRect: NSMakeRect(0,imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
-    [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height - DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
-    [path appendBezierPathWithOvalInRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS * 2,0, DRAG_LABEL_RADIUS * 2, DRAG_LABEL_RADIUS * 2)];
-    
-    [path appendBezierPathWithRect: NSMakeRect(DRAG_LABEL_RADIUS, 0, imageSize.width - DRAG_LABEL_RADIUS * 2, imageSize.height)];
-    [path appendBezierPathWithRect: NSMakeRect(0, DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 10, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
-    [path appendBezierPathWithRect: NSMakeRect(imageSize.width - DRAG_LABEL_RADIUS - 20,DRAG_LABEL_RADIUS, DRAG_LABEL_RADIUS + 20, imageSize.height - 2 * DRAG_LABEL_RADIUS)];
-    [path fill];
-        
-    NSColor *topColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.75];
-    NSColor *bottomColor = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
-    if (drawURLString) {
-	if (clipURLString)
-	    urlString = [WebStringTruncator centerTruncateString: urlString toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:urlFont];
-
-        [urlString _web_drawDoubledAtPoint:NSMakePoint(DRAG_LABEL_BORDER_X, DRAG_LABEL_BORDER_Y - [urlFont descender]) 
-             withTopColor:topColor bottomColor:bottomColor font:urlFont];
-    }
-
-    if (clipLabelString)
-	    label = [WebStringTruncator rightTruncateString: label toWidth:imageSize.width - (DRAG_LABEL_BORDER_X * 2) withFont:labelFont];
-    [label _web_drawDoubledAtPoint:NSMakePoint (DRAG_LABEL_BORDER_X, imageSize.height - DRAG_LABEL_BORDER_Y_OFFSET - [labelFont pointSize])
-             withTopColor:topColor bottomColor:bottomColor font:labelFont];
-    
-    [dragImage unlockFocus];
-    
-    return dragImage;
-}
-
-- (void)_handleMouseDragged:(NSEvent *)event
-{
-    // If the frame has a provisional data source, this view may be released.
-    // Don't allow drag because drag callbacks will reference this released view.
-    if ([[self _frame] provisionalDataSource]) {
-	return;
-    }
-
-    NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
-    NSDictionary *element = [self _elementAtPoint:mouseDownPoint];
-
-    NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
-    NSURL *imageURL = [element objectForKey:WebElementImageURLKey];
-    BOOL isSelectedText = [[element objectForKey:WebElementIsSelectedKey] boolValue];
-
-    [_private->draggingImageURL release];
-    _private->draggingImageURL = nil;
-
-    // We must have started over something draggable:
-    ASSERT((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
-           (!imageURL && linkURL) || isSelectedText); 
-
-    NSPoint mouseDraggedPoint = [self convertPoint:[event locationInWindow] fromView:nil];
-    float deltaX = ABS(mouseDraggedPoint.x - mouseDownPoint.x);
-    float deltaY = ABS(mouseDraggedPoint.y - mouseDownPoint.y);
-    
-    // Drag hysteresis hasn't been met yet but we don't want to do other drag actions like selection.
-    if (((imageURL || linkURL) && deltaX < DragHysteresis && deltaY < DragHysteresis) ||
-        (isSelectedText && deltaX < TextDragHysteresis && deltaY < TextDragHysteresis)) {
-	return;
-    }
-    
-    if (imageURL) {
-	_private->draggingImageURL = [imageURL retain];
-        WebImageRenderer *image = [element objectForKey:WebElementImageKey];
-        ASSERT([image isKindOfClass:[WebImageRenderer class]]);
-        [self _web_dragPromisedImage:image
-                                rect:[[element objectForKey:WebElementImageRectKey] rectValue]
-                                 URL:linkURL ? linkURL : imageURL
-                               title:[element objectForKey:WebElementImageAltStringKey]
-                               event:_private->mouseDownEvent];
-        
-    } else if (linkURL) {
-        NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
-        NSString *label = [element objectForKey:WebElementLinkLabelKey];
-        [pasteboard _web_writeURL:linkURL andTitle:label withOwner:self];
-        NSImage *dragImage = [self _dragImageForLinkElement:element];
-        NSSize offset = NSMakeSize([dragImage size].width / 2, -DRAG_LABEL_BORDER_Y);
-        [self dragImage:dragImage
-                     at:NSMakePoint(mouseDraggedPoint.x - offset.width, mouseDraggedPoint.y - offset.height)
-                 offset:offset
-                  event:event
-             pasteboard:pasteboard
-                 source:self
-              slideBack:NO];
-        
-    } else if (isSelectedText) {
-        NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard];
-        [self _writeSelectionToPasteboard:pasteboard];
-        NSImage *selectionImage = [[self _bridge] selectionImage];
-        [selectionImage _web_dissolveToFraction:WebDragImageAlpha];
-        NSRect visibleSelectionRect = [[self _bridge] visibleSelectionRect];
-        [self dragImage:selectionImage
-                     at:NSMakePoint(NSMinX(visibleSelectionRect), NSMaxY(visibleSelectionRect))
-                 offset:NSMakeSize(mouseDownPoint.x, mouseDownPoint.y)
-                  event:_private->mouseDownEvent
-             pasteboard:pasteboard
-                 source:self
-              slideBack:YES];
-    } else {
-        ERROR("Attempt to drag unknown element");
-    }
-}
-
-- (void)_handleAutoscrollForMouseDragged:(NSEvent *)event
-{
-    // FIXME: this really needs to be based on a timer
-    [self autoscroll:event];
-}
-
-- (BOOL)_mayStartDragWithMouseDragged:(NSEvent *)mouseDraggedEvent
-{
-    NSPoint mouseDownPoint = [self convertPoint:[_private->mouseDownEvent locationInWindow] fromView:nil];
-    NSDictionary *mouseDownElement = [self _elementAtPoint:mouseDownPoint];
-
-    NSURL *imageURL = [mouseDownElement objectForKey: WebElementImageURLKey];
-
-    if ((imageURL && [[WebPreferences standardPreferences] loadsImagesAutomatically]) ||
-        (!imageURL && [mouseDownElement objectForKey: WebElementLinkURLKey]) ||
-        ([[mouseDownElement objectForKey:WebElementIsSelectedKey] boolValue] &&
-         ([mouseDraggedEvent timestamp] - [_private->mouseDownEvent timestamp]) > TextDragDelay)) {
-        return YES;
-    }
-
-    return NO;
-}
-
-- (WebPluginController *)_pluginController
-{
-    return _private->pluginController;
-}
-
-- (void)_web_setPrintingModeRecursive
-{
-    [self _setPrinting:YES pageWidth:0 adjustViewSize:NO];
-    [super _web_setPrintingModeRecursive];
-}
-
-- (void)_web_clearPrintingModeRecursive
-{
-    [self _setPrinting:NO pageWidth:0 adjustViewSize:NO];
-    [super _web_clearPrintingModeRecursive];
-}
-
-- (void)_web_layoutIfNeededRecursive:(NSRect)displayRect testDirtyRect:(bool)testDirtyRect
-{
-    ASSERT(!_private->subviewsSetAside);
-    displayRect = NSIntersectionRect(displayRect, [self bounds]);
-
-    if (!testDirtyRect || [self needsDisplay]) {
-        if (testDirtyRect) {
-            NSRect dirtyRect = [self _dirtyRect];
-            displayRect = NSIntersectionRect(displayRect, dirtyRect);
-        }
-        if (!NSIsEmptyRect(displayRect)) {
-            if ([[self _bridge] needsLayout])
-                _private->needsLayout = YES;
-            if (_private->needsToApplyStyles || _private->needsLayout)
-                [self layout];
-        }
-    }
-
-    [super _web_layoutIfNeededRecursive: displayRect testDirtyRect: NO];
-}
-
-- (NSRect)_selectionRect
-{
-    return [[self _bridge] selectionRect];
-}
-
-- (void)_startAutoscrollTimer
-{
-    if (_private->autoscrollTimer == nil) {
-        _private->autoscrollTimer = [[NSTimer scheduledTimerWithTimeInterval:AUTOSCROLL_INTERVAL
-            target:self selector:@selector(_autoscroll) userInfo:nil repeats:YES] retain];
-    }
-}
-
-- (void)_stopAutoscrollTimer
-{
-    NSTimer *timer = _private->autoscrollTimer;
-    _private->autoscrollTimer = nil;
-    [timer invalidate];
-    [timer release];
-}
-
-- (void)_autoscroll
-{
-    NSEvent *mouseUpEvent = [NSApp nextEventMatchingMask:NSLeftMouseUpMask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:NO];
-    if (mouseUpEvent) {
-        return;
-    }
-
-    NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged
-        location:[[self window] convertScreenToBase:[NSEvent mouseLocation]]
-        modifierFlags:[[NSApp currentEvent] modifierFlags]
-        timestamp:[NSDate timeIntervalSinceReferenceDate]
-        windowNumber:[[self window] windowNumber]
-        context:[[NSApp currentEvent] context]
-        eventNumber:0 clickCount:0 pressure:0];
-    [self mouseDragged:fakeEvent];
-}
-
- at end
-
- at implementation NSView (WebHTMLViewPrivate)
-
-- (void)_web_setPrintingModeRecursive
-{
-    [_subviews makeObjectsPerformSelector:@selector(_web_setPrintingModeRecursive)];
-}
-
-- (void)_web_clearPrintingModeRecursive
-{
-    [_subviews makeObjectsPerformSelector:@selector(_web_clearPrintingModeRecursive)];
-}
-
-- (void)_web_layoutIfNeededRecursive: (NSRect)rect testDirtyRect:(bool)testDirtyRect
-{
-    unsigned index, count;
-    for (index = 0, count = [_subviews count]; index < count; index++) {
-        NSView *subview = [_subviews objectAtIndex:index];
-        NSRect dirtiedSubviewRect = [subview convertRect: rect fromView: self];
-        [subview _web_layoutIfNeededRecursive: dirtiedSubviewRect testDirtyRect:testDirtyRect];
-    }
-}
-
- at end
-
- at implementation NSMutableDictionary (WebHTMLViewPrivate)
-
-- (void)_web_setObjectIfNotNil:(id)object forKey:(id)key
-{
-    if (object == nil) {
-        [self removeObjectForKey:key];
-    } else {
-        [self setObject:object forKey:key];
-    }
-}
-
- at end
-
-// The following is a workaround for
-// <rdar://problem/3429631> window stops getting mouse moved events after first tooltip appears
-// The trick is to define a category on NSToolTipPanel that implements setAcceptsMouseMovedEvents:.
-// Since the category will be searched before the real class, we'll prevent the flag from being
-// set on the tool tip panel.
-
- at interface NSToolTipPanel : NSPanel
- at end
-
- at interface NSToolTipPanel (WebHTMLViewPrivate)
- at end
-
- at implementation NSToolTipPanel (WebHTMLViewPrivate)
-
-- (void)setAcceptsMouseMovedEvents:(BOOL)flag
-{
-    // Do nothing, preventing the tool tip panel from trying to accept mouse-moved events.
-}
-
- at end
diff --git a/WebKit/WebView.subproj/WebView.m b/WebKit/WebView.subproj/WebView.m
index 5bef728..6383087 100644
--- a/WebKit/WebView.subproj/WebView.m
+++ b/WebKit/WebView.subproj/WebView.m
@@ -37,6 +37,19 @@
 #import <Foundation/NSUserDefaults_NSURLExtras.h>
 #import <Foundation/NSURLConnection.h>
 
+#import <Foundation/NSData_NSURLExtras.h>
+#import <Foundation/NSDictionary_NSURLExtras.h>
+#import <Foundation/NSURLDownloadPrivate.h>
+#import <Foundation/NSURLFileTypeMappings.h>
+#import <WebCore/WebCoreEncodings.h>
+#import <WebCore/WebCoreSettings.h>
+#import <WebKit/WebDefaultFrameLoadDelegate.h>
+#import <WebKit/WebDefaultPolicyDelegate.h>
+#import <WebKit/WebDefaultResourceLoadDelegate.h>
+#import <WebKit/WebDefaultUIDelegate.h>
+#import <WebKit/WebDownload.h>
+#import <WebKit/WebFormDelegatePrivate.h>
+
 static const struct UserAgentSpoofTableEntry *_web_findSpoofTableEntry(const char *, unsigned);
 
 // Turn off inlining to avoid warning with newer gcc.
@@ -62,6 +75,891 @@ NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotificatio
 
 enum { WebViewVersion = 2 };
 
+
+static NSMutableSet *schemesWithRepresentationsSet;
+
+NSString *_WebCanGoBackKey = @"canGoBack";
+NSString *_WebCanGoForwardKey = @"canGoForward";
+NSString *_WebEstimatedProgressKey = @"estimatedProgress";
+NSString *_WebIsLoadingKey = @"isLoading";
+NSString *_WebMainFrameIconKey = @"mainFrameIcon";
+NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
+NSString *_WebMainFrameURLKey = @"mainFrameURL";
+
+ at interface WebProgressItem : NSObject
+{
+ at public
+    long long bytesReceived;
+    long long estimatedLength;
+}
+ at end
+
+ at implementation WebProgressItem
+ at end
+
+ at implementation WebViewPrivate
+
+- init 
+{
+    backForwardList = [[WebBackForwardList alloc] init];
+    textSizeMultiplier = 1;
+    progressNotificationInterval = 0.02;
+    settings = [[WebCoreSettings alloc] init];
+
+    return self;
+}
+
+- (void)dealloc
+{
+    ASSERT(!mainFrame);
+    
+    [backForwardList release];
+    [applicationNameForUserAgent release];
+    [userAgentOverride release];
+    int i;
+    for (i = 0; i != NumUserAgentStringTypes; ++i) {
+        [userAgent[i] release];
+    }
+    
+    [preferences release];
+    [settings release];
+    [hostWindow release];
+    
+    [policyDelegateForwarder release];
+    [resourceProgressDelegateForwarder release];
+    [UIDelegateForwarder release];
+    [frameLoadDelegateForwarder release];
+    
+    [progressItems release];
+    
+    [super dealloc];
+}
+
+ at end
+
+
+ at implementation WebView (WebPrivate)
+
++ (BOOL)canShowFile:(NSString *)path
+{
+    NSString *MIMEType;
+
+    MIMEType = [WebView _MIMETypeForFile:path];
+    return [[self class] canShowMIMEType:MIMEType];
+}
+
++ (NSString *)suggestedFileExtensionForMIMEType: (NSString *)type
+{
+    return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
+}
+
+- (void)_close
+{
+    if (_private->setName != nil) {
+        [WebViewSets removeWebView:self fromSetNamed:_private->setName];
+        [_private->setName release];
+        _private->setName = nil;
+    }
+
+    [_private->mainFrame _detachFromParent];
+    [_private->mainFrame release];
+    _private->mainFrame = nil;
+    
+    // Clear the page cache so we call destroy on all the plug-ins in the page cache to break any retain cycles.
+    // See comment in [WebHistoryItem _releaseAllPendingPageCaches] for more information.
+    [_private->backForwardList _clearPageCache];
+}
+
+- (WebFrame *)_createFrameNamed:(NSString *)fname inParent:(WebFrame *)parent allowsScrolling:(BOOL)allowsScrolling
+{
+    WebFrameView *childView = [[WebFrameView alloc] initWithFrame:NSMakeRect(0,0,0,0)];
+
+    [childView _setWebView:self];
+    [childView setAllowsScrolling:allowsScrolling];
+    
+    WebFrame *newFrame = [[WebFrame alloc] initWithName:fname webFrameView:childView webView:self];
+
+    [childView release];
+
+    [parent _addChild:newFrame];
+    
+    [newFrame release];
+        
+    return newFrame;
+}
+
+- (void)_finishedLoadingResourceFromDataSource: (WebDataSource *)dataSource
+{
+    WebFrame *frame = [dataSource webFrame];
+    
+    ASSERT(dataSource != nil);
+    
+    // This resource has completed, so check if the load is complete for all frames.
+    if (frame != nil) {
+        [frame _transitionToLayoutAcceptable];
+        [frame _checkLoadComplete];
+    }
+}
+
+- (void)_mainReceivedBytesSoFar: (unsigned)bytesSoFar fromDataSource: (WebDataSource *)dataSource complete: (BOOL)isComplete
+{
+    WebFrame *frame = [dataSource webFrame];
+    
+    ASSERT(dataSource != nil);
+
+    // The frame may be nil if a previously cancelled load is still making progress callbacks.
+    if (frame == nil)
+        return;
+        
+    // This resource has completed, so check if the load is complete for all frames.
+    if (isComplete){
+        // If the load is complete, mark the primary load as done.  The primary load is the load
+        // of the main document.  Other resources may still be arriving.
+        [dataSource _setPrimaryLoadComplete: YES];
+        [frame _checkLoadComplete];
+    }
+    else {
+        // If the frame isn't complete it might be ready for a layout.  Perform that check here.
+        // Note that transitioning a frame to this state doesn't guarantee a layout, rather it
+        // just indicates that an early layout can be performed.
+        int timedLayoutSize = [[WebPreferences standardPreferences] _initialTimedLayoutSize];
+        if ((int)bytesSoFar > timedLayoutSize)
+            [frame _transitionToLayoutAcceptable];
+    }
+}
+
+
+- (void)_receivedError: (NSError *)error fromDataSource: (WebDataSource *)dataSource
+{
+    WebFrame *frame = [dataSource webFrame];
+
+    [frame _checkLoadComplete];
+}
+
+
+- (void)_mainReceivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource complete:(BOOL)isComplete
+{
+    ASSERT(dataSource);
+#ifndef NDEBUG
+    ASSERT([dataSource webFrame]);
+#endif
+    
+    [dataSource _setMainDocumentError: error];
+
+    if (isComplete) {
+        [dataSource _setPrimaryLoadComplete:YES];
+        [[dataSource webFrame] _checkLoadComplete];
+    }
+}
+
++ (NSString *)_MIMETypeForFile:(NSString *)path
+{
+    NSString *extension = [path pathExtension];
+    NSString *MIMEType = nil;
+
+    // Get the MIME type from the extension.
+    if ([extension length] != 0) {
+        MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
+    }
+
+    // If we can't get a known MIME type from the extension, sniff.
+    if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
+        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
+        NSData *data = [handle readDataOfLength:GUESS_MIME_TYPE_PEEK_LENGTH];
+        [handle closeFile];
+        if ([data length] != 0) {
+            MIMEType = [data _web_guessedMIMEType];
+        }
+        if ([MIMEType length] == 0){
+            MIMEType = @"application/octet-stream";
+        }
+    }
+
+    return MIMEType;
+}
+
+- (void)_downloadURL:(NSURL *)URL
+{
+    [self _downloadURL:URL toDirectory:nil];
+}
+
+- (void)_downloadURL:(NSURL *)URL toDirectory:(NSString *)directory
+{
+    ASSERT(URL);
+    
+    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
+    [WebDownload _downloadWithRequest:request
+                             delegate:_private->downloadDelegate
+                            directory:[directory isAbsolutePath] ? directory : nil];
+    [request release];
+}
+
+- (BOOL)defersCallbacks
+{
+    return _private->defersCallbacks;
+}
+
+- (void)setDefersCallbacks:(BOOL)defers
+{
+    if (defers == _private->defersCallbacks) {
+        return;
+    }
+
+    _private->defersCallbacks = defers;
+    [_private->mainFrame _defersCallbacksChanged];
+}
+
+- (void)_setTopLevelFrameName:(NSString *)name
+{
+    [[self mainFrame] _setName:name];
+}
+
+- (WebFrame *)_findFrameInThisWindowNamed: (NSString *)name
+{
+    return [[self mainFrame] _descendantFrameNamed:name];
+}
+
+- (WebFrame *)_findFrameNamed:(NSString *)name
+{
+    // Try this WebView first.
+    WebFrame *frame = [self _findFrameInThisWindowNamed:name];
+
+    if (frame != nil) {
+        return frame;
+    }
+
+    // Try other WebViews in the same set
+    if (_private->setName != nil) {
+        NSEnumerator *enumerator = [WebViewSets webViewsInSetNamed:_private->setName];
+        WebView *webView;
+        while ((webView = [enumerator nextObject]) != nil && frame == nil) {
+	    frame = [webView _findFrameInThisWindowNamed:name];
+        }
+    }
+
+    return frame;
+}
+
+- (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
+{
+    id wd = [self UIDelegate];
+    WebView *newWindowWebView = nil;
+    if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
+        newWindowWebView = [wd webView:self createWebViewWithRequest:request];
+    else {
+        newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
+    }
+
+    [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
+
+    return newWindowWebView;
+}
+
+- (NSMenu *)_menuForElement:(NSDictionary *)element
+{
+    NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
+          webView:self contextMenuItemsForElement:element defaultMenuItems:nil];
+    NSArray *menuItems = defaultMenuItems;
+    NSMenu *menu = nil;
+    unsigned i;
+
+    if (_private->UIDelegate) {
+        id cd = _private->UIDelegate;
+        
+        if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)])
+            menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
+    } 
+
+    if (menuItems && [menuItems count] > 0) {
+        menu = [[[NSMenu alloc] init] autorelease];
+
+        for (i=0; i<[menuItems count]; i++) {
+            [menu addItem:[menuItems objectAtIndex:i]];
+        }
+    }
+
+    return menu;
+}
+
+- (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(unsigned)modifierFlags
+{
+    // When the mouse isn't over this view at all, we'll get called with a dictionary of nil over
+    // and over again. So it's a good idea to catch that here and not send multiple calls to the delegate
+    // for that case.
+    
+    if (dictionary && _private->lastElementWasNonNil) {
+        [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
+    }
+    _private->lastElementWasNonNil = dictionary != nil;
+}
+
+- (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
+{
+    // We never go back/forward on a per-frame basis, so the target must be the main frame
+    ASSERT([item target] == nil || [self _findFrameNamed:[item target]] == [self mainFrame]);
+
+    // abort any current load if we're going back/forward
+    [[self mainFrame] stopLoading];
+    [[self mainFrame] _goToItem:item withLoadType:type];
+}
+
+// Not used now, but could be if we ever store frames in bookmarks or history
+- (void)_loadItem:(WebHistoryItem *)item
+{
+    WebHistoryItem *newItem = [item copy];	// Makes a deep copy, happily
+    [[self backForwardList] addItem:newItem];
+    [self _goToItem:newItem withLoadType:WebFrameLoadTypeIndexedBackForward];
+}
+
+- (void)_loadBackForwardListFromOtherView:(WebView *)otherView
+{
+    // It turns out the right combination of behavior is done with the back/forward load
+    // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
+    // in the back forward list, and go to the current one.
+
+    WebBackForwardList *bfList = [self backForwardList];
+    ASSERT(![bfList currentItem]);	// destination list should be empty
+
+    WebBackForwardList *otherBFList = [otherView backForwardList];
+    if (![otherBFList currentItem]) {
+        return;		// empty back forward list, bail
+    }
+
+    WebHistoryItem *newItemToGoTo = nil;
+    int lastItemIndex = [otherBFList forwardListCount];
+    int i;
+    for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
+        if (i == 0) {
+            // If this item is showing , save away its current scroll and form state,
+            // since that might have changed since loading and it is normally not saved
+            // until we leave that page.
+            [[otherView mainFrame] _saveDocumentAndScrollState];
+        }
+        WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
+        [bfList addItem:newItem];
+        if (i == 0) {
+            newItemToGoTo = newItem;
+        }
+    }
+    
+    [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
+}
+
+- (void)_setFormDelegate: (id<WebFormDelegate>)delegate
+{
+    _private->formDelegate = delegate;
+}
+
+- (id<WebFormDelegate>)_formDelegate
+{
+    if (!_private->formDelegate) {
+        // create lazily, to give the client a chance to set one before we bother to alloc the shared one
+        _private->formDelegate = [WebFormDelegate _sharedWebFormDelegate];
+    }
+    return _private->formDelegate;
+}
+
+- (WebCoreSettings *)_settings
+{
+    return _private->settings;
+}
+
+- (void)_updateWebCoreSettingsFromPreferences: (WebPreferences *)preferences
+{
+    [_private->settings setCursiveFontFamily:[preferences cursiveFontFamily]];
+    [_private->settings setDefaultFixedFontSize:[preferences defaultFixedFontSize]];
+    [_private->settings setDefaultFontSize:[preferences defaultFontSize]];
+    [_private->settings setDefaultTextEncoding:[preferences defaultTextEncodingName]];
+    [_private->settings setFantasyFontFamily:[preferences fantasyFontFamily]];
+    [_private->settings setFixedFontFamily:[preferences fixedFontFamily]];
+    [_private->settings setJavaEnabled:[preferences isJavaEnabled]];
+    [_private->settings setJavaScriptEnabled:[preferences isJavaScriptEnabled]];
+    [_private->settings setJavaScriptCanOpenWindowsAutomatically:[preferences javaScriptCanOpenWindowsAutomatically]];
+    [_private->settings setMinimumFontSize:[preferences minimumFontSize]];
+    [_private->settings setPluginsEnabled:[preferences arePlugInsEnabled]];
+    [_private->settings setSansSerifFontFamily:[preferences sansSerifFontFamily]];
+    [_private->settings setSerifFontFamily:[preferences serifFontFamily]];
+    [_private->settings setStandardFontFamily:[preferences standardFontFamily]];
+    [_private->settings setWillLoadImagesAutomatically:[preferences loadsImagesAutomatically]];
+
+    if ([preferences userStyleSheetEnabled]) {
+        [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
+    } else {
+        [_private->settings setUserStyleSheetLocation:@""];
+    }
+    [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
+}
+
+- (void)_releaseUserAgentStrings
+{
+    int i;
+    for (i = 0; i != NumUserAgentStringTypes; ++i) {
+        [_private->userAgent[i] release];
+        _private->userAgent[i] = nil;
+    }
+}
+
+
+- (void)_preferencesChangedNotification: (NSNotification *)notification
+{
+    WebPreferences *preferences = (WebPreferences *)[notification object];
+    
+    ASSERT(preferences == [self preferences]);
+    [self _releaseUserAgentStrings];
+    [self _updateWebCoreSettingsFromPreferences: preferences];
+}
+
+- _frameLoadDelegateForwarder
+{
+    if (!_private->frameLoadDelegateForwarder)
+        _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate]  defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
+    return _private->frameLoadDelegateForwarder;
+}
+
+- _resourceLoadDelegateForwarder
+{
+    if (!_private->resourceProgressDelegateForwarder)
+        _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
+    return _private->resourceProgressDelegateForwarder;
+}
+
+- (void)_cacheResourceLoadDelegateImplementations
+{
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsDidCancelAuthenticationChallenge = YES;
+
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveAuthenticationChallenge = YES;
+
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didFinishLoadingFromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsDidFinishLoadingFromDataSource = YES;
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveContentLength:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveContentLength = YES;
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveResponse:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveResponse = YES;
+    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsWillSendRequest = YES;
+    if ([[self resourceLoadDelegate] respondsToSelector: @selector(webView:identifierForInitialRequest:fromDataSource:)])
+        _private->resourceLoadDelegateImplementations.delegateImplementsIdentifierForRequest = YES;
+}
+
+- (WebResourceDelegateImplementationCache)_resourceLoadDelegateImplementations
+{
+    return _private->resourceLoadDelegateImplementations;
+}
+
+- _policyDelegateForwarder
+{
+    if (!_private->policyDelegateForwarder)
+        _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
+    return _private->policyDelegateForwarder;
+}
+
+- _UIDelegateForwarder
+{
+    if (!_private->UIDelegateForwarder)
+        _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
+    return _private->UIDelegateForwarder;
+}
+
+
+- (WebFrame *)_frameForDataSource: (WebDataSource *)dataSource fromFrame: (WebFrame *)frame
+{
+    NSArray *frames;
+    int i, count;
+    WebFrame *result, *aFrame;
+
+    if ([frame dataSource] == dataSource)
+        return frame;
+
+    if ([frame provisionalDataSource] == dataSource)
+        return frame;
+
+    frames = [frame childFrames];
+    count = [frames count];
+    for (i = 0; i < count; i++){
+        aFrame = [frames objectAtIndex: i];
+        result = [self _frameForDataSource: dataSource fromFrame: aFrame];
+        if (result)
+            return result;
+    }
+
+    return nil;
+}
+
+
+- (WebFrame *)_frameForDataSource: (WebDataSource *)dataSource
+{
+    WebFrame *frame = [self mainFrame];
+
+    return [self _frameForDataSource: dataSource fromFrame: frame];
+}
+
+
+- (WebFrame *)_frameForView: (WebFrameView *)aView fromFrame: (WebFrame *)frame
+{
+    NSArray *frames;
+    int i, count;
+    WebFrame *result, *aFrame;
+
+    if ([frame frameView] == aView)
+        return frame;
+
+    frames = [frame childFrames];
+    count = [frames count];
+    for (i = 0; i < count; i++){
+        aFrame = [frames objectAtIndex: i];
+        result = [self _frameForView: aView fromFrame: aFrame];
+        if (result)
+            return result;
+    }
+
+    return nil;
+}
+
+- (WebFrame *)_frameForView: (WebFrameView *)aView
+{
+    WebFrame *frame = [self mainFrame];
+
+    return [self _frameForView: aView fromFrame: frame];
+}
+
+- (void)_registerDraggedTypes
+{
+    [self registerForDraggedTypes:[NSPasteboard _web_dragTypesForURL]];
+}
+
+- (void)_closeWindow
+{
+    [[self _UIDelegateForwarder] webViewClose:self];
+}
+
++ (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
+{
+    NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
+    [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
+
+    // This is used to make _representationExistsForURLScheme faster.
+    // Without this set, we'd have to create the MIME type each time.
+    if (schemesWithRepresentationsSet == nil) {
+        schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
+    }
+    [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
+}
+
++ (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
+{
+    return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
+}
+
++ (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
+{
+    return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
+}
+
++ (BOOL)_canHandleRequest:(NSURLRequest *)request
+{
+    if ([NSURLConnection canHandleRequest:request]) {
+        return YES;
+    }
+
+    return [self _representationExistsForURLScheme:[[request URL] scheme]];
+}
+
++ (NSString *)_decodeData:(NSData *)data
+{
+    return [WebCoreEncodings decodeData:data];
+}
+
+- (void)_pushPerformingProgrammaticFocus
+{
+    _private->programmaticFocusCount++;
+}
+
+- (void)_popPerformingProgrammaticFocus
+{
+    _private->programmaticFocusCount--;
+}
+
+- (BOOL)_isPerformingProgrammaticFocus
+{
+    return _private->programmaticFocusCount != 0;
+}
+
+#define UnknownTotalBytes -1
+#define WebProgressItemDefaultEstimatedLength 1024*16
+
+- (void)_didChangeValueForKey: (NSString *)key
+{
+    LOG (Bindings, "calling didChangeValueForKey: %@", key);
+    [self didChangeValueForKey: key];
+}
+
+- (void)_willChangeValueForKey: (NSString *)key
+{
+    LOG (Bindings, "calling willChangeValueForKey: %@", key);
+    [self willChangeValueForKey: key];
+}
+
+
+- (void)_progressStarted
+{
+    [self _willChangeValueForKey: @"estimatedProgress"];
+    if (_private->numProgressTrackedFrames == 0){
+        _private->totalPageAndResourceBytesToLoad = 0;
+        _private->totalBytesReceived = 0;
+        _private->progressValue = 0;
+        _private->lastNotifiedProgressValue = 0;
+        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressStartedNotification object:self];
+    }
+    _private->numProgressTrackedFrames++;
+    [self _didChangeValueForKey: @"estimatedProgress"];
+}
+
+- (void)_progressCompleted
+{
+    [self _willChangeValueForKey: @"estimatedProgress"];
+    if (![[[self mainFrame] dataSource] isLoading])
+        _private->numProgressTrackedFrames = 0;
+        
+    if (_private->numProgressTrackedFrames == 0){
+        [_private->progressItems release];
+        _private->progressItems = nil;
+        _private->progressValue = 1;
+        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
+    }
+    [self _didChangeValueForKey: @"estimatedProgress"];
+}
+
+- (void)_incrementProgressForConnection:(NSURLConnection *)con response:(NSURLResponse *)response;
+{
+    if (!con)
+        return;
+
+    WebProgressItem *item = [[WebProgressItem alloc] init];
+
+    if (!item)
+        return;
+
+    long long length = [response expectedContentLength];
+    if (length < 0){
+        length = WebProgressItemDefaultEstimatedLength;
+    }
+    item->estimatedLength = length;
+    _private->totalPageAndResourceBytesToLoad += length;
+    
+    if (!_private->progressItems)
+        _private->progressItems = [[NSMutableDictionary alloc] init];
+        
+    [_private->progressItems _web_setObject:item forUncopiedKey:con];
+    [item release];
+}
+
+- (void)_incrementProgressForConnection:(NSURLConnection *)con data:(NSData *)data
+{
+    if (!con)
+        return;
+
+    WebProgressItem *item = [_private->progressItems objectForKey:con];
+
+    if (!item)
+        return;
+
+    [self _willChangeValueForKey: @"estimatedProgress"];
+
+    unsigned bytesReceived = [data length];
+    double increment = 0, percentOfRemainingBytes;
+    long long remainingBytes, estimatedBytesForPendingRequests;
+
+    item->bytesReceived += bytesReceived;
+    if (item->bytesReceived > item->estimatedLength){
+        _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
+        item->estimatedLength = item->bytesReceived*2;
+    }
+    
+    int numPendingOrLoadingRequests = [[self mainFrame] _numPendingOrLoadingRequests:YES];
+    estimatedBytesForPendingRequests = WebProgressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
+    remainingBytes = ((_private->totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - _private->totalBytesReceived);
+    percentOfRemainingBytes = (double)bytesReceived / (double)remainingBytes;
+    increment = (1.0 - _private->progressValue) * percentOfRemainingBytes;
+    
+    _private->totalBytesReceived += bytesReceived;
+    
+    _private->progressValue += increment;
+
+    if (_private->progressValue < 0.0)
+        _private->progressValue = 0.0;
+
+    if (_private->progressValue > 1.0)
+        _private->progressValue = 1.0;
+
+    double notificationProgressDelta = _private->progressValue - _private->lastNotifiedProgressValue;
+    if (notificationProgressDelta >= _private->progressNotificationInterval){
+        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
+        _private->lastNotifiedProgressValue = _private->progressValue;
+    }
+
+    [self _didChangeValueForKey: @"estimatedProgress"];
+}
+
+- (void)_completeProgressForConnection:(NSURLConnection *)con
+{
+    WebProgressItem *item = [_private->progressItems objectForKey:con];
+
+    if (!item)
+        return;
+        
+    // Adjust the total expected bytes to account for any overage/underage.
+    long long delta = item->bytesReceived - item->estimatedLength;
+    _private->totalPageAndResourceBytesToLoad += delta;
+    item->estimatedLength = item->bytesReceived;
+}
+
+// Required to prevent automatic observer notifications.
++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
+    return NO;
+}
+
+- (NSArray *)_declaredKeys {
+    static NSArray *declaredKeys = nil;
+    
+    if (!declaredKeys) {
+        declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, nil];
+    }
+
+    return declaredKeys;
+}
+
+- (void)setObservationInfo:(void *)info
+{
+    _private->observationInfo = info;
+}
+
+- (void *)observationInfo
+{
+    return _private->observationInfo;
+}
+
+- (void)_willChangeBackForwardKeys
+{
+    [self _willChangeValueForKey: _WebCanGoBackKey];
+    [self _willChangeValueForKey: _WebCanGoForwardKey];
+}
+
+- (void)_didChangeBackForwardKeys
+{
+    [self _didChangeValueForKey: _WebCanGoBackKey];
+    [self _didChangeValueForKey: _WebCanGoForwardKey];
+}
+
+- (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
+{
+    [self _willChangeBackForwardKeys];
+    if (frame == [self mainFrame]){
+        // Force an observer update by sending a will/did.
+        [self _willChangeValueForKey: _WebIsLoadingKey];
+        [self _didChangeValueForKey: _WebIsLoadingKey];
+
+        [self _willChangeValueForKey: _WebMainFrameURLKey];
+    }
+    [NSApp setWindowsNeedUpdate:YES];
+}
+
+- (void)_didCommitLoadForFrame:(WebFrame *)frame
+{
+    if (frame == [self mainFrame]){
+        [self _didChangeValueForKey: _WebMainFrameURLKey];
+    }
+    [NSApp setWindowsNeedUpdate:YES];
+}
+
+- (void)_didFinishLoadForFrame:(WebFrame *)frame
+{
+    [self _didChangeBackForwardKeys];
+    if (frame == [self mainFrame]){
+        // Force an observer update by sending a will/did.
+        [self _willChangeValueForKey: _WebIsLoadingKey];
+        [self _didChangeValueForKey: _WebIsLoadingKey];
+    }
+    [NSApp setWindowsNeedUpdate:YES];
+}
+
+- (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
+{
+    [self _didChangeBackForwardKeys];
+    if (frame == [self mainFrame]){
+        // Force an observer update by sending a will/did.
+        [self _willChangeValueForKey: _WebIsLoadingKey];
+        [self _didChangeValueForKey: _WebIsLoadingKey];
+    }
+    [NSApp setWindowsNeedUpdate:YES];
+}
+
+- (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
+{
+    [self _didChangeBackForwardKeys];
+    if (frame == [self mainFrame]){
+        // Force an observer update by sending a will/did.
+        [self _willChangeValueForKey: _WebIsLoadingKey];
+        [self _didChangeValueForKey: _WebIsLoadingKey];
+        
+        [self _didChangeValueForKey: _WebMainFrameURLKey];
+    }
+    [NSApp setWindowsNeedUpdate:YES];
+}
+
+ at end
+
+
+ at implementation _WebSafeForwarder
+
+- initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
+{
+    [super init];
+    target = t;		// Non retained.
+    defaultTarget = dt;
+    templateClass = aClass;
+    return self;
+}
+
+
+// Used to send messages to delegates that implement informal protocols.
++ safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
+{
+    return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
+}
+
+#ifndef NDEBUG
+NSMutableDictionary *countInvocations;
+#endif
+
+- (void)forwardInvocation:(NSInvocation *)anInvocation
+{
+#ifndef NDEBUG
+    if (!countInvocations){
+        countInvocations = [[NSMutableDictionary alloc] init];
+    }
+    NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
+    if (!count)
+        count = [NSNumber numberWithInt: 1];
+    else
+        count = [NSNumber numberWithInt: [count intValue] + 1];
+    [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
+#endif
+    if ([target respondsToSelector: [anInvocation selector]])
+        [anInvocation invokeWithTarget: target];
+    else if ([defaultTarget respondsToSelector: [anInvocation selector]])
+        [anInvocation invokeWithTarget: defaultTarget];
+    // Do nothing quietly if method not implemented.
+}
+
+- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
+{
+    return [templateClass instanceMethodSignatureForSelector: aSelector];
+}
+
+ at end
+
 @interface WebView (WebInternal)
 - (BOOL)_isLoading;
 @end
diff --git a/WebKit/WebView.subproj/WebViewPrivate.m b/WebKit/WebView.subproj/WebViewPrivate.m
deleted file mode 100644
index df9b2e7..0000000
--- a/WebKit/WebView.subproj/WebViewPrivate.m
+++ /dev/null
@@ -1,925 +0,0 @@
-/*	
-    WebViewPrivate.m
-    Copyright (c) 2001, 2002, Apple, Inc. All rights reserved.
-*/
-
-#import <WebKit/WebViewPrivate.h>
-
-#import <WebKit/WebBackForwardList.h>
-#import <WebKit/WebBridge.h>
-#import <WebKit/WebControllerSets.h>
-#import <WebKit/WebDataSourcePrivate.h>
-#import <WebKit/WebDefaultFrameLoadDelegate.h>
-#import <WebKit/WebDefaultPolicyDelegate.h>
-#import <WebKit/WebDefaultResourceLoadDelegate.h>
-#import <WebKit/WebDefaultUIDelegate.h>
-#import <WebKit/WebDownload.h>
-#import <WebKit/WebFormDelegatePrivate.h>
-#import <WebKit/WebFrameLoadDelegate.h>
-#import <WebKit/WebFramePrivate.h>
-#import <WebKit/WebFrameViewPrivate.h>
-#import <WebKit/WebHistoryItemPrivate.h>
-#import <WebKit/WebKitLogging.h>
-#import <WebKit/WebNSPasteboardExtras.h>
-#import <WebKit/WebNSURLExtras.h>
-#import <WebKit/WebPreferencesPrivate.h>
-#import <WebKit/WebResourceLoadDelegate.h>
-#import <WebKit/WebUIDelegate.h>
-
-#import <WebKit/WebAssertions.h>
-
-#import <Foundation/NSURLFileTypeMappings.h>
-#import <Foundation/NSData_NSURLExtras.h>
-#import <Foundation/NSDictionary_NSURLExtras.h>
-#import <Foundation/NSString_NSURLExtras.h>
-#import <Foundation/NSURLConnection.h>
-#import <Foundation/NSURLDownloadPrivate.h>
-#import <Foundation/NSURLRequest.h>
-
-#import <WebCore/WebCoreEncodings.h>
-#import <WebCore/WebCoreSettings.h>
-
-static NSMutableSet *schemesWithRepresentationsSet;
-
-NSString *_WebCanGoBackKey = @"canGoBack";
-NSString *_WebCanGoForwardKey = @"canGoForward";
-NSString *_WebEstimatedProgressKey = @"estimatedProgress";
-NSString *_WebIsLoadingKey = @"isLoading";
-NSString *_WebMainFrameIconKey = @"mainFrameIcon";
-NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
-NSString *_WebMainFrameURLKey = @"mainFrameURL";
-
- at interface WebProgressItem : NSObject
-{
- at public
-    long long bytesReceived;
-    long long estimatedLength;
-}
- at end
-
- at implementation WebProgressItem
- at end
-
- at implementation WebViewPrivate
-
-- init 
-{
-    backForwardList = [[WebBackForwardList alloc] init];
-    textSizeMultiplier = 1;
-    progressNotificationInterval = 0.02;
-    settings = [[WebCoreSettings alloc] init];
-
-    return self;
-}
-
-- (void)dealloc
-{
-    ASSERT(!mainFrame);
-    
-    [backForwardList release];
-    [applicationNameForUserAgent release];
-    [userAgentOverride release];
-    int i;
-    for (i = 0; i != NumUserAgentStringTypes; ++i) {
-        [userAgent[i] release];
-    }
-    
-    [preferences release];
-    [settings release];
-    [hostWindow release];
-    
-    [policyDelegateForwarder release];
-    [resourceProgressDelegateForwarder release];
-    [UIDelegateForwarder release];
-    [frameLoadDelegateForwarder release];
-    
-    [progressItems release];
-    
-    [super dealloc];
-}
-
- at end
-
-
- at implementation WebView (WebPrivate)
-
-+ (BOOL)canShowFile:(NSString *)path
-{
-    NSString *MIMEType;
-
-    MIMEType = [WebView _MIMETypeForFile:path];
-    return [[self class] canShowMIMEType:MIMEType];
-}
-
-+ (NSString *)suggestedFileExtensionForMIMEType: (NSString *)type
-{
-    return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
-}
-
-- (void)_close
-{
-    if (_private->setName != nil) {
-        [WebViewSets removeWebView:self fromSetNamed:_private->setName];
-        [_private->setName release];
-        _private->setName = nil;
-    }
-
-    [_private->mainFrame _detachFromParent];
-    [_private->mainFrame release];
-    _private->mainFrame = nil;
-    
-    // Clear the page cache so we call destroy on all the plug-ins in the page cache to break any retain cycles.
-    // See comment in [WebHistoryItem _releaseAllPendingPageCaches] for more information.
-    [_private->backForwardList _clearPageCache];
-}
-
-- (WebFrame *)_createFrameNamed:(NSString *)fname inParent:(WebFrame *)parent allowsScrolling:(BOOL)allowsScrolling
-{
-    WebFrameView *childView = [[WebFrameView alloc] initWithFrame:NSMakeRect(0,0,0,0)];
-
-    [childView _setWebView:self];
-    [childView setAllowsScrolling:allowsScrolling];
-    
-    WebFrame *newFrame = [[WebFrame alloc] initWithName:fname webFrameView:childView webView:self];
-
-    [childView release];
-
-    [parent _addChild:newFrame];
-    
-    [newFrame release];
-        
-    return newFrame;
-}
-
-- (void)_finishedLoadingResourceFromDataSource: (WebDataSource *)dataSource
-{
-    WebFrame *frame = [dataSource webFrame];
-    
-    ASSERT(dataSource != nil);
-    
-    // This resource has completed, so check if the load is complete for all frames.
-    if (frame != nil) {
-        [frame _transitionToLayoutAcceptable];
-        [frame _checkLoadComplete];
-    }
-}
-
-- (void)_mainReceivedBytesSoFar: (unsigned)bytesSoFar fromDataSource: (WebDataSource *)dataSource complete: (BOOL)isComplete
-{
-    WebFrame *frame = [dataSource webFrame];
-    
-    ASSERT(dataSource != nil);
-
-    // The frame may be nil if a previously cancelled load is still making progress callbacks.
-    if (frame == nil)
-        return;
-        
-    // This resource has completed, so check if the load is complete for all frames.
-    if (isComplete){
-        // If the load is complete, mark the primary load as done.  The primary load is the load
-        // of the main document.  Other resources may still be arriving.
-        [dataSource _setPrimaryLoadComplete: YES];
-        [frame _checkLoadComplete];
-    }
-    else {
-        // If the frame isn't complete it might be ready for a layout.  Perform that check here.
-        // Note that transitioning a frame to this state doesn't guarantee a layout, rather it
-        // just indicates that an early layout can be performed.
-        int timedLayoutSize = [[WebPreferences standardPreferences] _initialTimedLayoutSize];
-        if ((int)bytesSoFar > timedLayoutSize)
-            [frame _transitionToLayoutAcceptable];
-    }
-}
-
-
-- (void)_receivedError: (NSError *)error fromDataSource: (WebDataSource *)dataSource
-{
-    WebFrame *frame = [dataSource webFrame];
-
-    [frame _checkLoadComplete];
-}
-
-
-- (void)_mainReceivedError:(NSError *)error fromDataSource:(WebDataSource *)dataSource complete:(BOOL)isComplete
-{
-    ASSERT(dataSource);
-#ifndef NDEBUG
-    ASSERT([dataSource webFrame]);
-#endif
-    
-    [dataSource _setMainDocumentError: error];
-
-    if (isComplete) {
-        [dataSource _setPrimaryLoadComplete:YES];
-        [[dataSource webFrame] _checkLoadComplete];
-    }
-}
-
-+ (NSString *)_MIMETypeForFile:(NSString *)path
-{
-    NSString *extension = [path pathExtension];
-    NSString *MIMEType = nil;
-
-    // Get the MIME type from the extension.
-    if ([extension length] != 0) {
-        MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
-    }
-
-    // If we can't get a known MIME type from the extension, sniff.
-    if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
-        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
-        NSData *data = [handle readDataOfLength:GUESS_MIME_TYPE_PEEK_LENGTH];
-        [handle closeFile];
-        if ([data length] != 0) {
-            MIMEType = [data _web_guessedMIMEType];
-        }
-        if ([MIMEType length] == 0){
-            MIMEType = @"application/octet-stream";
-        }
-    }
-
-    return MIMEType;
-}
-
-- (void)_downloadURL:(NSURL *)URL
-{
-    [self _downloadURL:URL toDirectory:nil];
-}
-
-- (void)_downloadURL:(NSURL *)URL toDirectory:(NSString *)directory
-{
-    ASSERT(URL);
-    
-    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
-    [WebDownload _downloadWithRequest:request
-                             delegate:_private->downloadDelegate
-                            directory:[directory isAbsolutePath] ? directory : nil];
-    [request release];
-}
-
-- (BOOL)defersCallbacks
-{
-    return _private->defersCallbacks;
-}
-
-- (void)setDefersCallbacks:(BOOL)defers
-{
-    if (defers == _private->defersCallbacks) {
-        return;
-    }
-
-    _private->defersCallbacks = defers;
-    [_private->mainFrame _defersCallbacksChanged];
-}
-
-- (void)_setTopLevelFrameName:(NSString *)name
-{
-    [[self mainFrame] _setName:name];
-}
-
-- (WebFrame *)_findFrameInThisWindowNamed: (NSString *)name
-{
-    return [[self mainFrame] _descendantFrameNamed:name];
-}
-
-- (WebFrame *)_findFrameNamed:(NSString *)name
-{
-    // Try this WebView first.
-    WebFrame *frame = [self _findFrameInThisWindowNamed:name];
-
-    if (frame != nil) {
-        return frame;
-    }
-
-    // Try other WebViews in the same set
-    if (_private->setName != nil) {
-        NSEnumerator *enumerator = [WebViewSets webViewsInSetNamed:_private->setName];
-        WebView *webView;
-        while ((webView = [enumerator nextObject]) != nil && frame == nil) {
-	    frame = [webView _findFrameInThisWindowNamed:name];
-        }
-    }
-
-    return frame;
-}
-
-- (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
-{
-    id wd = [self UIDelegate];
-    WebView *newWindowWebView = nil;
-    if ([wd respondsToSelector:@selector(webView:createWebViewWithRequest:)])
-        newWindowWebView = [wd webView:self createWebViewWithRequest:request];
-    else {
-        newWindowWebView = [[WebDefaultUIDelegate sharedUIDelegate] webView:self createWebViewWithRequest: request];
-    }
-
-    [[newWindowWebView _UIDelegateForwarder] webViewShow: newWindowWebView];
-
-    return newWindowWebView;
-}
-
-- (NSMenu *)_menuForElement:(NSDictionary *)element
-{
-    NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate]
-          webView:self contextMenuItemsForElement:element defaultMenuItems:nil];
-    NSArray *menuItems = defaultMenuItems;
-    NSMenu *menu = nil;
-    unsigned i;
-
-    if (_private->UIDelegate) {
-        id cd = _private->UIDelegate;
-        
-        if ([cd respondsToSelector:@selector(webView:contextMenuItemsForElement:defaultMenuItems:)])
-            menuItems = [cd webView:self contextMenuItemsForElement:element defaultMenuItems:defaultMenuItems];
-    } 
-
-    if (menuItems && [menuItems count] > 0) {
-        menu = [[[NSMenu alloc] init] autorelease];
-
-        for (i=0; i<[menuItems count]; i++) {
-            [menu addItem:[menuItems objectAtIndex:i]];
-        }
-    }
-
-    return menu;
-}
-
-- (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(unsigned)modifierFlags
-{
-    // When the mouse isn't over this view at all, we'll get called with a dictionary of nil over
-    // and over again. So it's a good idea to catch that here and not send multiple calls to the delegate
-    // for that case.
-    
-    if (dictionary && _private->lastElementWasNonNil) {
-        [[self _UIDelegateForwarder] webView:self mouseDidMoveOverElement:dictionary modifierFlags:modifierFlags];
-    }
-    _private->lastElementWasNonNil = dictionary != nil;
-}
-
-- (void)_goToItem:(WebHistoryItem *)item withLoadType:(WebFrameLoadType)type
-{
-    // We never go back/forward on a per-frame basis, so the target must be the main frame
-    ASSERT([item target] == nil || [self _findFrameNamed:[item target]] == [self mainFrame]);
-
-    // abort any current load if we're going back/forward
-    [[self mainFrame] stopLoading];
-    [[self mainFrame] _goToItem:item withLoadType:type];
-}
-
-// Not used now, but could be if we ever store frames in bookmarks or history
-- (void)_loadItem:(WebHistoryItem *)item
-{
-    WebHistoryItem *newItem = [item copy];	// Makes a deep copy, happily
-    [[self backForwardList] addItem:newItem];
-    [self _goToItem:newItem withLoadType:WebFrameLoadTypeIndexedBackForward];
-}
-
-- (void)_loadBackForwardListFromOtherView:(WebView *)otherView
-{
-    // It turns out the right combination of behavior is done with the back/forward load
-    // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
-    // in the back forward list, and go to the current one.
-
-    WebBackForwardList *bfList = [self backForwardList];
-    ASSERT(![bfList currentItem]);	// destination list should be empty
-
-    WebBackForwardList *otherBFList = [otherView backForwardList];
-    if (![otherBFList currentItem]) {
-        return;		// empty back forward list, bail
-    }
-
-    WebHistoryItem *newItemToGoTo = nil;
-    int lastItemIndex = [otherBFList forwardListCount];
-    int i;
-    for (i = -[otherBFList backListCount]; i <= lastItemIndex; i++) {
-        if (i == 0) {
-            // If this item is showing , save away its current scroll and form state,
-            // since that might have changed since loading and it is normally not saved
-            // until we leave that page.
-            [[otherView mainFrame] _saveDocumentAndScrollState];
-        }
-        WebHistoryItem *newItem = [[otherBFList itemAtIndex:i] copy];
-        [bfList addItem:newItem];
-        if (i == 0) {
-            newItemToGoTo = newItem;
-        }
-    }
-    
-    [self _goToItem:newItemToGoTo withLoadType:WebFrameLoadTypeIndexedBackForward];
-}
-
-- (void)_setFormDelegate: (id<WebFormDelegate>)delegate
-{
-    _private->formDelegate = delegate;
-}
-
-- (id<WebFormDelegate>)_formDelegate
-{
-    if (!_private->formDelegate) {
-        // create lazily, to give the client a chance to set one before we bother to alloc the shared one
-        _private->formDelegate = [WebFormDelegate _sharedWebFormDelegate];
-    }
-    return _private->formDelegate;
-}
-
-- (WebCoreSettings *)_settings
-{
-    return _private->settings;
-}
-
-- (void)_updateWebCoreSettingsFromPreferences: (WebPreferences *)preferences
-{
-    [_private->settings setCursiveFontFamily:[preferences cursiveFontFamily]];
-    [_private->settings setDefaultFixedFontSize:[preferences defaultFixedFontSize]];
-    [_private->settings setDefaultFontSize:[preferences defaultFontSize]];
-    [_private->settings setDefaultTextEncoding:[preferences defaultTextEncodingName]];
-    [_private->settings setFantasyFontFamily:[preferences fantasyFontFamily]];
-    [_private->settings setFixedFontFamily:[preferences fixedFontFamily]];
-    [_private->settings setJavaEnabled:[preferences isJavaEnabled]];
-    [_private->settings setJavaScriptEnabled:[preferences isJavaScriptEnabled]];
-    [_private->settings setJavaScriptCanOpenWindowsAutomatically:[preferences javaScriptCanOpenWindowsAutomatically]];
-    [_private->settings setMinimumFontSize:[preferences minimumFontSize]];
-    [_private->settings setPluginsEnabled:[preferences arePlugInsEnabled]];
-    [_private->settings setSansSerifFontFamily:[preferences sansSerifFontFamily]];
-    [_private->settings setSerifFontFamily:[preferences serifFontFamily]];
-    [_private->settings setStandardFontFamily:[preferences standardFontFamily]];
-    [_private->settings setWillLoadImagesAutomatically:[preferences loadsImagesAutomatically]];
-
-    if ([preferences userStyleSheetEnabled]) {
-        [_private->settings setUserStyleSheetLocation:[[preferences userStyleSheetLocation] _web_originalDataAsString]];
-    } else {
-        [_private->settings setUserStyleSheetLocation:@""];
-    }
-    [_private->settings setShouldPrintBackgrounds:[preferences shouldPrintBackgrounds]];
-}
-
-- (void)_releaseUserAgentStrings
-{
-    int i;
-    for (i = 0; i != NumUserAgentStringTypes; ++i) {
-        [_private->userAgent[i] release];
-        _private->userAgent[i] = nil;
-    }
-}
-
-
-- (void)_preferencesChangedNotification: (NSNotification *)notification
-{
-    WebPreferences *preferences = (WebPreferences *)[notification object];
-    
-    ASSERT(preferences == [self preferences]);
-    [self _releaseUserAgentStrings];
-    [self _updateWebCoreSettingsFromPreferences: preferences];
-}
-
-- _frameLoadDelegateForwarder
-{
-    if (!_private->frameLoadDelegateForwarder)
-        _private->frameLoadDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self frameLoadDelegate]  defaultTarget: [WebDefaultFrameLoadDelegate sharedFrameLoadDelegate] templateClass: [WebDefaultFrameLoadDelegate class]];
-    return _private->frameLoadDelegateForwarder;
-}
-
-- _resourceLoadDelegateForwarder
-{
-    if (!_private->resourceProgressDelegateForwarder)
-        _private->resourceProgressDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self resourceLoadDelegate] defaultTarget: [WebDefaultResourceLoadDelegate sharedResourceLoadDelegate] templateClass: [WebDefaultResourceLoadDelegate class]];
-    return _private->resourceProgressDelegateForwarder;
-}
-
-- (void)_cacheResourceLoadDelegateImplementations
-{
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsDidCancelAuthenticationChallenge = YES;
-
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveAuthenticationChallenge = YES;
-
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didFinishLoadingFromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsDidFinishLoadingFromDataSource = YES;
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveContentLength:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveContentLength = YES;
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:didReceiveResponse:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsDidReceiveResponse = YES;
-    if ([[self resourceLoadDelegate] respondsToSelector:@selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsWillSendRequest = YES;
-    if ([[self resourceLoadDelegate] respondsToSelector: @selector(webView:identifierForInitialRequest:fromDataSource:)])
-        _private->resourceLoadDelegateImplementations.delegateImplementsIdentifierForRequest = YES;
-}
-
-- (WebResourceDelegateImplementationCache)_resourceLoadDelegateImplementations
-{
-    return _private->resourceLoadDelegateImplementations;
-}
-
-- _policyDelegateForwarder
-{
-    if (!_private->policyDelegateForwarder)
-        _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self policyDelegate] defaultTarget: [WebDefaultPolicyDelegate sharedPolicyDelegate] templateClass: [WebDefaultPolicyDelegate class]];
-    return _private->policyDelegateForwarder;
-}
-
-- _UIDelegateForwarder
-{
-    if (!_private->UIDelegateForwarder)
-        _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget: [self UIDelegate] defaultTarget: [WebDefaultUIDelegate sharedUIDelegate] templateClass: [WebDefaultUIDelegate class]];
-    return _private->UIDelegateForwarder;
-}
-
-
-- (WebFrame *)_frameForDataSource: (WebDataSource *)dataSource fromFrame: (WebFrame *)frame
-{
-    NSArray *frames;
-    int i, count;
-    WebFrame *result, *aFrame;
-
-    if ([frame dataSource] == dataSource)
-        return frame;
-
-    if ([frame provisionalDataSource] == dataSource)
-        return frame;
-
-    frames = [frame childFrames];
-    count = [frames count];
-    for (i = 0; i < count; i++){
-        aFrame = [frames objectAtIndex: i];
-        result = [self _frameForDataSource: dataSource fromFrame: aFrame];
-        if (result)
-            return result;
-    }
-
-    return nil;
-}
-
-
-- (WebFrame *)_frameForDataSource: (WebDataSource *)dataSource
-{
-    WebFrame *frame = [self mainFrame];
-
-    return [self _frameForDataSource: dataSource fromFrame: frame];
-}
-
-
-- (WebFrame *)_frameForView: (WebFrameView *)aView fromFrame: (WebFrame *)frame
-{
-    NSArray *frames;
-    int i, count;
-    WebFrame *result, *aFrame;
-
-    if ([frame frameView] == aView)
-        return frame;
-
-    frames = [frame childFrames];
-    count = [frames count];
-    for (i = 0; i < count; i++){
-        aFrame = [frames objectAtIndex: i];
-        result = [self _frameForView: aView fromFrame: aFrame];
-        if (result)
-            return result;
-    }
-
-    return nil;
-}
-
-- (WebFrame *)_frameForView: (WebFrameView *)aView
-{
-    WebFrame *frame = [self mainFrame];
-
-    return [self _frameForView: aView fromFrame: frame];
-}
-
-- (void)_registerDraggedTypes
-{
-    [self registerForDraggedTypes:[NSPasteboard _web_dragTypesForURL]];
-}
-
-- (void)_closeWindow
-{
-    [[self _UIDelegateForwarder] webViewClose:self];
-}
-
-+ (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme;
-{
-    NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
-    [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
-
-    // This is used to make _representationExistsForURLScheme faster.
-    // Without this set, we'd have to create the MIME type each time.
-    if (schemesWithRepresentationsSet == nil) {
-        schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
-    }
-    [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
-}
-
-+ (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
-{
-    return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
-}
-
-+ (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
-{
-    return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
-}
-
-+ (BOOL)_canHandleRequest:(NSURLRequest *)request
-{
-    if ([NSURLConnection canHandleRequest:request]) {
-        return YES;
-    }
-
-    return [self _representationExistsForURLScheme:[[request URL] scheme]];
-}
-
-+ (NSString *)_decodeData:(NSData *)data
-{
-    return [WebCoreEncodings decodeData:data];
-}
-
-- (void)_pushPerformingProgrammaticFocus
-{
-    _private->programmaticFocusCount++;
-}
-
-- (void)_popPerformingProgrammaticFocus
-{
-    _private->programmaticFocusCount--;
-}
-
-- (BOOL)_isPerformingProgrammaticFocus
-{
-    return _private->programmaticFocusCount != 0;
-}
-
-#define UnknownTotalBytes -1
-#define WebProgressItemDefaultEstimatedLength 1024*16
-
-- (void)_didChangeValueForKey: (NSString *)key
-{
-    LOG (Bindings, "calling didChangeValueForKey: %@", key);
-    [self didChangeValueForKey: key];
-}
-
-- (void)_willChangeValueForKey: (NSString *)key
-{
-    LOG (Bindings, "calling willChangeValueForKey: %@", key);
-    [self willChangeValueForKey: key];
-}
-
-
-- (void)_progressStarted
-{
-    [self _willChangeValueForKey: @"estimatedProgress"];
-    if (_private->numProgressTrackedFrames == 0){
-        _private->totalPageAndResourceBytesToLoad = 0;
-        _private->totalBytesReceived = 0;
-        _private->progressValue = 0;
-        _private->lastNotifiedProgressValue = 0;
-        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressStartedNotification object:self];
-    }
-    _private->numProgressTrackedFrames++;
-    [self _didChangeValueForKey: @"estimatedProgress"];
-}
-
-- (void)_progressCompleted
-{
-    [self _willChangeValueForKey: @"estimatedProgress"];
-    if (![[[self mainFrame] dataSource] isLoading])
-        _private->numProgressTrackedFrames = 0;
-        
-    if (_private->numProgressTrackedFrames == 0){
-        [_private->progressItems release];
-        _private->progressItems = nil;
-        _private->progressValue = 1;
-        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressFinishedNotification object:self];
-    }
-    [self _didChangeValueForKey: @"estimatedProgress"];
-}
-
-- (void)_incrementProgressForConnection:(NSURLConnection *)con response:(NSURLResponse *)response;
-{
-    if (!con)
-        return;
-
-    WebProgressItem *item = [[WebProgressItem alloc] init];
-
-    if (!item)
-        return;
-
-    long long length = [response expectedContentLength];
-    if (length < 0){
-        length = WebProgressItemDefaultEstimatedLength;
-    }
-    item->estimatedLength = length;
-    _private->totalPageAndResourceBytesToLoad += length;
-    
-    if (!_private->progressItems)
-        _private->progressItems = [[NSMutableDictionary alloc] init];
-        
-    [_private->progressItems _web_setObject:item forUncopiedKey:con];
-    [item release];
-}
-
-- (void)_incrementProgressForConnection:(NSURLConnection *)con data:(NSData *)data
-{
-    if (!con)
-        return;
-
-    WebProgressItem *item = [_private->progressItems objectForKey:con];
-
-    if (!item)
-        return;
-
-    [self _willChangeValueForKey: @"estimatedProgress"];
-
-    unsigned bytesReceived = [data length];
-    double increment = 0, percentOfRemainingBytes;
-    long long remainingBytes, estimatedBytesForPendingRequests;
-
-    item->bytesReceived += bytesReceived;
-    if (item->bytesReceived > item->estimatedLength){
-        _private->totalPageAndResourceBytesToLoad += ((item->bytesReceived*2) - item->estimatedLength);
-        item->estimatedLength = item->bytesReceived*2;
-    }
-    
-    int numPendingOrLoadingRequests = [[self mainFrame] _numPendingOrLoadingRequests:YES];
-    estimatedBytesForPendingRequests = WebProgressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
-    remainingBytes = ((_private->totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - _private->totalBytesReceived);
-    percentOfRemainingBytes = (double)bytesReceived / (double)remainingBytes;
-    increment = (1.0 - _private->progressValue) * percentOfRemainingBytes;
-    
-    _private->totalBytesReceived += bytesReceived;
-    
-    _private->progressValue += increment;
-
-    if (_private->progressValue < 0.0)
-        _private->progressValue = 0.0;
-
-    if (_private->progressValue > 1.0)
-        _private->progressValue = 1.0;
-
-    double notificationProgressDelta = _private->progressValue - _private->lastNotifiedProgressValue;
-    if (notificationProgressDelta >= _private->progressNotificationInterval){
-        [[NSNotificationCenter defaultCenter] postNotificationName:WebViewProgressEstimateChangedNotification object:self];
-        _private->lastNotifiedProgressValue = _private->progressValue;
-    }
-
-    [self _didChangeValueForKey: @"estimatedProgress"];
-}
-
-- (void)_completeProgressForConnection:(NSURLConnection *)con
-{
-    WebProgressItem *item = [_private->progressItems objectForKey:con];
-
-    if (!item)
-        return;
-        
-    // Adjust the total expected bytes to account for any overage/underage.
-    long long delta = item->bytesReceived - item->estimatedLength;
-    _private->totalPageAndResourceBytesToLoad += delta;
-    item->estimatedLength = item->bytesReceived;
-}
-
-// Required to prevent automatic observer notifications.
-+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
-    return NO;
-}
-
-- (NSArray *)_declaredKeys {
-    static NSArray *declaredKeys = nil;
-    
-    if (!declaredKeys) {
-        declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey, _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, nil];
-    }
-
-    return declaredKeys;
-}
-
-- (void)setObservationInfo:(void *)info
-{
-    _private->observationInfo = info;
-}
-
-- (void *)observationInfo
-{
-    return _private->observationInfo;
-}
-
-- (void)_willChangeBackForwardKeys
-{
-    [self _willChangeValueForKey: _WebCanGoBackKey];
-    [self _willChangeValueForKey: _WebCanGoForwardKey];
-}
-
-- (void)_didChangeBackForwardKeys
-{
-    [self _didChangeValueForKey: _WebCanGoBackKey];
-    [self _didChangeValueForKey: _WebCanGoForwardKey];
-}
-
-- (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
-{
-    [self _willChangeBackForwardKeys];
-    if (frame == [self mainFrame]){
-        // Force an observer update by sending a will/did.
-        [self _willChangeValueForKey: _WebIsLoadingKey];
-        [self _didChangeValueForKey: _WebIsLoadingKey];
-
-        [self _willChangeValueForKey: _WebMainFrameURLKey];
-    }
-    [NSApp setWindowsNeedUpdate:YES];
-}
-
-- (void)_didCommitLoadForFrame:(WebFrame *)frame
-{
-    if (frame == [self mainFrame]){
-        [self _didChangeValueForKey: _WebMainFrameURLKey];
-    }
-    [NSApp setWindowsNeedUpdate:YES];
-}
-
-- (void)_didFinishLoadForFrame:(WebFrame *)frame
-{
-    [self _didChangeBackForwardKeys];
-    if (frame == [self mainFrame]){
-        // Force an observer update by sending a will/did.
-        [self _willChangeValueForKey: _WebIsLoadingKey];
-        [self _didChangeValueForKey: _WebIsLoadingKey];
-    }
-    [NSApp setWindowsNeedUpdate:YES];
-}
-
-- (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
-{
-    [self _didChangeBackForwardKeys];
-    if (frame == [self mainFrame]){
-        // Force an observer update by sending a will/did.
-        [self _willChangeValueForKey: _WebIsLoadingKey];
-        [self _didChangeValueForKey: _WebIsLoadingKey];
-    }
-    [NSApp setWindowsNeedUpdate:YES];
-}
-
-- (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
-{
-    [self _didChangeBackForwardKeys];
-    if (frame == [self mainFrame]){
-        // Force an observer update by sending a will/did.
-        [self _willChangeValueForKey: _WebIsLoadingKey];
-        [self _didChangeValueForKey: _WebIsLoadingKey];
-        
-        [self _didChangeValueForKey: _WebMainFrameURLKey];
-    }
-    [NSApp setWindowsNeedUpdate:YES];
-}
-
- at end
-
-
- at implementation _WebSafeForwarder
-
-- initWithTarget: t defaultTarget: dt templateClass: (Class)aClass
-{
-    [super init];
-    target = t;		// Non retained.
-    defaultTarget = dt;
-    templateClass = aClass;
-    return self;
-}
-
-
-// Used to send messages to delegates that implement informal protocols.
-+ safeForwarderWithTarget: t defaultTarget: dt templateClass: (Class)aClass;
-{
-    return [[[_WebSafeForwarder alloc] initWithTarget: t defaultTarget: dt templateClass: aClass] autorelease];
-}
-
-#ifndef NDEBUG
-NSMutableDictionary *countInvocations;
-#endif
-
-- (void)forwardInvocation:(NSInvocation *)anInvocation
-{
-#ifndef NDEBUG
-    if (!countInvocations){
-        countInvocations = [[NSMutableDictionary alloc] init];
-    }
-    NSNumber *count = [countInvocations objectForKey: NSStringFromSelector([anInvocation selector])];
-    if (!count)
-        count = [NSNumber numberWithInt: 1];
-    else
-        count = [NSNumber numberWithInt: [count intValue] + 1];
-    [countInvocations setObject: count forKey: NSStringFromSelector([anInvocation selector])];
-#endif
-    if ([target respondsToSelector: [anInvocation selector]])
-        [anInvocation invokeWithTarget: target];
-    else if ([defaultTarget respondsToSelector: [anInvocation selector]])
-        [anInvocation invokeWithTarget: defaultTarget];
-    // Do nothing quietly if method not implemented.
-}
-
-- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
-{
-    return [templateClass instanceMethodSignatureForSelector: aSelector];
-}
-
- at end
-

-- 
WebKit Debian packaging



More information about the Pkg-webkit-commits mailing list