FrameLoaderClientBlackBerry.cpp 52.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright (C) 2009, 2010, 2011, 2012 Research In Motion Limited. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "FrameLoaderClientBlackBerry.h"

22
#include "AboutData.h"
23
#include "AutofillManager.h"
24 25 26 27 28 29 30 31
#include "BackForwardController.h"
#include "BackForwardListImpl.h"
#include "BackingStoreClient.h"
#include "BackingStore_p.h"
#include "Chrome.h"
#include "ChromeClientBlackBerry.h"
#include "ClientExtension.h"
#include "CookieManager.h"
32 33 34
#include "CredentialBackingStore.h"
#include "CredentialManager.h"
#include "CredentialTransformData.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include "DumpRenderTreeClient.h"
#include "FrameNetworkingContextBlackBerry.h"
#include "FrameView.h"
#include "HTMLFormElement.h"
#include "HTMLHeadElement.h"
#include "HTMLLinkElement.h"
#include "HTMLMediaElement.h"
#include "HTMLMetaElement.h"
#include "HTMLNames.h"
#include "HTMLPlugInElement.h"
#include "HTTPParsers.h"
#include "HistoryItem.h"
#include "IconDatabase.h"
#include "Image.h"
#include "InputHandler.h"
#include "MIMETypeRegistry.h"
#include "NativeImageSkia.h"
#include "NetworkManager.h"
#include "NodeList.h"
#include "Page.h"
55
#include "PluginDatabase.h"
56 57
#include "PluginView.h"
#include "ProgressTracker.h"
58
#include "ProtectionSpace.h"
59
#include "ScopePointer.h"
60 61 62
#if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
#include "Settings.h"
#endif
63
#include "SharedBuffer.h"
64 65 66
#include "SkData.h"
#include "SkImageEncoder.h"
#include "SkStream.h"
67 68 69 70 71 72 73
#include "TextEncoding.h"
#include "TouchEventHandler.h"
#if ENABLE(WEBDOM)
#include "WebDOMDocument.h"
#endif
#include "WebPageClient.h"

74
#include <BlackBerryPlatformExecutableMessage.h>
75
#include <BlackBerryPlatformLog.h>
76
#include <BlackBerryPlatformMediaDocument.h>
77
#include <BlackBerryPlatformMessageClient.h>
78 79 80 81
#include <BlackBerryPlatformScreen.h>
#include <JavaScriptCore/APICast.h>
#include <network/FilterStream.h>
#include <network/NetworkRequest.h>
82
#include <wtf/text/Base64.h>
83 84 85 86

using WTF::String;
using namespace WebCore;
using namespace BlackBerry::WebKit;
87
using BlackBerry::Platform::NetworkRequest;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

// This was copied from file "WebKit/Source/WebKit/mac/Misc/WebKitErrors.h".
enum {
    WebKitErrorCannotShowMIMEType =                             100,
    WebKitErrorCannotShowURL =                                  101,
    WebKitErrorFrameLoadInterruptedByPolicyChange =             102,
    WebKitErrorCannotUseRestrictedPort =                        103,
    WebKitErrorCannotFindPlugIn =                               200,
    WebKitErrorCannotLoadPlugIn =                               201,
    WebKitErrorJavaUnavailable =                                202,
    WebKitErrorPluginWillHandleLoad =                           203
};

namespace WebCore {

FrameLoaderClientBlackBerry::FrameLoaderClientBlackBerry()
    : m_frame(0)
    , m_webPagePrivate(0)
    , m_sentReadyToRender(false)
    , m_pendingFragmentScrollPolicyFunction(0)
    , m_loadingErrorPage(false)
    , m_clientRedirectIsPending(false)
    , m_childFrameCreationSuppressed(false)
    , m_pluginView(0)
    , m_hasSentResponseToPlugin(false)
    , m_cancelLoadOnNextData(false)
114
    , m_wasProvisionalLoadTriggeredByUserGesture(true) // To avoid affecting the first load.
115 116 117 118 119 120 121 122 123
{
}

FrameLoaderClientBlackBerry::~FrameLoaderClientBlackBerry()
{
}

int FrameLoaderClientBlackBerry::playerId() const
{
124
    return m_webPagePrivate ? m_webPagePrivate->playerID() : 0;
125 126 127 128 129 130 131 132 133 134 135 136 137 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 165 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 200 201 202 203 204 205 206 207
}

bool FrameLoaderClientBlackBerry::cookiesEnabled() const
{
    return m_webPagePrivate->m_webSettings->areCookiesEnabled();
}

void FrameLoaderClientBlackBerry::dispatchDidAddBackForwardItem(HistoryItem* item) const
{
    // Inform the client that the back/forward list has changed.
    invalidateBackForwardList();
}

void FrameLoaderClientBlackBerry::dispatchDidRemoveBackForwardItem(HistoryItem* item) const
{
    invalidateBackForwardList();
}

void FrameLoaderClientBlackBerry::dispatchDidChangeBackForwardIndex() const
{
    invalidateBackForwardList();
}

void FrameLoaderClientBlackBerry::dispatchDidChangeLocationWithinPage()
{
    if (!isMainFrame())
        return;

    String url = m_frame->document()->url().string();
    String token = m_frame->loader()->documentLoader()->request().token();

    m_webPagePrivate->m_client->notifyLoadToAnchor(url.characters(), url.length(), token.characters(), token.length());
}

void FrameLoaderClientBlackBerry::dispatchDidPushStateWithinPage()
{
    // FIXME: As a workaround we abuse anchor navigation to achieve history push. See PR #119779 for more details.
    dispatchDidChangeLocationWithinPage();
}

void FrameLoaderClientBlackBerry::dispatchDidReplaceStateWithinPage()
{
    // FIXME: As a workaround we abuse anchor navigation to achieve history replace. See PR #119779 for more details.
    dispatchDidChangeLocationWithinPage();
}

void FrameLoaderClientBlackBerry::dispatchDidPopStateWithinPage()
{
    // Not needed.
}

void FrameLoaderClientBlackBerry::dispatchDidCancelClientRedirect()
{
    m_clientRedirectIsPending = false;
}

void FrameLoaderClientBlackBerry::dispatchWillPerformClientRedirect(const KURL&, double, double)
{
    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didDispatchWillPerformClientRedirect();

    m_clientRedirectIsPending = true;
}

void FrameLoaderClientBlackBerry::dispatchDecidePolicyForResponse(FramePolicyFunction function, const ResourceResponse& response, const ResourceRequest& request)
{
    // FIXME: What should we do for HTTP status code 204 and 205 and "application/zip"?
    PolicyAction policy = PolicyIgnore;

    if (contentDispositionType(response.httpHeaderField("Content-Disposition")) == ContentDispositionAttachment
        || request.forceDownload())
        policy = PolicyDownload;
    else if (canShowMIMEType(response.mimeType()))
        policy = PolicyUse;
    else if ((ResourceRequest::TargetIsMainFrame == request.targetType())
             && m_webPagePrivate->m_client->downloadAllowed(request.url().string().utf8().data()))
        policy = PolicyDownload;

    (m_frame->loader()->policyChecker()->*function)(policy);
}

void FrameLoaderClientBlackBerry::dispatchDecidePolicyForNavigationAction(FramePolicyFunction function, const NavigationAction& action, const ResourceRequest& request, PassRefPtr<FormState>)
{
208
    PolicyAction decision = PolicyIgnore;
209 210

    const KURL& url = request.url();
211 212 213 214 215 216
    if (!url.isNull()) {
        // Fragment scrolls on the same page should always be handled internally.
        // (Only count as a fragment scroll if we are scrolling to a #fragment url, not back to the top, and reloading
        // the same url is not a fragment scroll even if it has a #fragment.)
        const KURL& currentUrl = m_frame->document()->url();
        bool isFragmentScroll = url.hasFragmentIdentifier() && url != currentUrl && equalIgnoringFragmentIdentifier(currentUrl, url);
217 218
        decision = decidePolicyForExternalLoad(request, isFragmentScroll);

219
        // Let the client have a chance to say whether this navigation should be ignored or not.
220
        NetworkRequest platformRequest;
221
        request.initializePlatformRequest(platformRequest, cookiesEnabled());
222 223 224 225 226 227 228 229 230 231 232 233 234 235
        if (!platformRequest.getUrlRef().empty()) { // Some invalid URLs will result in empty URL in platformRequest
            if (platformRequest.getTargetType() == NetworkRequest::TargetIsUnknown)
                platformRequest.setTargetType(isMainFrame() ? NetworkRequest::TargetIsMainFrame : NetworkRequest::TargetIsSubframe);

            if (!m_webPagePrivate->m_client->acceptNavigationRequest(platformRequest, BlackBerry::Platform::NavigationType(action.type()))) {
                decision = PolicyIgnore;
                if (isMainFrame()) {
                    if (action.type() == NavigationTypeFormSubmitted || action.type() == NavigationTypeFormResubmitted)
                        m_frame->loader()->resetMultipleFormSubmissionProtection();

                    if (action.type() == NavigationTypeLinkClicked && url.hasFragmentIdentifier()) {
                        ResourceRequest emptyRequest;
                        m_frame->loader()->activeDocumentLoader()->setLastCheckedRequest(emptyRequest);
                    }
236 237
                }
            }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        }
    }

    // If we abort here, dispatchDidCancelClientRedirect will not be called.
    // So call it by hand.
    if (decision == PolicyIgnore)
        dispatchDidCancelClientRedirect();

    (m_frame->loader()->policyChecker()->*function)(decision);

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didDecidePolicyForNavigationAction(action, request);
}

void FrameLoaderClientBlackBerry::delayPolicyCheckUntilFragmentExists(const String& fragment, FramePolicyFunction function)
{
    ASSERT(isMainFrame());

    if (m_webPagePrivate->loadState() < WebPagePrivate::Finished && !m_frame->document()->findAnchor(fragment)) {
        // Tell the client we need more data, in case the fragment exists but is being held back.
        m_webPagePrivate->m_client->needMoreData();
        m_pendingFragmentScrollPolicyFunction = function;
        m_pendingFragmentScroll = fragment;
        return;
    }

    (m_frame->loader()->policyChecker()->*function)(PolicyUse);
}

void FrameLoaderClientBlackBerry::cancelPolicyCheck()
{
    m_pendingFragmentScrollPolicyFunction = 0;
    m_pendingFragmentScroll = String();
}

void FrameLoaderClientBlackBerry::doPendingFragmentScroll()
{
    if (m_pendingFragmentScroll.isNull())
        return;

    // Make sure to clear the pending members first to avoid recursion.
    String fragment = m_pendingFragmentScroll;
    m_pendingFragmentScroll = String();

    FramePolicyFunction function = m_pendingFragmentScrollPolicyFunction;
    m_pendingFragmentScrollPolicyFunction = 0;

    delayPolicyCheckUntilFragmentExists(fragment, function);
}

288
void FrameLoaderClientBlackBerry::dispatchDecidePolicyForNewWindowAction(FramePolicyFunction function, const NavigationAction&, const ResourceRequest& request, PassRefPtr<FormState>, const String& frameName)
289
{
290
    if (ScriptController::processingUserGesture() && !m_webPagePrivate->m_pluginMayOpenNewTab) {
291
        (m_frame->loader()->policyChecker()->*function)(PolicyIgnore);
292 293
        return;
    }
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 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

    // A new window can never be a fragment scroll.
    PolicyAction decision = decidePolicyForExternalLoad(request, false);
    (m_frame->loader()->policyChecker()->*function)(decision);
}

void FrameLoaderClientBlackBerry::committedLoad(DocumentLoader* loader, const char* data, int length)
{
    // The structure of this code may seem...a bit odd. It's structured with two checks on the state
    // of m_pluginView because it's actually receivedData that may cause the request to re-direct data
    // to a PluginView. This is because receivedData may decide to create a PluginDocument containing
    // a PluginView. The PluginView will request that the main resource for the frame be redirected
    // to the PluginView. So after receivedData has been called, this code needs to check whether
    // re-direction to a PluginView has been requested and pass the same data on to the PluginView.
    // Thereafter, all data will be re-directed to the PluginView; i.e., no additional data will go
    // to receivedData.

    if (!m_pluginView) {
        const String& textEncoding = loader->response().textEncodingName();
        receivedData(data, length, textEncoding);
    }

    if (m_pluginView) {
        if (!m_hasSentResponseToPlugin) {
            m_pluginView->didReceiveResponse(loader->response());
            m_hasSentResponseToPlugin = true;
        }

        if (!m_pluginView)
            return;

        m_pluginView->didReceiveData(data, length);
    }
}

PassRefPtr<Widget> FrameLoaderClientBlackBerry::createPlugin(const IntSize& pluginSize,
    HTMLPlugInElement* element, const KURL& url, const Vector<String>& paramNames,
    const Vector<String>& paramValues, const String& mimeTypeIn, bool loadManually)
{
    String mimeType(mimeTypeIn);
    if (mimeType.isEmpty()) {
        mimeType = MIMETypeRegistry::getMIMETypeForPath(url.path());
336
        mimeType = MIMETypeRegistry::getNormalizedMIMEType(mimeType);
337 338 339 340
        if (mimeType != "application/x-shockwave-flash")
            mimeType = mimeTypeIn;
    }

341
    if (PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType))
342 343 344 345 346 347 348 349 350 351 352 353
        return PluginView::create(m_frame, pluginSize, element, url, paramNames, paramValues, mimeType, loadManually);

    // If it's not the plugin type we support, try load directly from browser.
    if (m_frame->loader() && m_frame->loader()->subframeLoader() && !url.isNull())
        m_frame->loader()->subframeLoader()->requestFrame(element, url, String());

    return 0;
}

void FrameLoaderClientBlackBerry::redirectDataToPlugin(Widget* pluginWidget)
{
    m_pluginView = static_cast<PluginView*>(pluginWidget);
354 355
    if (pluginWidget)
        m_hasSentResponseToPlugin = false;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
}

void FrameLoaderClientBlackBerry::receivedData(const char* data, int length, const String& textEncoding)
{
    if (!m_frame)
        return;

    if (m_cancelLoadOnNextData) {
        m_frame->loader()->activeDocumentLoader()->stopLoading();
        m_frame->loader()->documentLoader()->writer()->end();
        m_cancelLoadOnNextData = false;
        return;
    }

    // Set the encoding. This only needs to be done once, but it's harmless to do it again later.
    String encoding = m_frame->loader()->documentLoader()->overrideEncoding();
    bool userChosen = !encoding.isNull();
    if (encoding.isNull())
        encoding = textEncoding;
    m_frame->loader()->documentLoader()->writer()->setEncoding(encoding, userChosen);
    m_frame->loader()->documentLoader()->writer()->addData(data, length);
}

379
void FrameLoaderClientBlackBerry::finishedLoading(DocumentLoader*)
380 381
{
    if (m_pluginView) {
382 383
        if (m_hasSentResponseToPlugin)
            m_pluginView->didFinishLoading();
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        m_pluginView = 0;
        m_hasSentResponseToPlugin = false;
    }
}

PassRefPtr<DocumentLoader> FrameLoaderClientBlackBerry::createDocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
{
    // Make a copy of the request with the token from the original request for this frame
    // (unless it already has a token, in which case the request came from the client).
    ResourceRequest newRequest(request);
    if (m_frame && m_frame->loader() && m_frame->loader()->documentLoader()) {
        const ResourceRequest& originalRequest = m_frame->loader()->documentLoader()->originalRequest();
        if (request.token().isNull() && !originalRequest.token().isNull())
            newRequest.setToken(originalRequest.token());
    }

400
    SubstituteData substituteDataLocal = substituteData;
401 402 403 404 405 406 407 408 409
    if (isMainFrame()) {
        String source;
        if (request.url().protocolIs("about")) {
            // The first 6 letters is "about:"
            String aboutWhat = request.url().string().substring(6);
            source = aboutData(aboutWhat);
        } else if (request.url().protocolIs("rtsp"))
            source = BlackBerry::Platform::mediaDocument(request.url().string().utf8().data()).c_str();

410 411 412 413 414 415 416
        if (!source.isEmpty()) {
            // Always ignore existing substitute data if any.
            WTF::RefPtr<SharedBuffer> buffer = SharedBuffer::create(source.is8Bit() ? reinterpret_cast<const char*>(source.characters8()) : source.latin1().data(), source.length());
            substituteDataLocal = SubstituteData(buffer, "text/html", "latin1", KURL());
        }
    }

417
    // FIXME: This should probably be shared.
418 419
    RefPtr<DocumentLoader> loader = DocumentLoader::create(newRequest, substituteDataLocal);
    if (substituteDataLocal.isValid())
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        loader->setDeferMainResourceDataLoad(false);
    return loader.release();
}

void FrameLoaderClientBlackBerry::frameLoaderDestroyed()
{
    delete this;
}

void FrameLoaderClientBlackBerry::transitionToCommittedForNewPage()
{
    m_cancelLoadOnNextData = false;

    // In Frame::createView, Frame's FrameView object is set to 0 and recreated.
    // This operation is not atomic, and an attempt to blit contents might happen
435
    // in the backing store from another thread (see BackingStorePrivate::blitVisibleContents method),
436 437
    // so we suspend and resume screen update to make sure we do not get a invalid FrameView
    // state.
438 439
    if (isMainFrame() && m_webPagePrivate->backingStoreClient())
        m_webPagePrivate->backingStoreClient()->backingStore()->d->suspendScreenAndBackingStoreUpdates();
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

    // We are navigating away from this document, so clean up any footprint we might have.
    if (m_frame->document())
        m_webPagePrivate->clearDocumentData(m_frame->document());

    Color backgroundColor(m_webPagePrivate->m_webSettings->backgroundColor());

    m_frame->createView(m_webPagePrivate->viewportSize(),      /* viewport */
                        backgroundColor,                       /* background color */
                        backgroundColor.hasAlpha(),            /* is transparent */
                        m_webPagePrivate->actualVisibleSize(), /* fixed reported size */
                        m_webPagePrivate->fixedLayoutSize(),   /* fixed layout size */
                        m_webPagePrivate->useFixedLayout(),    /* use fixed layout */
                        ScrollbarAlwaysOff,                    /* hor mode */
                        true,                                  /* lock the mode */
                        ScrollbarAlwaysOff,                    /* ver mode */
                        true);                                 /* lock the mode */

458 459 460
    if (isMainFrame() && m_webPagePrivate->backingStoreClient())
        m_webPagePrivate->backingStoreClient()->backingStore()->d->resumeScreenAndBackingStoreUpdates(BackingStore::None);

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    m_frame->view()->updateCanHaveScrollbars();

    if (isMainFrame()) {
        // Since the mainframe has a tiled backingstore request to receive all update
        // rects instead of the default which just sends update rects for currently
        // visible viewport.
        m_frame->view()->setPaintsEntireContents(true);
    }
}

String FrameLoaderClientBlackBerry::userAgent(const KURL&)
{
    return m_webPagePrivate->m_webSettings->userAgentString();
}

bool FrameLoaderClientBlackBerry::canHandleRequest(const ResourceRequest&) const
{
    // FIXME: Stub.
    return true;
}

bool FrameLoaderClientBlackBerry::canShowMIMEType(const String& mimeTypeIn) const
{
    // Get normalized type.
485
    String mimeType = MIMETypeRegistry::getNormalizedMIMEType(mimeTypeIn);
486 487

    // FIXME: Seems no other port checks empty MIME type in this function. Should we do that?
488 489
    return MIMETypeRegistry::canShowMIMEType(mimeType)
        || WebSettings::isSupportedObjectMIMEType(mimeType)
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        || (mimeType == "application/x-shockwave-flash");
}

bool FrameLoaderClientBlackBerry::canShowMIMETypeAsHTML(const String&) const
{
    // FIXME: Stub.
    return true;
}

bool FrameLoaderClientBlackBerry::isMainFrame() const
{
    return m_frame == m_webPagePrivate->m_mainFrame;
}

void FrameLoaderClientBlackBerry::dispatchDidStartProvisionalLoad()
{
    if (isMainFrame())
        m_webPagePrivate->setLoadState(WebPagePrivate::Provisional);

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didStartProvisionalLoadForFrame(m_frame);
511 512

    m_wasProvisionalLoadTriggeredByUserGesture = ScriptController::processingUserGesture();
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
}

void FrameLoaderClientBlackBerry::dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse& response)
{
    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didReceiveResponseForFrame(m_frame, response);
}

void FrameLoaderClientBlackBerry::dispatchDidReceiveTitle(const StringWithDirection& title)
{
    if (isMainFrame())
        m_webPagePrivate->m_client->setPageTitle(title.string().characters(), title.string().length());

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didReceiveTitleForFrame(title.string(), m_frame);
}

void FrameLoaderClientBlackBerry::setTitle(const StringWithDirection& /*title*/, const KURL& /*url*/)
{
    // Used by Apple WebKit to update the title of an existing history item.
    // QtWebKit doesn't accomodate this on history items. If it ever does,
    // it should be privateBrowsing-aware. For now, we are just passing
    // globalhistory layout tests.
    // FIXME: Use direction of title.
    notImplemented();
}

void FrameLoaderClientBlackBerry::dispatchDidCommitLoad()
{
    // FIXME: Do we need to find a replacement for m_frame->document()->setExtraLayoutDelay(250);?

    if (isMainFrame()) {
        m_webPagePrivate->setLoadState(WebPagePrivate::Committed);

        String originalUrl = m_frame->loader()->documentLoader()->originalRequest().url().string();
        String url = m_frame->loader()->documentLoader()->request().url().string();
        String token = m_frame->loader()->documentLoader()->request().token();

        // Notify the client that the load succeeded or failed (if it failed, this
        // is actually committing the error page, which was set through
        // SubstituteData in dispatchDidFailProvisionalLoad).
        if (m_loadingErrorPage) {
            m_loadingErrorPage = false;
556 557
            if (HistoryItem* item = m_frame->loader()->history()->currentItem())
                item->viewState().shouldSaveViewState = false;
558 559 560 561 562 563 564
            m_webPagePrivate->m_client->notifyLoadFailedBeforeCommit(
                originalUrl.characters(), originalUrl.length(),
                    url.characters(), url.length(), token.characters(), token.length());
        } else {
            m_webPagePrivate->m_client->notifyLoadCommitted(
                originalUrl.characters(), originalUrl.length(),
                    url.characters(), url.length(), token.characters(), token.length());
565 566 567
            HistoryItem* currentItem = m_frame->loader()->history()->currentItem();
            if (currentItem && currentItem->isInPageCache())
                dispatchDidReceiveIcon();
568 569 570 571 572 573 574 575 576
        }
    }

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didCommitLoadForFrame(m_frame);
}

void FrameLoaderClientBlackBerry::dispatchDidHandleOnloadEvents()
{
577
    m_webPagePrivate->m_client->notifyDocumentOnLoad(isMainFrame());
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 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 631 632 633 634 635 636 637 638 639 640 641 642 643
    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didHandleOnloadEventsForFrame(m_frame);
}

void FrameLoaderClientBlackBerry::dispatchDidFinishLoad()
{
    didFinishOrFailLoading(ResourceError());

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didFinishLoadForFrame(m_frame);

    if (!isMainFrame() || m_webPagePrivate->m_webSettings->isEmailMode()
        || !m_frame->document() || !m_frame->document()->head())
        return;

    HTMLHeadElement* headElement = m_frame->document()->head();
    // FIXME: Handle NOSCRIPT special case?

    // Process document metadata.
    RefPtr<NodeList> nodeList = headElement->getElementsByTagName(HTMLNames::metaTag.localName());
    unsigned int size = nodeList->length();
    ScopeArray<WebString> headers;

    // This may allocate more space than needed since not all meta elements will be http-equiv.
    headers.reset(new WebString[2 * size]);
    unsigned headersLength = 0;

    for (unsigned i = 0; i < size; ++i) {
        HTMLMetaElement* metaElement = static_cast<HTMLMetaElement*>(nodeList->item(i));
        if (WTF::equalIgnoringCase(metaElement->name(), "apple-mobile-web-app-capable")
            && WTF::equalIgnoringCase(metaElement->content().stripWhiteSpace(), "yes"))
            m_webPagePrivate->m_client->setWebAppCapable();
        else {
            String httpEquiv = metaElement->httpEquiv().stripWhiteSpace();
            String content = metaElement->content().stripWhiteSpace();

            if (!httpEquiv.isNull() && !content.isNull()) {
                headers[headersLength++] = httpEquiv;
                headers[headersLength++] = content;
            }
        }
    }

    if (headersLength > 0)
        m_webPagePrivate->m_client->setMetaHeaders(headers, headersLength);

    nodeList = headElement->getElementsByTagName(HTMLNames::linkTag.localName());
    size = nodeList->length();

    for (unsigned i = 0; i < size; ++i) {
        HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(nodeList->item(i));
        String href = linkElement->href().string();
        if (!href.isEmpty()) {
            String title = linkElement->title();

            if (WTF::equalIgnoringCase(linkElement->rel(), "apple-touch-icon"))
                m_webPagePrivate->m_client->setLargeIcon(href.latin1().data());
            else if (WTF::equalIgnoringCase(linkElement->rel(), "search")) {
                if (WTF::equalIgnoringCase(linkElement->type(), "application/opensearchdescription+xml"))
                    m_webPagePrivate->m_client->setSearchProviderDetails(title.utf8().data(), href.utf8().data());
            } else if (WTF::equalIgnoringCase(linkElement->rel(), "alternate")
                && (WTF::equalIgnoringCase(linkElement->type(), "application/rss+xml")
                || WTF::equalIgnoringCase(linkElement->type(), "application/atom+xml")))
                m_webPagePrivate->m_client->setAlternateFeedDetails(title.utf8().data(), href.utf8().data());
        }
    }
644 645

#if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
646 647
    if (m_webPagePrivate->m_webSettings->isCredentialAutofillEnabled()
        && !m_webPagePrivate->m_webSettings->isPrivateBrowsingEnabled())
648 649
        credentialManager().autofillPasswordForms(m_frame->document()->forms());
#endif
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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
}

void FrameLoaderClientBlackBerry::dispatchDidFinishDocumentLoad()
{
    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didFinishDocumentLoadForFrame(m_frame);
    notImplemented();
}

void FrameLoaderClientBlackBerry::dispatchDidFailLoad(const ResourceError& error)
{
    didFinishOrFailLoading(error);
    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didFailLoadForFrame(m_frame);
}

void FrameLoaderClientBlackBerry::didFinishOrFailLoading(const ResourceError& error)
{
    // FIXME: Do we need to find a replacement for m_frame->document()->setExtraLayoutDelay(0);?

    // If we have finished loading a page through history navigation, any
    // attempt to go back to that page through an automatic redirect should be
    // denied to avoid redirect loops. So save the history navigation urls to
    // check later. (If this was not a history navigation,
    // m_historyNavigationSourceURLs will be empty, and we should save that
    // too.)
    m_redirectURLsToSkipDueToHistoryNavigation.swap(m_historyNavigationSourceURLs);

    // History navigation is finished so clear the history navigation url.
    m_historyNavigationSourceURLs.clear();

    if (isMainFrame()) {
        m_loadError = error;
        m_webPagePrivate->setLoadState(error.isNull() ? WebPagePrivate::Finished : WebPagePrivate::Failed);
    }
}

void FrameLoaderClientBlackBerry::dispatchDidFailProvisionalLoad(const ResourceError& error)
{
    if (isMainFrame()) {
        m_loadError = error;
        m_webPagePrivate->setLoadState(WebPagePrivate::Failed);

        if (error.domain() == ResourceError::platformErrorDomain
                && (error.errorCode() == BlackBerry::Platform::FilterStream::StatusErrorAlreadyHandled)) {
            // Error has already been displayed by client.
            return;
        }

        if (error.domain().isEmpty() && !error.errorCode() && error.failingURL().isEmpty() && error.localizedDescription().isEmpty()) {
            // Don't try to display empty errors returned from the unimplemented error functions in FrameLoaderClientBlackBerry - there's nothing to display anyway.
            return;
        }
    }

    if (m_webPagePrivate->m_dumpRenderTree)
        m_webPagePrivate->m_dumpRenderTree->didFailProvisionalLoadForFrame(m_frame);

    if (!isMainFrame())
        return;

    String errorPage = m_webPagePrivate->m_client->getErrorPage(error.errorCode()
            , error.localizedDescription().isEmpty() ? "" : error.localizedDescription().utf8().data()
            , error.failingURL().isEmpty() ? "" : error.failingURL().utf8().data());

    // Make sure we're still in the provisionalLoad state - getErrorPage runs a
    // nested event loop while it's waiting for client resources to load so
    // there's a small window for the user to hit stop.
    if (m_frame->loader()->provisionalDocumentLoader()) {
        SubstituteData errorData(utf8Buffer(errorPage), "text/html", "utf-8", KURL(KURL(), error.failingURL()));

        ResourceRequest originalRequest = m_frame->loader()->provisionalDocumentLoader()->originalRequest();

        // Loading using SubstituteData will replace the original request with our
        // error data. This must be done within dispatchDidFailProvisionalLoad,
        // and do NOT call stopAllLoaders first, because the loader checks the
        // provisionalDocumentLoader to decide the load type; if called any other
        // way, the error page is added to the end of the history instead of
        // replacing the failed load.
        //
        // If this comes from a back/forward navigation, we need to save the current viewstate
        // to original historyitem, and prevent the restore of view state to the error page.
        if (isBackForwardLoadType(m_frame->loader()->loadType())) {
            m_frame->loader()->history()->saveScrollPositionAndViewStateToItem(m_frame->loader()->history()->currentItem());
            ASSERT(m_frame->loader()->history()->provisionalItem());
            m_frame->loader()->history()->provisionalItem()->viewState().shouldSaveViewState = false;
        }
        m_loadingErrorPage = true;
        m_frame->loader()->load(originalRequest, errorData, false);
    }
}

742
void FrameLoaderClientBlackBerry::dispatchWillSubmitForm(FramePolicyFunction function, PassRefPtr<FormState>)
743 744 745 746 747
{
    // FIXME: Stub.
    (m_frame->loader()->policyChecker()->*function)(PolicyUse);
}

748
void FrameLoaderClientBlackBerry::dispatchWillSendSubmitEvent(PassRefPtr<FormState> prpFormState)
749
{
750
    if (!m_webPagePrivate->m_webSettings->isPrivateBrowsingEnabled()) {
751 752
        if (m_webPagePrivate->m_webSettings->isFormAutofillEnabled())
            m_webPagePrivate->m_autofillManager->saveTextFields(prpFormState->form());
753
#if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
754 755
        if (m_webPagePrivate->m_webSettings->isCredentialAutofillEnabled())
            credentialManager().saveCredentialIfConfirmed(m_webPagePrivate, CredentialTransformData(prpFormState->form()));
756
#endif
757
    }
758 759
}

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
PassRefPtr<Frame> FrameLoaderClientBlackBerry::createFrame(const KURL& url, const String& name
    , HTMLFrameOwnerElement* ownerElement, const String& referrer, bool allowsScrolling, int marginWidth, int marginHeight)
{
    if (!m_webPagePrivate)
        return 0;

    if (m_childFrameCreationSuppressed)
        return 0;

    FrameLoaderClientBlackBerry* frameLoaderClient = new FrameLoaderClientBlackBerry();
    RefPtr<Frame> childFrame = Frame::create(m_frame->page(), ownerElement, frameLoaderClient);
    frameLoaderClient->setFrame(childFrame.get(), m_webPagePrivate);

    // Initialize FrameView.
    RefPtr<FrameView> frameView = FrameView::create(childFrame.get());
    childFrame->setView(frameView.get());
    if (!allowsScrolling)
        frameView->setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
    if (marginWidth != -1)
        frameView->setMarginWidth(marginWidth);
    if (marginHeight != -1)
        frameView->setMarginHeight(marginHeight);

    childFrame->tree()->setName(name);
    m_frame->tree()->appendChild(childFrame);
    childFrame->init();

    if (!childFrame->tree()->parent())
        return 0;

    m_frame->loader()->loadURLIntoChildFrame(url, referrer, childFrame.get());

    if (!childFrame->tree()->parent())
        return 0;

    return childFrame.release();
}

ObjectContentType FrameLoaderClientBlackBerry::objectContentType(const KURL& url, const String& mimeTypeIn, bool shouldPreferPlugInsForImages)
{
    String mimeType = mimeTypeIn;
    if (mimeType.isEmpty())
        mimeType = MIMETypeRegistry::getMIMETypeForPath(url.path());

    // Get mapped type.
805
    mimeType = MIMETypeRegistry::getNormalizedMIMEType(mimeType);
806 807 808 809 810 811 812 813 814 815 816 817 818

    ObjectContentType defaultType = FrameLoader::defaultObjectContentType(url, mimeType, shouldPreferPlugInsForImages);
    if (defaultType != ObjectContentNone)
        return defaultType;

    if (WebSettings::isSupportedObjectMIMEType(mimeType))
        return ObjectContentOtherPlugin;

    return ObjectContentNone;
}

void FrameLoaderClientBlackBerry::dispatchWillClose()
{
819
    m_webPagePrivate->frameUnloaded(m_frame);
820 821 822 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
}

void FrameLoaderClientBlackBerry::setMainDocumentError(DocumentLoader*, const ResourceError& error)
{
    if (!m_pluginView)
        return;

    m_pluginView->didFail(error);
    m_pluginView = 0;
    m_hasSentResponseToPlugin = false;
}

void FrameLoaderClientBlackBerry::postProgressStartedNotification()
{
    if (!isMainFrame())
        return;

    // New load started, so clear the error.
    m_loadError = ResourceError();
    m_sentReadyToRender = false;
    m_webPagePrivate->m_client->notifyLoadStarted();
}

void FrameLoaderClientBlackBerry::postProgressEstimateChangedNotification()
{
    if (!isMainFrame() || !m_frame->page())
        return;

    m_webPagePrivate->m_client->notifyLoadProgress(m_frame->page()->progress()->estimatedProgress() * 100);
}

851
void FrameLoaderClientBlackBerry::dispatchDidLayout(LayoutMilestones milestones)
852 853 854 855
{
    if (!isMainFrame())
        return;

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    if (milestones & DidFirstVisuallyNonEmptyLayout) {
        BlackBerry::Platform::log(BlackBerry::Platform::LogLevelInfo, "dispatchDidFirstVisuallyNonEmptyLayout");

        readyToRender(true);

        // For FrameLoadTypeSame or FrameLoadTypeStandard load, the layout timer can be fired which can call
        // dispatchDidFirstVisuallyNonEmptyLayout() after the load Finished state, in which case the web page
        // will have no chance to zoom to initial scale. So we should give it a chance, otherwise the scale of
        // the web page can be incorrect.
        FrameLoadType frameLoadType = m_frame->loader()->loadType();
        if (m_webPagePrivate->loadState() == WebPagePrivate::Finished && (frameLoadType == FrameLoadTypeSame || frameLoadType == FrameLoadTypeStandard))
            m_webPagePrivate->setShouldZoomToInitialScaleAfterLoadFinished(true);

        if (m_webPagePrivate->shouldZoomToInitialScaleOnLoad()) {
            BackingStorePrivate* backingStorePrivate = m_webPagePrivate->m_backingStore->d;
            m_webPagePrivate->zoomToInitialScaleOnLoad(); // Set the proper zoom level first.
            backingStorePrivate->clearVisibleZoom(); // Clear the visible zoom since we're explicitly rendering+blitting below.
            if (backingStorePrivate->renderVisibleContents()) {
                if (!backingStorePrivate->shouldDirectRenderingToWindow())
                    backingStorePrivate->blitVisibleContents();
                m_webPagePrivate->m_client->notifyContentRendered(backingStorePrivate->visibleContentsRect());
            }
878
        }
879

880 881
        m_webPagePrivate->m_client->notifyFirstVisuallyNonEmptyLayout();
    }
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
}

void FrameLoaderClientBlackBerry::postProgressFinishedNotification()
{
    if (!isMainFrame())
        return;

    // Empty pages will never have called
    // dispatchDidFirstVisuallyNonEmptyLayout, since they're visually empty, so
    // we may need to call readyToRender now.
    readyToRender(false);

    // FIXME: Send up a real status code.
    m_webPagePrivate->m_client->notifyLoadFinished(m_loadError.isNull() ? 0 : -1);

    // Notify plugins that are waiting for the page to fully load before starting that
    // the load has completed.
    m_webPagePrivate->notifyPageOnLoad();
}

void FrameLoaderClientBlackBerry::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
{
    if (world != mainThreadNormalWorld())
        return;

    // Provide the extension object first in case the client or others want to use it.
908 909
    if (m_webPagePrivate->m_enableQnxJavaScriptObject)
        attachExtensionObjectToFrame(m_frame, m_webPagePrivate->m_client);
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

    m_webPagePrivate->m_client->notifyWindowObjectCleared();

    if (m_webPagePrivate->m_dumpRenderTree) {
        JSGlobalContextRef context = toGlobalRef(m_frame->script()->globalObject(mainThreadNormalWorld())->globalExec());
        JSObjectRef windowObject = toRef(m_frame->script()->globalObject(mainThreadNormalWorld()));
        ASSERT(windowObject);
        m_webPagePrivate->m_dumpRenderTree->didClearWindowObjectInWorld(world, context, windowObject);
    }
}

bool FrameLoaderClientBlackBerry::shouldGoToHistoryItem(HistoryItem*) const
{
    return true;
}

bool FrameLoaderClientBlackBerry::shouldStopLoadingForHistoryItem(HistoryItem*) const
{
    return true;
}

void FrameLoaderClientBlackBerry::invalidateBackForwardList() const
{
    notifyBackForwardListChanged();
}

void FrameLoaderClientBlackBerry::notifyBackForwardListChanged() const
{
    BackForwardListImpl* backForwardList = static_cast<BackForwardListImpl*>(m_webPagePrivate->m_page->backForward()->client());
    ASSERT(backForwardList);

    unsigned listSize = backForwardList->entries().size();
    unsigned currentIndex = backForwardList->backListCount();
    m_webPagePrivate->m_client->resetBackForwardList(listSize, currentIndex);
}

Frame* FrameLoaderClientBlackBerry::dispatchCreatePage(const NavigationAction& navigation)
{
    WebPage* webPage = m_webPagePrivate->m_client->createWindow(0, 0, -1, -1, WebPageClient::FlagWindowDefault, navigation.url().string(), WebString());
    if (!webPage)
        return 0;

    return webPage->d->m_page->mainFrame();
}

void FrameLoaderClientBlackBerry::detachedFromParent2()
{
    if (m_frame->document())
        m_webPagePrivate->clearDocumentData(m_frame->document());

960
    m_webPagePrivate->frameUnloaded(m_frame);
961 962 963 964 965 966 967 968 969
    m_webPagePrivate->m_client->notifyFrameDetached(m_frame);
}

void FrameLoaderClientBlackBerry::dispatchWillSendRequest(DocumentLoader* docLoader, long unsigned int, ResourceRequest& request, const ResourceResponse&)
{
    // If the request is being loaded by the provisional document loader, then
    // it is a new top level request which has not been commited.
    bool isMainResourceLoad = docLoader && docLoader == docLoader->frameLoader()->provisionalDocumentLoader();

970 971 972 973
    // TargetType for subresource loads should have been set in CachedResource::load().
    if (isMainResourceLoad && request.targetType() == ResourceRequest::TargetIsUnspecified)
        request.setTargetType(isMainFrame() ? ResourceRequest::TargetIsMainFrame : ResourceRequest::TargetIsSubframe);

974
    // Any processing which is done for all loads (both main and subresource) should go here.
975
    NetworkRequest platformRequest;
976
    request.initializePlatformRequest(platformRequest, cookiesEnabled());
977
    m_webPagePrivate->m_client->populateCustomHeaders(platformRequest);
978 979
    const NetworkRequest::HeaderList& headerLists = platformRequest.getHeaderListRef();
    for (NetworkRequest::HeaderList::const_iterator it = headerLists.begin(); it != headerLists.end(); ++it) {
980 981
        std::string headerString = it->first;
        std::string headerValueString = it->second;
982
        request.setHTTPHeaderField(String::fromUTF8WithLatin1Fallback(headerString.data(), headerString.length()), String::fromUTF8WithLatin1Fallback(headerValueString.data(), headerValueString.length()));
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    }
    if (!isMainResourceLoad) {
        // Do nothing for now.
        // Any processing which is done only for subresources should go here.
        return;
    }

    // All processing beyond this point is done only for main resource loads.

    if (m_clientRedirectIsPending && isMainFrame()) {
        String originalUrl = m_frame->document()->url().string();
        String finalUrl = request.url().string();

        m_webPagePrivate->m_client->notifyClientRedirect(originalUrl.characters(), originalUrl.length(),
            finalUrl.characters(), finalUrl.length());
    }

    FrameLoader* loader = m_frame->loader();
    ASSERT(loader);
    if (isBackForwardLoadType(loader->loadType())) {
        // Do not use the passed DocumentLoader because it is the loader that
        // will be used for the new request (the DESTINATION of the history
        // navigation - we want to use the current DocumentLoader to record the
        // SOURCE).
        DocumentLoader* docLoader = m_frame->loader()->documentLoader();
        ASSERT(docLoader);
        m_historyNavigationSourceURLs.add(docLoader->url());
        m_historyNavigationSourceURLs.add(docLoader->originalURL());
    }
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
bool FrameLoaderClientBlackBerry::shouldUseCredentialStorage(DocumentLoader* loader, long unsigned identifier)
{
#if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
    if (m_frame->page()->settings()->privateBrowsingEnabled())
        return false;
    return true;
#else
    return false;
#endif
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
void FrameLoaderClientBlackBerry::loadIconExternally(const String& originalPageUrl, const String& finalPageUrl, const String& iconUrl)
{
    m_webPagePrivate->m_client->setIconForUrl(originalPageUrl.utf8().data(), finalPageUrl.utf8().data(), iconUrl.utf8().data());
}

void FrameLoaderClientBlackBerry::saveViewStateToItem(HistoryItem* item)
{
    if (!isMainFrame())
        return;

    ASSERT(item);
    HistoryItemViewState& viewState = item->viewState();
1037
    if (viewState.shouldSaveViewState) {
1038 1039 1040 1041
        viewState.orientation = m_webPagePrivate->mainFrame()->orientation();
        viewState.isZoomToFitScale = m_webPagePrivate->currentScale() == m_webPagePrivate->zoomToFitScale();
        viewState.scale = m_webPagePrivate->currentScale();
        viewState.shouldReflowBlock = m_webPagePrivate->m_shouldReflowBlock;
1042 1043 1044
        viewState.minimumScale = m_webPagePrivate->m_minimumScale;
        viewState.maximumScale = m_webPagePrivate->m_maximumScale;
        viewState.isUserScalable = m_webPagePrivate->m_userScalable;
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    }
}

void FrameLoaderClientBlackBerry::restoreViewState()
{
    if (!isMainFrame())
        return;

    HistoryItem* currentItem = m_frame->loader()->history()->currentItem();
    ASSERT(currentItem);

    if (!currentItem)
        return;

1059 1060 1061
    HistoryItemViewState& viewState = currentItem->viewState();
    if (!viewState.shouldSaveViewState)
        return;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    // WebPagePrivate is messing up FrameView::wasScrolledByUser() by sending
    // scroll events that look like they were user generated all the time.
    //
    // Even if the user did not scroll, FrameView is gonna think they did.
    // So we use our own bookkeeping code to keep track of whether we were
    // actually scrolled by the user during load.
    //
    // If the user did scroll though, all are going to be in agreement about
    // that, and the worst thing that could happen is that
    // HistoryController::restoreScrollPositionAndViewState calls
    // setScrollPosition with the the same point, which is a NOOP.
    IntSize contentsSize = currentItem->contentsSize();
    IntPoint scrollPosition = currentItem->scrollPoint();
    if (m_webPagePrivate->m_userPerformedManualScroll)
        scrollPosition = m_webPagePrivate->scrollPosition();

    // We need to reset this variable after the view state has been restored.
    m_webPagePrivate->m_didRestoreFromPageCache = false;

1081 1082 1083 1084
    // Restore the meta first.
    m_webPagePrivate->m_minimumScale = viewState.minimumScale;
    m_webPagePrivate->m_maximumScale = viewState.maximumScale;
    m_webPagePrivate->m_userScalable = viewState.isUserScalable;
1085

1086 1087
    // Also, try to keep the users zoom if any.
    double scale = viewState.scale;
1088 1089 1090 1091 1092 1093 1094

    // If it was zoomToFitScale use the new zoomToFitScale because
    // the new one may be different to the old one due to contents
    // size change (e.g. after reloaded).
    if (viewState.isZoomToFitScale)
        scale = m_webPagePrivate->zoomToFitScale();

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    bool shouldReflowBlock = viewState.shouldReflowBlock;
    if (m_webPagePrivate->m_userPerformedManualZoom) {
        scale = m_webPagePrivate->currentScale();
        shouldReflowBlock = m_webPagePrivate->m_shouldReflowBlock;
    }

    bool scrollChanged = scrollPosition != m_webPagePrivate->scrollPosition();
    bool scaleChanged = scale != m_webPagePrivate->currentScale();
    bool reflowChanged = shouldReflowBlock != m_webPagePrivate->m_shouldReflowBlock;
    bool orientationChanged = viewState.orientation % 180 != m_webPagePrivate->mainFrame()->orientation() % 180;

    if (!scrollChanged && !scaleChanged && !reflowChanged && !orientationChanged)
        return;

    // When rotate happens, only zoom when previous page was zoomToFitScale, otherwise keep old scale.
    if (orientationChanged && viewState.isZoomToFitScale)
1111
        scale = BlackBerry::Platform::Graphics::Screen::primaryScreen()->width() * scale / static_cast<double>(BlackBerry::Platform::Graphics::Screen::primaryScreen()->height());
1112

1113 1114 1115 1116
    // Don't flash checkerboard before WebPagePrivate::restoreHistoryViewState() finished.
    // This call will be balanced by BackingStorePrivate::resumeScreenAndBackingStoreUpdates() in WebPagePrivate::restoreHistoryViewState().
    m_webPagePrivate->m_backingStore->d->suspendScreenAndBackingStoreUpdates();

1117 1118 1119
    // It is not safe to render the page at this point. So we post a message instead. Messages have higher priority than timers.
    BlackBerry::Platform::webKitThreadMessageClient()->dispatchMessage(BlackBerry::Platform::createMethodCallMessage(
        &WebPagePrivate::restoreHistoryViewState, m_webPagePrivate, contentsSize, scrollPosition, scale, viewState.shouldReflowBlock));
1120 1121 1122 1123
}

PolicyAction FrameLoaderClientBlackBerry::decidePolicyForExternalLoad(const ResourceRequest& request, bool isFragmentScroll)
{
1124 1125 1126 1127 1128
#if 0
    // FIXME: Enable these commented out when WebPageClient::handleStringPattern is implemented
    // and exposed to client. Before that, don't return PolicyIgnore so we can continue to
    // create new window and get to dispatchDecidePolicyForNavigationAction() where the client
    // is given a chance to decide how to handle patterns such as 'mailto:'.
1129 1130 1131 1132 1133 1134
    const KURL& url = request.url();
    String pattern = m_webPagePrivate->findPatternStringForUrl(url);
    if (!pattern.isEmpty()) {
        m_webPagePrivate->m_client->handleStringPattern(pattern.characters(), pattern.length());
        return PolicyIgnore;
    }
1135
#endif
1136 1137 1138 1139 1140

    if (m_webPagePrivate->m_webSettings->areLinksHandledExternally()
            && isMainFrame()
            && !request.mustHandleInternally()
            && !isFragmentScroll) {
1141
        NetworkRequest platformRequest;
1142
        request.initializePlatformRequest(platformRequest, cookiesEnabled());
1143 1144 1145
        if (platformRequest.getTargetType() == NetworkRequest::TargetIsUnknown)
            platformRequest.setTargetType(isMainFrame() ? NetworkRequest::TargetIsMainFrame : NetworkRequest::TargetIsSubframe);

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        m_webPagePrivate->m_client->handleExternalLink(platformRequest, request.anchorText().characters(), request.anchorText().length(), m_clientRedirectIsPending);
        return PolicyIgnore;
    }

    return PolicyUse;
}

void FrameLoaderClientBlackBerry::willDeferLoading()
{
    if (!isMainFrame())
        return;

    m_webPagePrivate->willDeferLoading();
}

void FrameLoaderClientBlackBerry::didResumeLoading()
{
    if (!isMainFrame())
        return;

    m_webPagePrivate->didResumeLoading();
}

void FrameLoaderClientBlackBerry::readyToRender(bool pageIsVisuallyNonEmpty)
{
    // Only send the notification once.
    if (!m_sentReadyToRender) {
        m_webPagePrivate->m_client->notifyLoadReadyToRender(pageIsVisuallyNonEmpty);
        m_sentReadyToRender = true;
    }
}

PassRefPtr<FrameNetworkingContext> FrameLoaderClientBlackBerry::createNetworkingContext()
{
    return FrameNetworkingContextBlackBerry::create(m_frame);
}

1183
void FrameLoaderClientBlackBerry::startDownload(const ResourceRequest& request, const String& suggestedName)
1184
{
1185
    m_webPagePrivate->load(request.url().string().utf8().data(), 0, "GET", NetworkRequest::UseProtocolCachePolicy, 0, 0, 0, 0, false, false, true, "", suggestedName.utf8().data());
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
}

void FrameLoaderClientBlackBerry::download(ResourceHandle* handle, const ResourceRequest&, const ResourceRequest&, const ResourceResponse& r)
{
    BlackBerry::Platform::FilterStream* stream = NetworkManager::instance()->streamForHandle(handle);
    ASSERT(stream);

    m_webPagePrivate->m_client->downloadRequested(stream, r.suggestedFilename());
}

void FrameLoaderClientBlackBerry::dispatchDidReceiveIcon()
{
    String url = m_frame->document()->url().string();
1199
    NativeImageSkia* bitmap = iconDatabase().synchronousNativeIconForPageURL(url, IntSize(10, 10));
1200
    if (!bitmap || bitmap->bitmap().empty())
1201
        return;
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    SkAutoLockPixels locker(bitmap->bitmap());
    SkDynamicMemoryWStream writer;
    if (!SkImageEncoder::EncodeStream(&writer, bitmap->bitmap(), SkImageEncoder::kPNG_Type, 100)) {
        BlackBerry::Platform::logAlways(BlackBerry::Platform::LogLevelInfo, "Failed to convert the icon to PNG format.");
        return;
    }
    SkData* data = writer.copyToData();
    Vector<char> out;
    base64Encode(static_cast<const char*>(data->data()), data->size(), out);
    out.append('\0'); // Make it null-terminated.
1213
    String iconUrl = iconDatabase().synchronousIconURLForPageURL(url);
1214 1215
    m_webPagePrivate->m_client->setFavicon(out.data(), iconUrl.utf8().data());
    data->unref();
1216 1217 1218 1219
}

bool FrameLoaderClientBlackBerry::canCachePage() const
{
1220
    // We won't cache pages containing multipart with "multipart/x-mixed-replace".
1221 1222 1223 1224 1225 1226 1227
    ASSERT(m_frame->loader()->documentLoader());
    const ResponseVector& responses = m_frame->loader()->documentLoader()->responses();
    size_t count = responses.size();
    for (size_t i = 0; i < count; i++) {
        if (responses[i].isMultipartPayload())
            return false;
    }
1228 1229 1230
    return true;
}

1231 1232 1233 1234 1235 1236 1237
void FrameLoaderClientBlackBerry::didSaveToPageCache()
{
    // When page goes into PageCache, clean up any possible
    // document data cache we might have.
    m_webPagePrivate->clearDocumentData(m_frame->document());
}

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
void FrameLoaderClientBlackBerry::provisionalLoadStarted()
{
    // We would like to hide the virtual keyboard before it navigates to another page
    // so that the scroll offset without keyboard shown will be saved in the history item.
    // Then when the user navigates back, it will scroll to the right position.
    if (isMainFrame())
        m_webPagePrivate->showVirtualKeyboard(false);
}

// We don't need to provide the error message string, that will be handled in BrowserErrorPage according to the error code.
ResourceError FrameLoaderClientBlackBerry::cannotShowURLError(const ResourceRequest& request)
{
    // FIXME: Why are we not passing the domain to the ResourceError? See PR #119789.
    return ResourceError(String(), WebKitErrorCannotShowURL, request.url().string(), String());
}

void FrameLoaderClientBlackBerry::didRestoreFromPageCache()
{
    m_webPagePrivate->m_didRestoreFromPageCache = true;
}

void FrameLoaderClientBlackBerry::dispatchWillUpdateApplicationCache(const ResourceRequest&)
{
    ASSERT(isMainFrame());
    if (!isMainFrame())
        return;

    m_webPagePrivate->m_client->notifyWillUpdateApplicationCache();
}

void FrameLoaderClientBlackBerry::dispatchDidLoadFromApplicationCache(const ResourceRequest&)
{
    ASSERT(isMainFrame());
    if (!isMainFrame())
        return;

    m_webPagePrivate->m_client->notifyDidLoadFromApplicationCache();
}

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
PassRefPtr<SecurityOrigin> FrameLoaderClientBlackBerry::securityOriginForNewDocument(const KURL& url)
{
    // What we are trying to do here is to keep using the old path as origin when a file-based html page
    // changes its location to some html in a subfolder. This will allow some file-based html packages
    // to work smoothly even with security checks enabled.

    RefPtr<SecurityOrigin> newSecurityOrigin = SecurityOrigin::create(url);

    if (m_wasProvisionalLoadTriggeredByUserGesture || !url.isLocalFile())
        return newSecurityOrigin;

    RefPtr<SecurityOrigin> currentSecurityOrigin = m_frame->document()->securityOrigin();
    if (currentSecurityOrigin && currentSecurityOrigin->containsInFolder(newSecurityOrigin.get()))
        return currentSecurityOrigin;

    return newSecurityOrigin;
}

1295
} // WebCore