FrameLoader.cpp 154 KB
Newer Older
mjs's avatar
mjs committed
1
/*
darin's avatar
darin committed
2
 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
mjs's avatar
mjs committed
3
 * Copyright (C) 2007 Trolltech ASA
mjs's avatar
mjs committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

darin's avatar
darin committed
30
31
#include "config.h"
#include "FrameLoader.h"
mjs's avatar
mjs committed
32

darin's avatar
darin committed
33
#include "Cache.h"
beidson's avatar
beidson committed
34
#include "CachedPage.h"
ggaren's avatar
ggaren committed
35
#include "Chrome.h"
beidson's avatar
beidson committed
36
#include "CString.h"
darin's avatar
darin committed
37
38
39
#include "DOMImplementation.h"
#include "DocLoader.h"
#include "Document.h"
ggaren's avatar
ggaren committed
40
#include "DocumentLoader.h"
darin's avatar
darin committed
41
42
#include "EditCommand.h"
#include "Editor.h"
andersca's avatar
andersca committed
43
#include "EditorClient.h"
darin's avatar
darin committed
44
#include "Element.h"
darin's avatar
darin committed
45
#include "Event.h"
darin's avatar
darin committed
46
#include "EventNames.h"
ggaren's avatar
ggaren committed
47
48
#include "FloatRect.h"
#include "FormState.h"
darin's avatar
darin committed
49
#include "Frame.h"
ggaren's avatar
ggaren committed
50
#include "FrameLoadRequest.h"
darin's avatar
darin committed
51
#include "FrameLoaderClient.h"
darin's avatar
darin committed
52
#include "FramePrivate.h"
ggaren's avatar
ggaren committed
53
#include "FrameTree.h"
darin's avatar
darin committed
54
#include "FrameView.h"
beidson's avatar
beidson committed
55
#include "HistoryItem.h"
darin's avatar
darin committed
56
#include "HTMLFormElement.h"
lars's avatar
lars committed
57
#include "HTMLFrameElement.h"
darin's avatar
darin committed
58
59
#include "HTMLNames.h"
#include "HTMLObjectElement.h"
ap's avatar
ap committed
60
#include "HTTPParsers.h"
darin's avatar
darin committed
61
62
#include "IconDatabase.h"
#include "IconLoader.h"
beidson's avatar
beidson committed
63
#include "Logging.h"
darin's avatar
darin committed
64
#include "MainResourceLoader.h"
andersca's avatar
andersca committed
65
#include "MimeTypeRegistry.h"
ggaren's avatar
ggaren committed
66
#include "Page.h"
ggaren's avatar
ggaren committed
67
#include "PageCache.h"
andersca's avatar
andersca committed
68
#include "ProgressTracker.h"
darin's avatar
darin committed
69
70
#include "RenderPart.h"
#include "RenderWidget.h"
beidson's avatar
beidson committed
71
#include "ResourceHandle.h"
darin's avatar
darin committed
72
73
74
75
76
#include "ResourceRequest.h"
#include "SegmentedString.h"
#include "Settings.h"
#include "SystemTime.h"
#include "TextResourceDecoder.h"
ggaren's avatar
ggaren committed
77
#include "WindowFeatures.h"
darin's avatar
darin committed
78
79
80
81
82
83
84
85
#include "XMLTokenizer.h"
#include "kjs_binding.h"
#include "kjs_proxy.h"
#include "kjs_window.h"
#include "xmlhttprequest.h"
#include <kjs/JSLock.h>
#include <kjs/object.h>

kmccullo's avatar
kmccullo committed
86
87
88
using KJS::UString;
using KJS::JSLock;
using KJS::JSValue;
mjs's avatar
mjs committed
89

darin's avatar
darin committed
90
91
namespace WebCore {

darin's avatar
darin committed
92
93
94
using namespace HTMLNames;
using namespace EventNames;

darin's avatar
darin committed
95
#if USE(LOW_BANDWIDTH_DISPLAY)
bdash's avatar
bdash committed
96
const unsigned int cMaxPendingSourceLengthInLowBandwidthDisplay = 128 * 1024;
darin's avatar
darin committed
97
98
#endif

darin's avatar
darin committed
99
100
101
struct FormSubmission {
    const char* action;
    String URL;
beidson's avatar
beidson committed
102
    RefPtr<FormData> data;
darin's avatar
darin committed
103
104
105
106
107
    String target;
    String contentType;
    String boundary;
    RefPtr<Event> event;

beidson's avatar
beidson committed
108
    FormSubmission(const char* a, const String& u, PassRefPtr<FormData> d, const String& t,
darin's avatar
darin committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
            const String& ct, const String& b, PassRefPtr<Event> e)
        : action(a)
        , URL(u)
        , data(d)
        , target(t)
        , contentType(ct)
        , boundary(b)
        , event(e)
    {
    }
};

struct ScheduledRedirection {
    enum Type { redirection, locationChange, historyNavigation, locationChangeDuringLoad };
    Type type;
    double delay;
    String URL;
    String referrer;
    int historySteps;
    bool lockHistory;
    bool wasUserGesture;

beidson's avatar
beidson committed
131
    ScheduledRedirection(double redirectDelay, const String& redirectURL, bool redirectLockHistory, bool userGesture)
darin's avatar
darin committed
132
133
134
135
136
        : type(redirection)
        , delay(redirectDelay)
        , URL(redirectURL)
        , historySteps(0)
        , lockHistory(redirectLockHistory)
beidson's avatar
beidson committed
137
        , wasUserGesture(userGesture)
darin's avatar
darin committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
    {
    }

    ScheduledRedirection(Type locationChangeType,
            const String& locationChangeURL, const String& locationChangeReferrer,
            bool locationChangeLockHistory, bool locationChangeWasUserGesture)
        : type(locationChangeType)
        , delay(0)
        , URL(locationChangeURL)
        , referrer(locationChangeReferrer)
        , historySteps(0)
        , lockHistory(locationChangeLockHistory)
        , wasUserGesture(locationChangeWasUserGesture)
    {
    }

    explicit ScheduledRedirection(int historyNavigationSteps)
        : type(historyNavigation)
        , delay(0)
        , historySteps(historyNavigationSteps)
        , lockHistory(false)
        , wasUserGesture(false)
    {
    }
};

static double storedTimeOfLastCompletedLoad;
kmccullo's avatar
kmccullo committed
165
static bool m_restrictAccessToLocal = false;
darin's avatar
darin committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

static bool getString(JSValue* result, String& string)
{
    if (!result)
        return false;
    JSLock lock;
    UString ustring;
    if (!result->getString(ustring))
        return false;
    string = ustring;
    return true;
}

bool isBackForwardLoadType(FrameLoadType type)
{
    switch (type) {
        case FrameLoadTypeStandard:
        case FrameLoadTypeReload:
        case FrameLoadTypeReloadAllowingStaleData:
        case FrameLoadTypeSame:
        case FrameLoadTypeInternal:
        case FrameLoadTypeReplace:
            return false;
        case FrameLoadTypeBack:
        case FrameLoadTypeForward:
        case FrameLoadTypeIndexedBackForward:
            return true;
    }
    ASSERT_NOT_REACHED();
    return false;
}

static int numRequests(Document* document)
{
beidson's avatar
beidson committed
200
201
202
203
    if (!document)
        return 0;
    
    return document->docLoader()->requestCount();
darin's avatar
darin committed
204
205
}

ggaren's avatar
ggaren committed
206
FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
darin's avatar
darin committed
207
    : m_frame(frame)
ggaren's avatar
ggaren committed
208
    , m_client(client)
darin's avatar
darin committed
209
210
    , m_state(FrameStateCommittedPage)
    , m_loadType(FrameLoadTypeStandard)
darin's avatar
darin committed
211
    , m_policyLoadType(FrameLoadTypeStandard)
darin's avatar
darin committed
212
213
214
215
216
217
    , m_delegateIsHandlingProvisionalLoadError(false)
    , m_delegateIsDecidingNavigationPolicy(false)
    , m_delegateIsHandlingUnimplementablePolicy(false)
    , m_firstLayoutDone(false)
    , m_quickRedirectComing(false)
    , m_sentRedirectNotification(false)
darin's avatar
darin committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    , m_inStopAllLoaders(false)
    , m_cachePolicy(CachePolicyVerify)
    , m_isExecutingJavaScriptFormAction(false)
    , m_isRunningScript(false)
    , m_wasLoadEventEmitted(false)
    , m_wasUnloadEventEmitted(false)
    , m_isComplete(false)
    , m_isLoadingMainResource(false)
    , m_cancellingWithLoadInProgress(false)
    , m_needsClear(false)
    , m_receivedData(false)
    , m_encodingWasChosenByUser(false)
    , m_containsPlugIns(false)
    , m_redirectionTimer(this, &FrameLoader::redirectionTimerFired)
weinig's avatar
weinig committed
232
    , m_checkCompletedTimer(this, &FrameLoader::checkCompletedTimerFired)
darin's avatar
darin committed
233
    , m_opener(0)
kmccullo's avatar
kmccullo committed
234
    , m_openedByDOM(false)
mjs's avatar
mjs committed
235
236
    , m_creatingInitialEmptyDocument(false)
    , m_committedFirstRealDocumentLoad(false)
darin's avatar
darin committed
237
238
239
240
241
#if USE(LOW_BANDWIDTH_DISPLAY)
    , m_useLowBandwidthDisplay(true)
    , m_finishedParsingDuringLowBandwidthDisplay(false)
    , m_needToSwitchOutLowBandwidthDisplay(false)
#endif 
darin's avatar
darin committed
242
243
244
245
246
{
}

FrameLoader::~FrameLoader()
{
darin's avatar
darin committed
247
248
249
250
251
    setOpener(0);

    HashSet<Frame*>::iterator end = m_openedFrames.end();
    for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
        (*it)->loader()->m_opener = 0;
ggaren's avatar
ggaren committed
252
253
        
    m_client->frameLoaderDestroyed();
darin's avatar
darin committed
254
255
}

mjs's avatar
mjs committed
256
257
258
259
260
261
262
263
264
void FrameLoader::init()
{
    // this somewhat odd set of steps is needed to give the frame an initial empty document
    m_creatingInitialEmptyDocument = true;
    setPolicyDocumentLoader(m_client->createDocumentLoader(ResourceRequest(String("")), SubstituteData()).get());
    setProvisionalDocumentLoader(m_policyDocumentLoader.get());
    setState(FrameStateProvisional);
    m_provisionalDocumentLoader->finishedLoading();
    begin();
265
    write("<html><body>");
mjs's avatar
mjs committed
266
267
268
269
270
271
    end();
    m_frame->document()->cancelParsing();
    m_creatingInitialEmptyDocument = false;
    m_wasLoadEventEmitted = true;
}

darin's avatar
darin committed
272
void FrameLoader::setDefersLoading(bool defers)
mjs's avatar
mjs committed
273
{
darin's avatar
darin committed
274
275
276
277
278
279
    if (m_documentLoader)
        m_documentLoader->setDefersLoading(defers);
    if (m_provisionalDocumentLoader)
        m_provisionalDocumentLoader->setDefersLoading(defers);
    if (m_policyDocumentLoader)
        m_policyDocumentLoader->setDefersLoading(defers);
darin's avatar
darin committed
280
    m_client->setDefersLoading(defers);
mjs's avatar
mjs committed
281
282
}

mjs's avatar
mjs committed
283
Frame* FrameLoader::createWindow(const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
ggaren's avatar
ggaren committed
284
285
286
{ 
    ASSERT(!features.dialog || request.frameName().isEmpty());

mjs's avatar
mjs committed
287
    if (!request.frameName().isEmpty() && request.frameName() != "_blank")
ggaren's avatar
ggaren committed
288
        if (Frame* frame = m_frame->tree()->find(request.frameName())) {
darin's avatar
darin committed
289
            if (!request.resourceRequest().url().isEmpty())
290
                frame->loader()->load(request, true, 0, 0, HashMap<String, String>());
ggaren's avatar
ggaren committed
291
            frame->page()->chrome()->focus();
mjs's avatar
mjs committed
292
            created = false;
ggaren's avatar
ggaren committed
293
294
295
296
297
            return frame;
        }

    // FIXME: Setting the referrer should be the caller's responsibility.
    FrameLoadRequest requestWithReferrer = request;
darin's avatar
darin committed
298
    requestWithReferrer.resourceRequest().setHTTPReferrer(m_outgoingReferrer);
ggaren's avatar
ggaren committed
299
300
301
    
    Page* page;
    if (features.dialog)
302
        page = m_frame->page()->chrome()->createModalDialog(m_frame, requestWithReferrer);
ggaren's avatar
ggaren committed
303
    else
304
        page = m_frame->page()->chrome()->createWindow(m_frame, requestWithReferrer);
ggaren's avatar
ggaren committed
305
306
307
308
    if (!page)
        return 0;

    Frame* frame = page->mainFrame();
mjs's avatar
mjs committed
309
310
    if (request.frameName() != "_blank")
        frame->tree()->setName(request.frameName());
ggaren's avatar
ggaren committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

    page->chrome()->setToolbarsVisible(features.toolBarVisible || features.locationBarVisible);
    page->chrome()->setStatusbarVisible(features.statusBarVisible);
    page->chrome()->setScrollbarsVisible(features.scrollbarsVisible);
    page->chrome()->setMenubarVisible(features.menuBarVisible);
    page->chrome()->setResizable(features.resizable);

    // 'x' and 'y' specify the location of the window, while 'width' and 'height' 
    // specify the size of the page. We can only resize the window, so 
    // adjust for the difference between the window size and the page size.

    FloatRect windowRect = page->chrome()->windowRect();
    FloatSize pageSize = page->chrome()->pageRect().size();
    if (features.xSet)
        windowRect.setX(features.x);
    if (features.ySet)
        windowRect.setY(features.y);
    if (features.widthSet)
        windowRect.setWidth(features.width + (windowRect.width() - pageSize.width()));
    if (features.heightSet)
        windowRect.setHeight(features.height + (windowRect.height() - pageSize.height()));
    page->chrome()->setWindowRect(windowRect);

    page->chrome()->show();

mjs's avatar
mjs committed
336
    created = true;
ggaren's avatar
ggaren committed
337
338
    return frame;
}
darin's avatar
darin committed
339

bdakin's avatar
bdakin committed
340
341
342
343
344
bool FrameLoader::canHandleRequest(const ResourceRequest& request)
{
    return m_client->canHandleRequest(request);
}

darin's avatar
darin committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
void FrameLoader::changeLocation(const String& URL, const String& referrer, bool lockHistory, bool userGesture)
{
    if (URL.find("javascript:", 0, false) == 0) {
        String script = KURL::decode_string(URL.substring(strlen("javascript:")).deprecatedString());
        JSValue* result = executeScript(0, script, userGesture);
        String scriptResult;
        if (getString(result, scriptResult)) {
            begin(m_URL);
            write(scriptResult);
            end();
        }
        return;
    }

    ResourceRequestCachePolicy policy = (m_cachePolicy == CachePolicyReload) || (m_cachePolicy == CachePolicyRefresh)
        ? ReloadIgnoringCacheData : UseProtocolCachePolicy;
    ResourceRequest request(completeURL(URL), referrer, policy);
    
beidson's avatar
beidson committed
363
    urlSelected(request, "_self", 0, lockHistory, userGesture);
darin's avatar
darin committed
364
365
}

366
void FrameLoader::urlSelected(const ResourceRequest& request, const String& _target, Event* triggeringEvent, bool lockHistory, bool userGesture)
darin's avatar
darin committed
367
{
368
    String target = _target;
darin's avatar
darin committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    if (target.isEmpty() && m_frame->document())
        target = m_frame->document()->baseTarget();

    const KURL& url = request.url();
    if (url.url().startsWith("javascript:", false)) {
        executeScript(0, KURL::decode_string(url.url().mid(strlen("javascript:"))), true);
        return;
    }

    if (!url.isValid())
        return;

    FrameLoadRequest frameRequest(request, target);

    if (frameRequest.resourceRequest().httpReferrer().isEmpty())
        frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);

386
    urlSelected(frameRequest, triggeringEvent, userGesture);
darin's avatar
darin committed
387
388
}

darin's avatar
darin committed
389
bool FrameLoader::requestFrame(HTMLFrameOwnerElement* ownerElement, const String& urlString, const AtomicString& frameName)
darin's avatar
darin committed
390
{
darin's avatar
darin committed
391
392
393
394
395
396
397
398
#if USE(LOW_BANDWIDTH_DISPLAY)
    // don't create sub-frame during low bandwidth display
    if (frame()->document()->inLowBandwidthDisplay()) {
        m_needToSwitchOutLowBandwidthDisplay = true;
        return false;
    }
#endif

darin's avatar
darin committed
399
400
401
402
    // Support for <frame src="javascript:string">
    KURL scriptURL;
    KURL url;
    if (urlString.startsWith("javascript:", false)) {
darin's avatar
darin committed
403
        scriptURL = urlString.deprecatedString();
darin's avatar
darin committed
404
405
406
407
408
        url = "about:blank";
    } else
        url = completeURL(urlString);

    Frame* frame = m_frame->tree()->child(frameName);
andersca's avatar
andersca committed
409
    if (frame)
beidson's avatar
beidson committed
410
        frame->loader()->scheduleLocationChange(url.url(), m_outgoingReferrer, false, userGestureHint());
andersca's avatar
andersca committed
411
    else
darin's avatar
darin committed
412
413
414
415
416
417
418
419
420
421
422
        frame = loadSubframe(ownerElement, url, frameName, m_outgoingReferrer);
    
    if (!frame)
        return false;

    if (!scriptURL.isEmpty())
        frame->loader()->replaceContentsWithScriptResult(scriptURL);

    return true;
}

darin's avatar
darin committed
423
Frame* FrameLoader::loadSubframe(HTMLFrameOwnerElement* ownerElement, const KURL& url, const String& name, const String& referrer)
darin's avatar
darin committed
424
{
lars's avatar
lars committed
425
426
427
428
429
430
431
432
433
434
    bool allowsScrolling = true;
    int marginWidth = -1;
    int marginHeight = -1;
    if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag)) {
        HTMLFrameElementBase* o = static_cast<HTMLFrameElementBase*>(ownerElement);
        allowsScrolling = o->scrollingMode() != ScrollbarAlwaysOff;
        marginWidth = o->getMarginWidth();
        marginHeight = o->getMarginHeight();
    }

kmccullo's avatar
kmccullo committed
435
    if (!canLoad(url, referrer)) {
kmccullo's avatar
kmccullo committed
436
        FrameLoader::reportLocalLoadFailed(frame()->page(), url.url());
lars's avatar
lars committed
437
        return 0;
kmccullo's avatar
kmccullo committed
438
    }
lars's avatar
lars committed
439

kmccullo's avatar
kmccullo committed
440
    bool hideReferrer = shouldHideReferrer(url, referrer);
lars's avatar
lars committed
441
442
443
    Frame* frame = m_client->createFrame(url, name, ownerElement, hideReferrer ? String() : referrer,
                                         allowsScrolling, marginWidth, marginHeight);

darin's avatar
darin committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    if (!frame)  {
        checkEmitLoadEvent();
        return 0;
    }
    
    frame->loader()->m_isComplete = false;
    
    if (ownerElement->renderer() && frame->view())
        static_cast<RenderWidget*>(ownerElement->renderer())->setWidget(frame->view());
    
    checkEmitLoadEvent();
    
    // In these cases, the synchronous load would have finished
    // before we could connect the signals, so make sure to send the 
    // completed() signal for the child by hand
    // FIXME: In this case the Frame will have finished loading before 
    // it's being added to the child list. It would be a good idea to
    // create the child first, then invoke the loader separately.
    if (url.isEmpty() || url == "about:blank") {
        frame->loader()->completed();
        frame->loader()->checkCompleted();
    }

    return frame;
}

void FrameLoader::submitFormAgain()
{
    if (m_isRunningScript)
        return;
    OwnPtr<FormSubmission> form(m_deferredFormSubmission.release());
    if (form)
        submitForm(form->action, form->URL, form->data, form->target,
            form->contentType, form->boundary, form->event.get());
}

beidson's avatar
beidson committed
480
void FrameLoader::submitForm(const char* action, const String& url, PassRefPtr<FormData> formData,
darin's avatar
darin committed
481
482
    const String& target, const String& contentType, const String& boundary, Event* event)
{
beidson's avatar
beidson committed
483
484
    ASSERT(formData.get());
    
485
    KURL u = completeURL(url.isNull() ? "" : url);
darin's avatar
darin committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    if (!u.isValid())
        return;

    DeprecatedString urlString = u.url();
    if (urlString.startsWith("javascript:", false)) {
        m_isExecutingJavaScriptFormAction = true;
        executeScript(0, KURL::decode_string(urlString.mid(strlen("javascript:"))));
        m_isExecutingJavaScriptFormAction = false;
        return;
    }

    if (m_isRunningScript) {
        if (m_deferredFormSubmission)
            return;
beidson's avatar
beidson committed
500
        m_deferredFormSubmission.set(new FormSubmission(action, url, formData, target,
darin's avatar
darin committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
            contentType, boundary, event));
        return;
    }

    FrameLoadRequest frameRequest;

    if (!m_outgoingReferrer.isEmpty())
        frameRequest.resourceRequest().setHTTPReferrer(m_outgoingReferrer);

    frameRequest.setFrameName(target.isEmpty() ? m_frame->document()->baseTarget() : target);

    // Handle mailto: forms
    bool mailtoForm = u.protocol() == "mailto";
    if (mailtoForm) {
        // Append body=
darin's avatar
darin committed
516
        String body;
darin's avatar
darin committed
517
518
        if (equalIgnoringCase(contentType, "multipart/form-data"))
            // FIXME: is this correct? I suspect not, but what site can we test this on?
darin's avatar
darin committed
519
520
            body = formData->flattenToString();
        else if (equalIgnoringCase(contentType, "text/plain"))
darin's avatar
darin committed
521
            // Convention seems to be to decode, and s/&/\n/
darin's avatar
darin committed
522
523
524
525
526
527
528
            body = KURL::decode_string(
                formData->flattenToString().replace('&', '\n')
                .replace('+', ' ').deprecatedString()); // Recode for the URL
        else
            body = formData->flattenToString();

        String query = u.query();
darin's avatar
darin committed
529
        if (!query.isEmpty())
darin's avatar
darin committed
530
531
            query.append('&');
        u.setQuery((query + "body=" + KURL::encode_string(body.deprecatedString())).deprecatedString());
darin's avatar
darin committed
532
533
534
535
    }

    if (strcmp(action, "GET") == 0) {
        if (!mailtoForm)
beidson's avatar
beidson committed
536
            u.setQuery(formData->flattenToString().deprecatedString());
darin's avatar
darin committed
537
    } else {
beidson's avatar
beidson committed
538
        frameRequest.resourceRequest().setHTTPBody(formData.get());
darin's avatar
darin committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
        frameRequest.resourceRequest().setHTTPMethod("POST");

        // construct some user headers if necessary
        if (contentType.isNull() || contentType == "application/x-www-form-urlencoded")
            frameRequest.resourceRequest().setHTTPContentType(contentType);
        else // contentType must be "multipart/form-data"
            frameRequest.resourceRequest().setHTTPContentType(contentType + "; boundary=" + boundary);
    }

    frameRequest.resourceRequest().setURL(u);

    submitForm(frameRequest, event);
}

void FrameLoader::stopLoading(bool sendUnload)
{
    if (m_frame->document() && m_frame->document()->tokenizer())
        m_frame->document()->tokenizer()->stopParsing();
mjs's avatar
mjs committed
557

darin's avatar
darin committed
558
559
560
    if (sendUnload) {
        if (m_frame->document()) {
            if (m_wasLoadEventEmitted && !m_wasUnloadEventEmitted) {
ggaren's avatar
ggaren committed
561
562
563
                Node* currentFocusedNode = m_frame->document()->focusedNode();
                if (currentFocusedNode)
                    currentFocusedNode->aboutToUnload();
darin's avatar
darin committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
                m_frame->document()->dispatchWindowEvent(unloadEvent, false, false);
                if (m_frame->document())
                    m_frame->document()->updateRendering();
                m_wasUnloadEventEmitted = true;
            }
        }
        if (m_frame->document() && !m_frame->document()->inPageCache())
            m_frame->document()->removeAllEventListenersFromAllNodes();
    }

    m_isComplete = true; // to avoid calling completed() in finishedParsing() (David)
    m_isLoadingMainResource = false;
    m_wasLoadEventEmitted = true; // don't want that one either
    m_cachePolicy = CachePolicyVerify; // Why here?

    if (m_frame->document() && m_frame->document()->parsing()) {
        finishedParsing();
        m_frame->document()->setParsing(false);
    }
  
    m_workingURL = KURL();

    if (Document* doc = m_frame->document()) {
        if (DocLoader* docLoader = doc->docLoader())
            cache()->loader()->cancelRequests(docLoader);
        XMLHttpRequest::cancelRequests(doc);
    }

    // tell all subframes to stop as well
    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
        child->loader()->stopLoading(sendUnload);

    cancelRedirection();
darin's avatar
darin committed
597
598
599
600
601
602
603
604

#if USE(LOW_BANDWIDTH_DISPLAY)
    if (m_frame->document() && m_frame->document()->inLowBandwidthDisplay()) {
        // Since loading is forced to stop, reset the state without really switching.
        m_needToSwitchOutLowBandwidthDisplay = false;
        switchOutLowBandwidthDisplayIfReady();
    }
#endif  
darin's avatar
darin committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
}

void FrameLoader::stop()
{
    // http://bugs.webkit.org/show_bug.cgi?id=10854
    // The frame's last ref may be removed and it will be deleted by checkCompleted().
    RefPtr<Frame> protector(m_frame);
    
    if (m_frame->document()) {
        if (m_frame->document()->tokenizer())
            m_frame->document()->tokenizer()->stopParsing();
        m_frame->document()->finishParsing();
    } else
        // WebKit partially uses WebCore when loading non-HTML docs.  In these cases doc==nil, but
        // WebCore is enough involved that we need to checkCompleted() in order for m_bComplete to
        // become true. An example is when a subframe is a pure text doc, and that subframe is the
        // last one to complete.
        checkCompleted();
    if (m_iconLoader)
        m_iconLoader->stopLoading();
}

bool FrameLoader::closeURL()
{
    saveDocumentState();
    stopLoading(true);
ggaren's avatar
ggaren committed
631
    m_frame->editor()->clearUndoRedoOperations();
darin's avatar
darin committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    return true;
}

void FrameLoader::cancelRedirection(bool cancelWithLoadInProgress)
{
    m_cancellingWithLoadInProgress = cancelWithLoadInProgress;

    stopRedirectionTimer();

    m_scheduledRedirection.clear();
}

KURL FrameLoader::iconURL()
{
    // If this isn't a top level frame, return nothing
    if (m_frame->tree() && m_frame->tree()->parent())
        return "";
        
    // If we have an iconURL from a Link element, return that
    if (m_frame->document() && !m_frame->document()->iconURL().isEmpty())
        return m_frame->document()->iconURL().deprecatedString();
        
    // Don't return a favicon iconURL unless we're http or https
    if (m_URL.protocol() != "http" && m_URL.protocol() != "https")
        return "";
        
    KURL url;
    url.setProtocol(m_URL.protocol());
    url.setHost(m_URL.host());
beidson's avatar
beidson committed
661
662
    if (int port = m_URL.port())
        url.setPort(port);
darin's avatar
darin committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    url.setPath("/favicon.ico");
    return url;
}

bool FrameLoader::didOpenURL(const KURL& url)
{
    if (m_scheduledRedirection && m_scheduledRedirection->type == ScheduledRedirection::locationChangeDuringLoad)
        // A redirect was scheduled before the document was created.
        // This can happen when one frame changes another frame's location.
        return false;

    cancelRedirection();
    m_frame->editor()->setLastEditCommand(0);
    closeURL();

    m_isComplete = false;
    m_isLoadingMainResource = true;
    m_wasLoadEventEmitted = false;

682
683
    m_frame->setJSStatusBarText(String());
    m_frame->setJSDefaultStatusBarText(String());
darin's avatar
darin committed
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704

    m_URL = url;
    if (m_URL.protocol().startsWith("http") && !m_URL.host().isEmpty() && m_URL.path().isEmpty())
        m_URL.setPath("/");
    m_workingURL = m_URL;

    started();

    return true;
}

void FrameLoader::didExplicitOpen()
{
    m_isComplete = false;
    m_wasLoadEventEmitted = false;

    // Prevent window.open(url) -- eg window.open("about:blank") -- from blowing away results
    // from a subsequent window.document.open / window.document.write call. 
    // Cancelling redirection here works for all cases because document.open 
    // implicitly precedes document.write.
    cancelRedirection(); 
aliceli1's avatar
aliceli1 committed
705
706
    if (m_frame->document()->URL() != "about:blank")
        m_URL = m_frame->document()->URL();
darin's avatar
darin committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
}

void FrameLoader::replaceContentsWithScriptResult(const KURL& url)
{
    JSValue* result = executeScript(0, KURL::decode_string(url.url().mid(strlen("javascript:"))));
    String scriptResult;
    if (!getString(result, scriptResult))
        return;
    begin();
    write(scriptResult);
    end();
}

JSValue* FrameLoader::executeScript(Node* node, const String& script, bool forceUserGesture)
{
    return executeScript(forceUserGesture ? String() : String(m_URL.url()), 0, node, script);
}

JSValue* FrameLoader::executeScript(const String& URL, int baseLine, Node* node, const String& script)
{
    KJSProxy* proxy = m_frame->scriptProxy();
    if (!proxy)
        return 0;

    bool wasRunningScript = m_isRunningScript;
    m_isRunningScript = true;

    JSValue* result = proxy->evaluate(URL, baseLine, script, node);

    if (!wasRunningScript) {
        m_isRunningScript = false;
        submitFormAgain();
        Document::updateDocumentsRendering();
    }

    return result;
}

void FrameLoader::cancelAndClear()
{
    cancelRedirection();

    if (!m_isComplete)
        closeURL();

    clear(false);
}

void FrameLoader::clear(bool clearWindowProperties)
{
    // FIXME: Commenting out the below line causes <http://bugs.webkit.org/show_bug.cgi?id=11212>, but putting it
    // back causes a measurable performance regression which we will need to fix to restore the correct behavior
    // urlsBridgeKnowsAbout.clear();

#if PLATFORM(MAC)
mjs's avatar
mjs committed
762
    m_frame->setMarkedTextRange(0, nil, nil);
darin's avatar
darin committed
763
764
765
766
767
#endif

    if (!m_needsClear)
        return;
    m_needsClear = false;
lars's avatar
lars committed
768
    
darin's avatar
darin committed
769
770
    if (m_frame->document()) {
        m_frame->document()->cancelParsing();
beidson's avatar
beidson committed
771
        m_frame->document()->willRemove();
darin's avatar
darin committed
772
773
774
775
776
777
778
        m_frame->document()->detach();
    }

    // Do this after detaching the document so that the unload event works.
    if (clearWindowProperties && m_frame->scriptProxy())
        m_frame->scriptProxy()->clear();

darin's avatar
darin committed
779
780
    m_frame->selectionController()->clear();
    m_frame->eventHandler()->clear();
darin's avatar
darin committed
781
782
783
784
785
    if (m_frame->view())
        m_frame->view()->clear();

    // Do not drop the document before the script proxy and view are cleared, as some destructors
    // might still try to access the document.
darin's avatar
darin committed
786
    m_frame->setDocument(0);
darin's avatar
darin committed
787
788
789
    m_decoder = 0;

    m_containsPlugIns = false;
mjs's avatar
mjs committed
790
    m_frame->cleanupScriptObjects();
darin's avatar
darin committed
791
  
darin's avatar
darin committed
792
    m_redirectionTimer.stop();
darin's avatar
darin committed
793
794
    m_scheduledRedirection.clear();

weinig's avatar
weinig committed
795
796
    m_checkCompletedTimer.stop();

darin's avatar
darin committed
797
798
799
800
801
802
803
804
805
806
807
808
809
    m_receivedData = false;

    if (!m_encodingWasChosenByUser)
        m_encoding = String();
}

void FrameLoader::receivedFirstData()
{
    begin(m_workingURL);

    m_frame->document()->docLoader()->setCachePolicy(m_cachePolicy);
    m_workingURL = KURL();

darin's avatar
darin committed
810
811
    double delay;
    String URL;
darin's avatar
darin committed
812
813
814
    if (!m_documentLoader)
        return;
    if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, URL))
ap's avatar
ap committed
815
816
817
        return;

    if (URL.isEmpty())
darin's avatar
darin committed
818
        URL = m_URL.url();
ap's avatar
ap committed
819
820
    else
        URL = m_frame->document()->completeURL(URL);
darin's avatar
darin committed
821

beidson's avatar
beidson committed
822
    scheduleRedirection(delay, URL);
darin's avatar
darin committed
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
}

const String& FrameLoader::responseMIMEType() const
{
    return m_responseMIMEType;
}

void FrameLoader::setResponseMIMEType(const String& type)
{
    m_responseMIMEType = type;
}

void FrameLoader::begin()
{
    begin(KURL());
}

void FrameLoader::begin(const KURL& url)
{
    clear();
    partClearedInBegin();

    m_needsClear = true;
    m_isComplete = false;
    m_wasLoadEventEmitted = false;
    m_isLoadingMainResource = true;

    KURL ref(url);
    ref.setUser(DeprecatedString());
    ref.setPass(DeprecatedString());
    ref.setRef(DeprecatedString());
    m_outgoingReferrer = ref.url();
    m_URL = url;
    KURL baseurl;

    if (!m_URL.isEmpty())
        baseurl = m_URL;

mjs's avatar
mjs committed
861
    RefPtr<Document> document = DOMImplementation::instance()->createDocument(m_responseMIMEType, m_frame, m_frame->inViewSourceMode());
862
    m_frame->setDocument(document);
darin's avatar
darin committed
863
864
865
866
867
868
869
870
871
872

    document->setURL(m_URL.url());
    // We prefer m_baseURL over m_URL because m_URL changes when we are
    // about to load a new page.
    document->setBaseURL(baseurl.url());
    if (m_decoder)
        document->setDecoder(m_decoder.get());

    updatePolicyBaseURL();

ggaren's avatar
ggaren committed
873
874
875
    Settings* settings = document->settings();
    document->docLoader()->setAutoLoadImages(settings && settings->loadsImagesAutomatically());
    KURL userStyleSheet = settings ? settings->userStyleSheetLocation() : KURL();
darin's avatar
darin committed
876
    if (!userStyleSheet.isEmpty())
ggaren's avatar
ggaren committed
877
        m_frame->setUserStyleSheetLocation(userStyleSheet);
darin's avatar
darin committed
878
879
880
881
882
883
884

    restoreDocumentState();

    document->implicitOpen();

    if (m_frame->view())
        m_frame->view()->resizeContents(0, 0);
darin's avatar
darin committed
885
886
887
888
889
890
891
892
893
894
895
896

#if USE(LOW_BANDWIDTH_DISPLAY)
    // Low bandwidth display is a first pass display without external resources
    // used to give an instant visual feedback. We currently only enable it for
    // HTML documents in the top frame.
    if (document->isHTMLDocument() && !m_frame->tree()->parent() && m_useLowBandwidthDisplay) {
        m_pendingSourceInLowBandwidthDisplay = String();
        m_finishedParsingDuringLowBandwidthDisplay = false;
        m_needToSwitchOutLowBandwidthDisplay = false;
        document->setLowBandwidthDisplay(true);
    }
#endif
darin's avatar
darin committed
897
898
}

ap's avatar
ap committed
899
void FrameLoader::write(const char* str, int len, bool flush)
darin's avatar
darin committed
900
{
ap's avatar
ap committed
901
    if (len == 0 && !flush)
darin's avatar
darin committed
902
903
904
905
906
907
908
        return;
    
    if (len == -1)
        len = strlen(str);

    Tokenizer* tokenizer = m_frame->document()->tokenizer();
    if (tokenizer && tokenizer->wantsRawData()) {
andersca's avatar
andersca committed
909
910
        if (len > 0)
            tokenizer->writeRawData(str, len);
darin's avatar
darin committed
911
912
913
914
        return;
    }
    
    if (!m_decoder) {
ggaren's avatar
ggaren committed
915
916
        Settings* settings = m_frame->settings();
        m_decoder = new TextResourceDecoder(m_responseMIMEType, settings ? settings->defaultTextEncodingName() : String());
darin's avatar
darin committed
917
918
919
920
921
922
923
924
        if (!m_encoding.isNull())
            m_decoder->setEncoding(m_encoding,
                m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
        if (m_frame->document())
            m_frame->document()->setDecoder(m_decoder.get());
    }

    String decoded = m_decoder->decode(str, len);
ap's avatar
ap committed
925
926
    if (flush)
        decoded += m_decoder->flush();
darin's avatar
darin committed
927
928
929
    if (decoded.isEmpty())
        return;

darin's avatar
darin committed
930
931
932
933
934
935
936
#if USE(LOW_BANDWIDTH_DISPLAY)
    if (m_frame->document()->inLowBandwidthDisplay())
        m_pendingSourceInLowBandwidthDisplay.append(decoded);
    else // reset policy which is changed in switchOutLowBandwidthDisplayIfReady()
        m_frame->document()->docLoader()->setCachePolicy(m_cachePolicy);    
#endif

darin's avatar
darin committed
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
    if (!m_receivedData) {
        m_receivedData = true;
        m_frame->document()->determineParseMode(decoded);
        if (m_decoder->encoding().usesVisualOrdering())
            m_frame->document()->setVisuallyOrdered();
        m_frame->document()->recalcStyle(Node::Force);
    }

    if (tokenizer) {
        ASSERT(!tokenizer->wantsRawData());
        tokenizer->write(decoded, true);
    }
}

void FrameLoader::write(const String& str)
{
    if (str.isNull())
        return;

    if (!m_receivedData) {
        m_receivedData = true;
        m_frame->document()->setParseMode(Document::Strict);
    }

    if (Tokenizer* tokenizer = m_frame->document()->tokenizer())
        tokenizer->write(str, true);
}

void FrameLoader::end()
{
    m_isLoadingMainResource = false;
    endIfNotLoading();
}

void FrameLoader::endIfNotLoading()
{
    // http://bugs.webkit.org/show_bug.cgi?id=10854
    // The frame's last ref may be removed and it can be deleted by checkCompleted(), 
    // so we'll add a protective refcount
    RefPtr<Frame> protector(m_frame);

    if (m_isLoadingMainResource)
        return;

    // make sure nothing's left in there
    if (m_frame->document()) {
ap's avatar
ap committed
983
        write(0, 0, true);
darin's avatar
darin committed
984
        m_frame->document()->finishParsing();
darin's avatar
darin committed
985
986
987
988
989
990
#if USE(LOW_BANDWIDTH_DISPLAY)
        if (m_frame->document()->inLowBandwidthDisplay()) {
            m_finishedParsingDuringLowBandwidthDisplay = true;
            switchOutLowBandwidthDisplayIfReady();
        }
#endif            
darin's avatar
darin committed
991
992
993
994
995
996
997
    } else
        // WebKit partially uses WebCore when loading non-HTML docs.  In these cases doc==nil, but
        // WebCore is enough involved that we need to checkCompleted() in order for m_bComplete to
        // become true.  An example is when a subframe is a pure text doc, and that subframe is the
        // last one to complete.
        checkCompleted();

beidson's avatar
beidson committed
998
999
    if (m_documentLoader && !m_documentLoader->isLoadingFromCachedPage())
        startIconLoader();
darin's avatar
darin committed
1000
1001
1002
1003
1004
1005
1006
1007
1008
}

void FrameLoader::startIconLoader()
{
    // FIXME: We kick off the icon loader when the frame is done receiving its main resource.
    // But we should instead do it when we're done parsing the head element.
    if (!isLoadingMainFrame())
        return;

ggaren's avatar
ggaren committed
1009
    if (!iconDatabase() || !iconDatabase()->enabled())
darin's avatar
darin committed
1010
1011
1012
1013
1014
1015
1016
1017
        return;

    KURL url(iconURL());
    String urlString(url.url());
    if (urlString.isEmpty())
        return;

    // If we already have an unexpired icon, we won't kick off a load but we *will* map the appropriate URLs to it
ggaren's avatar
ggaren committed
1018
    if (iconDatabase()->hasEntryForIconURL(urlString) && loadType() != FrameLoadTypeReload && !iconDatabase()->isIconExpiredForIconURL(urlString)) {
beidson's avatar
beidson committed
1019
        LOG(IconDatabase, "FrameLoader::startIconLoader() - Committing iconURL %s to database", urlString.ascii().data());
darin's avatar
darin committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
        commitIconURLToIconDatabase(url);
        return;
    }

    if (!m_iconLoader)
        m_iconLoader.set(IconLoader::create(m_frame).release());
    m_iconLoader->startLoading();
}

kmccullo's avatar
kmccullo committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
bool FrameLoader::restrictAccessToLocal()
{
    return m_restrictAccessToLocal;
}

void FrameLoader::setRestrictAccessToLocal(bool access)
{
    m_restrictAccessToLocal = access;
}

static HashSet<String, CaseInsensitiveHash<String> >& localSchemes()
{
    static HashSet<String, CaseInsensitiveHash<String> > localSchemes;

    if (localSchemes.isEmpty()) {
        localSchemes.add("file");
        localSchemes.add("applewebdata");
    }

    return localSchemes;
}

darin's avatar
darin committed
1051
1052
void FrameLoader::commitIconURLToIconDatabase(const KURL& icon)
{
ggaren's avatar
ggaren committed
1053
    ASSERT(iconDatabase());
beidson's avatar
beidson committed
1054
    LOG(IconDatabase, "Committing iconURL %s to database for pageURLs %s and %s", icon.url().ascii(), m_URL.url().ascii(), originalRequestURL().url().ascii());
ggaren's avatar
ggaren committed
1055
1056
    iconDatabase()->setIconURLForPageURL(icon.url(), m_URL.url());
    iconDatabase()->setIconURLForPageURL(icon.url(), originalRequestURL().url());
darin's avatar
darin committed
1057
1058
}

beidson's avatar
beidson committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
void FrameLoader::restoreDocumentState()
{
    Document* doc = m_frame->document();
    if (!doc)
        return;
        
    HistoryItem* itemToRestore = 0;
    
    switch (loadType()) {
        case FrameLoadTypeReload:
        case FrameLoadTypeReloadAllowingStaleData:
        case FrameLoadTypeSame:
        case FrameLoadTypeReplace:
            break;
        case FrameLoadTypeBack:
        case FrameLoadTypeForward:
        case FrameLoadTypeIndexedBackForward:
        case FrameLoadTypeInternal:
        case FrameLoadTypeStandard:
            itemToRestore = m_currentHistoryItem.get(); 
    }
    
    if (!itemToRestore)
        return;
        
    doc->setStateForNewFormElements(itemToRestore->documentState());
}

darin's avatar
darin committed
1087
1088
1089
void FrameLoader::gotoAnchor()
{
    // If our URL has no ref, then we have no place we need to jump to.
rwlbuis's avatar
rwlbuis committed
1090
1091
1092
1093
1094
    // OTOH if css target was set previously, we want to set it to 0, recalc
    // and possibly repaint because :target pseudo class may have been
    // set(See bug 11321)
    if (!m_URL.hasRef() &&
        !(m_frame->document() && m_frame->document()->getCSSTarget()))
darin's avatar
darin committed
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
        return;

    DeprecatedString ref = m_URL.encodedHtmlRef();
    if (!gotoAnchor(ref)) {
        // Can't use htmlRef() here because it doesn't know which encoding to use to decode.
        // Decoding here has to match encoding in completeURL, which means it has to use the
        // page's encoding rather than UTF-8.
        if (m_decoder)
            gotoAnchor(KURL::decode_string(ref, m_decoder->encoding()));
    }
}

void FrameLoader::finishedParsing()
{
mjs's avatar
mjs committed
1109
1110
1111
    if (m_creatingInitialEmptyDocument)
        return;

darin's avatar
darin committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
    // This can be called from the Frame's destructor, in which case we shouldn't protect ourselves
    // because doing so will cause us to re-enter the destructor when protector goes out of scope.
    RefPtr<Frame> protector = m_frame->refCount() > 0 ? m_frame : 0;

    checkCompleted();

    if (!m_frame->view())
        return; // We are being destroyed by something checkCompleted called.

    // Check if the scrollbars are really needed for the content.
    // If not, remove them, relayout, and repaint.
    m_frame->view()->restoreScrollbar();

sullivan's avatar
sullivan committed
1125
1126
    m_client->dispatchDidFinishDocumentLoad();

darin's avatar
darin committed
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
    gotoAnchor();
}

void FrameLoader::loadDone()
{
    if (m_frame->document())
        checkCompleted();
}

void FrameLoader::checkCompleted()
{
    // Any frame that hasn't completed yet?
    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
        if (!child->loader()->m_isComplete)
            return;

    // Have we completed before?
    if (m_isComplete)
        return;

    // Are we still parsing?
    if (m_frame->document() && m_frame->document()->parsing())
        return;

    // Still waiting for images/scripts?
beidson's avatar
beidson committed
1152
1153
    if (m_frame->document())
        if (numRequests(m_frame->document()))
darin's avatar
darin committed
1154
1155
            return;

darin's avatar
darin committed
1156
1157
1158
1159
1160
1161
#if USE(LOW_BANDWIDTH_DISPLAY)
    // as switch will be called, don't complete yet
    if (m_frame->document() && m_frame->document()->inLowBandwidthDisplay() && m_needToSwitchOutLowBandwidthDisplay)
        return;
#endif

darin's avatar
darin committed
1162
1163
1164
    // OK, completed.
    m_isComplete = true;

weinig's avatar
weinig committed
1165
    RefPtr<Frame> protect(m_frame);
darin's avatar
darin committed
1166
1167
1168
1169
1170
1171
1172
1173
    checkEmitLoadEvent(); // if we didn't do it before

    // Do not start a redirection timer for subframes here.
    // That is deferred until the parent is completed.
    if (m_scheduledRedirection && !m_frame->tree()->parent())
        startRedirectionTimer();

    completed();
mjs's avatar
mjs committed
1174
1175
    if (m_frame->page())
        checkLoadComplete();
darin's avatar
darin committed
1176
1177
}

weinig's avatar
weinig committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
void FrameLoader::checkCompletedTimerFired(Timer<FrameLoader>*)
{
    checkCompleted();
}

void FrameLoader::scheduleCheckCompleted()
{
    if (!m_checkCompletedTimer.isActive())
        m_checkCompletedTimer.startOneShot(0);
}

darin's avatar
darin committed
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
void FrameLoader::checkEmitLoadEvent()
{
    if (m_wasLoadEventEmitted || !m_frame->document() || m_frame->document()->parsing())
        return;

    for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
        if (!child->loader()->m_isComplete) // still got a frame running -> too early
            return;

    // All frames completed -> set their domain to the frameset's domain
    // This must only be done when loading the frameset initially (#22039),
    // not when following a link in a frame (#44162).
    if (m_frame->document()) {
        String domain = m_frame->document()->domain();
        for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
            if (child->document())
                child->document()->setDomain(domain);
    }

    m_wasLoadEventEmitted = true;
    m_wasUnloadEventEmitted = false;
    if (m_frame->document())
        m_frame->document()->implicitClose();
}

KURL FrameLoader::baseURL() const
{
mjs's avatar
mjs committed
1216
    ASSERT(m_frame->document());
darin's avatar
darin committed
1217
1218
1219
1220
1221
    return m_frame->document()->baseURL();
}

String FrameLoader::baseTarget() const
{
mjs's avatar
mjs committed
1222
    ASSERT(m_frame->document());
darin's avatar
darin committed
1223
1224
1225
1226
1227
    return m_frame->document()->baseTarget();
}

KURL FrameLoader::completeURL(const String& url)
{
mjs's avatar
mjs committed
1228
    ASSERT(m_frame->document());
darin's avatar
darin committed
1229
1230
1231
    return m_frame->document()->completeURL(url).deprecatedString();
}

beidson's avatar
beidson committed
1232
void FrameLoader::scheduleRedirection(double delay, const String& url)
darin's avatar
darin committed
1233
1234
1235
{
    if (delay < 0 || delay > INT_MAX / 1000)
        return;
beidson's avatar
beidson committed
1236
1237
1238
        
    // We want a new history item if the refresh timeout > 1 second.  We accomplish this
    // by pretending a slow redirect is a user gesture and passing false for lockHistory
darin's avatar
darin committed
1239
    if (!m_scheduledRedirection || delay <= m_scheduledRedirection->delay)
beidson's avatar
beidson committed
1240
        scheduleRedirection(new ScheduledRedirection(delay, url, delay <= 1, delay > 1));
darin's avatar
darin committed
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
}

void FrameLoader::scheduleLocationChange(const String& url, const String& referrer, bool lockHistory, bool wasUserGesture)
{    
    // If the URL we're going to navigate to is the same as the current one, except for the
    // fragment part, we don't need to schedule the location change.
    KURL u(url.deprecatedString());
    if (u.hasRef() && equalIgnoringRef(m_URL, u)) {
        changeLocation(url, referrer, lockHistory, wasUserGesture);
        return;
    }

    // Handle a location change of a page with no document as a special case.
    // This may happen when a frame changes the location of another frame.
mjs's avatar
mjs committed
1255
    bool duringLoad = !m_committedFirstRealDocumentLoad;
darin's avatar
darin committed
1256
1257
1258
1259

    // If a redirect was scheduled during a load, then stop the current load.
    // Otherwise when the current load transitions from a provisional to a 
    // committed state, pending redirects may be cancelled. 
mjs's avatar
mjs committed
1260
1261
1262
    if (duringLoad) {
        if (m_provisionalDocumentLoader)
            m_provisionalDocumentLoader->stopLoading();
darin's avatar
darin committed
1263
        stopLoading(true);   
mjs's avatar
mjs committed
1264
    }
darin's avatar
darin committed
1265
1266

    ScheduledRedirection::Type type = duringLoad
darin's avatar
darin committed
1267
        ? ScheduledRedirection::locationChangeDuringLoad : ScheduledRedirection::locationChange;
darin's avatar
darin committed
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
    scheduleRedirection(new ScheduledRedirection(type, url, referrer, lockHistory, wasUserGesture));
}

void FrameLoader::scheduleRefresh(bool wasUserGesture)
{
    // Handle a location change of a page with no document as a special case.
    // This may happen when a frame requests a refresh of another frame.
    bool duringLoad = !m_frame->document();
    
    // If a refresh was scheduled during a load, then stop the current load.
    // Otherwise when the current load transitions from a provisional to a 
    // committed state, pending redirects may be cancelled. 
    if (duringLoad)
        stopLoading(true);   

    ScheduledRedirection::Type type = duringLoad
darin's avatar
darin committed
1284
        ? ScheduledRedirection::locationChangeDuringLoad : ScheduledRedirection::locationChange;
darin's avatar
darin committed
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
    scheduleRedirection(new ScheduledRedirection(type, m_URL.url(), m_outgoingReferrer, true, wasUserGesture));
    m_cachePolicy = CachePolicyRefresh;
}

bool FrameLoader::isScheduledLocationChangePending() const
{
    if (!m_scheduledRedirection)
        return false;
    switch (m_scheduledRedirection->type) {
        case ScheduledRedirection::redirection:
            return false;
        case ScheduledRedirection::historyNavigation:
        case ScheduledRedirection::locationChange:
        case ScheduledRedirection::locationChangeDuringLoad:
            return true;
    }
    ASSERT_NOT_REACHED();
    return false;
}

void FrameLoader::scheduleHistoryNavigation(int steps)
{
    // navigation will always be allowed in the 0 steps case, which is OK because
    // that's supposed to force a reload.
    if (!canGoBackOrForward(steps)) {
        cancelRedirection();
        return;
    }

adele's avatar
adele committed
1314
1315
1316
    // If the steps to navigate is not zero (which needs to force a reload), and if the URL we're going to navigate 
    // to is the same as the current one, except for the fragment part, we don't need to schedule the navigation.
    if (steps != 0 && equalIgnoringRef(m_URL, historyURL(steps))) {
darin's avatar
darin committed
1317
1318
1319
1320
1321
1322
1323
        goBackOrForward(steps);
        return;
    }
    
    scheduleRedirection(new ScheduledRedirection(steps));
}

beidson's avatar
beidson committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
void FrameLoader::goBackOrForward(int distance)
{
    if (distance == 0)
        return;
        
    Page* page = m_frame->page();
    if (!page)
        return;
    BackForwardList* list = page->backForwardList();
    if (!list)
        return;
    
    HistoryItem* item = list->itemAtIndex(distance);
    if (!item) {
        if (distance > 0) {
            int forwardListCount = list->forwardListCount();
            if (forwardListCount > 0) 
                item = list->itemAtIndex(forwardListCount);
        } else {
            int backListCount = list->forwardListCount();
            if (backListCount > 0)
                item = list->itemAtIndex(-backListCount);
        }
    }
    if (item)
        page->goToItem(item, FrameLoadTypeIndexedBackForward);
}

darin's avatar
darin committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
void FrameLoader::redirectionTimerFired(Timer<FrameLoader>*)
{
    OwnPtr<ScheduledRedirection> redirection(m_scheduledRedirection.release());

    switch (redirection->type) {
        case ScheduledRedirection::redirection:
        case ScheduledRedirection::locationChange:
        case ScheduledRedirection::locationChangeDuringLoad:
            changeLocation(redirection->URL, redirection->referrer,
                redirection->lockHistory, redirection->wasUserGesture);
            return;
        case ScheduledRedirection::historyNavigation:
            if (redirection->historySteps == 0) {
                // Special case for go(0) from a frame -> reload only the frame
beidson's avatar
beidson committed
1366
                urlSelected(m_URL, "", 0, redirection->lockHistory, redirection->wasUserGesture);
darin's avatar
darin committed
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
                return;
            }
            // go(i!=0) from a frame navigates into the history of the frame only,
            // in both IE and NS (but not in Mozilla). We can't easily do that.
            goBackOrForward(redirection->historySteps);
            return;
    }
    ASSERT_NOT_REACHED();
}

String FrameLoader::encoding() const
{
    if (m_encodingWasChosenByUser && !m_encoding.isEmpty())
        return m_encoding;
    if (m_decoder && m_decoder->encoding().isValid())
        return m_decoder->encoding().name();
ggaren's avatar
ggaren committed
1383
1384
    Settings* settings = m_frame->settings();
    return settings ? settings->defaultTextEncodingName() : String();
darin's avatar
darin committed
1385
1386
1387
1388
}

bool FrameLoader::gotoAnchor(const String& name)
{
mjs's avatar
mjs committed
1389
    ASSERT(m_frame->document());
darin's avatar
darin committed
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431

    Node* anchorNode = m_frame->document()->getElementById(AtomicString(name));
    if (!anchorNode)
        anchorNode = m_frame->document()->anchors()->namedItem(name, !m_frame->document()->inCompatMode());

    m_frame->document()->setCSSTarget(anchorNode); // Setting to null will clear the current target.
  
    // Implement the rule that "" and "top" both mean top of page as in other browsers.
    if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
        return false;

    // We need to update the layout before scrolling, otherwise we could
    // really mess things up if an anchor scroll comes at a bad moment.
    if (m_frame->document()) {
        m_frame->document()->updateRendering();
        // Only do a layout if changes have occurred that make it necessary.      
        if (m_frame->view() && m_frame->document()->renderer() && m_frame->document()->renderer()->needsLayout())
            m_frame->view()->layout();
    }
  
    // Scroll nested layers and frames to reveal the anchor.
    // Align to the top and to the closest side (this matches other browsers).
    RenderObject* renderer;
    IntRect rect;
    if (!anchorNode)
        renderer = m_frame->document()->renderer(); // top of document
    else {
        renderer = anchorNode->renderer();
        rect = anchorNode->getRect();
    }
    if (renderer)
        renderer->enclosingLayer()->scrollRectToVisible(rect, RenderLayer::gAlignToEdgeIfNeeded, RenderLayer::gAlignTopAlways);

    return true;
}

bool FrameLoader::requestObject(RenderPart* renderer, const String& url, const AtomicString& frameName,
    const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
{
    if (url.isEmpty() && mimeType.isEmpty())
        return true;

darin's avatar
darin committed
1432
1433
1434
1435
1436
1437
1438
1439
#if USE(LOW_BANDWIDTH_DISPLAY)
    // don't care object during low bandwidth display
    if (frame()->document()->inLowBandwidthDisplay()) {
        m_needToSwitchOutLowBandwidthDisplay = true;
        return false;
    }
#endif

darin's avatar
darin committed
1440
1441
1442
1443
1444
    KURL completedURL;
    if (!url.isEmpty())
        completedURL = completeURL(url);

    bool useFallback;
darin's avatar
darin committed
1445
    if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback)) {
ggaren's avatar
ggaren committed
1446
        Settings* settings = m_frame->settings();
andersca's avatar
andersca committed
1447
1448
        if (!settings || !settings->arePluginsEnabled() || 
            (!settings->isJavaEnabled() && MimeTypeRegistry::isJavaAppletMIMEType(mimeType)))
1449
            return false;
darin's avatar
darin committed
1450
        return loadPlugin(renderer, completedURL, mimeType, paramNames, paramValues, useFallback);
1451
    }
darin's avatar
darin committed
1452
1453

    ASSERT(renderer->node()->hasTagName(objectTag) || renderer->node()->hasTagName(embedTag));
darin's avatar
darin committed
1454
1455
    HTMLPlugInElement* element = static_cast<HTMLPlugInElement*>(renderer->node());

darin's avatar
darin committed
1456
    AtomicString uniqueFrameName = m_frame->tree()->uniqueChildName(frameName);
darin's avatar
darin committed
1457
    element->setFrameName(uniqueFrameName);
darin's avatar
darin committed
1458
    
darin's avatar
darin committed
1459
1460
    // FIXME: OK to always make a new frame? When does the old frame get removed?
    return loadSubframe(element, completedURL, uniqueFrameName, m_outgoingReferrer);
darin's avatar
darin committed
1461
1462
}

darin's avatar
darin committed
1463
bool FrameLoader::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
darin's avatar
darin committed
1464
{
lars's avatar
lars committed
1465
    ObjectContentType objectType = m_client->objectContentType(url, mimeType);
darin's avatar
darin committed
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
    // If an object's content can't be handled and it has no fallback, let
    // it be handled as a plugin to show the broken plugin icon.
    useFallback = objectType == ObjectContentNone && hasFallback;
    return objectType == ObjectContentNone || objectType == ObjectContentPlugin;
}

bool FrameLoader::loadPlugin(RenderPart* renderer, const KURL& url, const String& mimeType, 
    const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
{
    Widget* widget = 0;

    if (renderer && !useFallback) {
        Element* pluginElement = 0;
        if (renderer->node() && renderer->node()->isElementNode())
            pluginElement = static_cast<Element*>(renderer->node());

kmccullo's avatar
kmccullo committed
1482
1483
        if (!canLoad(url, frame()->document())) {
            FrameLoader::reportLocalLoadFailed(frame()->page(), url.url());
lars's avatar
lars committed
1484
            return false;
kmccullo's avatar
kmccullo committed
1485
        }
lars's avatar
lars committed
1486
1487
1488

        widget = m_client->createPlugin(pluginElement, url, paramNames, paramValues, mimeType,
                                        m_frame->document()->isPluginDocument());
darin's avatar
darin committed
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
        if (widget) {
            renderer->setWidget(widget);
            m_containsPlugIns = true;
        }
    }

    checkEmitLoadEvent();
    return widget != 0;
}

void FrameLoader::clearRecordedFormValues()
{
    m_formAboutToBeSubmitted = 0;
    m_formValuesAboutToBeSubmitted.clear();
}

void FrameLoader::recordFormValue(const String& name, const String& value, PassRefPtr<HTMLFormElement> element)
{
    m_formAboutToBeSubmitted = element;
    m_formValuesAboutToBeSubmitted.set(name, value);
}

void FrameLoader::parentCompleted()
{
    if (m_scheduledRedirection && !m_redirectionTimer.isActive())
        startRedirectionTimer();
}

String FrameLoader::outgoingReferrer() const
{
    return m_outgoingReferrer;
}

Frame* FrameLoader::opener()
{
    return m_opener;
}

void FrameLoader::setOpener(Frame* opener)
{
    if <