WebView.cpp 194 KB
Newer Older
aroben's avatar
aroben committed
1
/*
2
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple, Inc.  All rights reserved.
aroben's avatar
aroben committed
3
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
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 COMPUTER, INC. OR
 * 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. 
 */

#include "config.h"
#include "WebView.h"

beidson's avatar
beidson committed
29
#include "CFDictionaryPropertyBag.h"
aroben's avatar
aroben committed
30
#include "DOMCoreClasses.h"
31
#include "FullscreenVideoController.h"
32
#include "MarshallingHelpers.h"
33
#include "SoftLinking.h"
34
35
36
37
#include "WebBackForwardList.h"
#include "WebChromeClient.h"
#include "WebContextMenuClient.h"
#include "WebCoreTextRenderer.h"
beidson's avatar
beidson committed
38
#include "WebDatabaseManager.h"
aroben's avatar
aroben committed
39
#include "WebDocumentLoader.h"
40
#include "WebDownload.h"
41
#include "WebDragClient.h"
aroben's avatar
aroben committed
42
43
44
#include "WebEditorClient.h"
#include "WebElementPropertyBag.h"
#include "WebFrame.h"
45
46
#include "WebGeolocationControllerClient.h"
#include "WebGeolocationPosition.h"
beidson's avatar
beidson committed
47
#include "WebIconDatabase.h"
48
#include "WebInspector.h"
aroben's avatar
aroben committed
49
#include "WebInspectorClient.h"
aroben's avatar
aroben committed
50
#include "WebKit.h"
51
#include "WebKitDLL.h"
ap@apple.com's avatar
ap@apple.com committed
52
#include "WebKitLogging.h"
aroben's avatar
aroben committed
53
#include "WebKitStatisticsPrivate.h"
weinig's avatar
weinig committed
54
#include "WebKitSystemBits.h"
aroben's avatar
aroben committed
55
56
#include "WebMutableURLRequest.h"
#include "WebNotificationCenter.h"
57
#include "WebPluginHalterClient.h"
aroben's avatar
aroben committed
58
#include "WebPreferences.h"
59
#include "WebScriptWorld.h"
60
#include "WindowsTouch.h"
61
62
63
#include <JavaScriptCore/InitializeThreading.h>
#include <JavaScriptCore/JSLock.h>
#include <JavaScriptCore/JSValue.h>
64
#include <WebCore/AXObjectCache.h>
65
66
#include <WebCore/ApplicationCacheStorage.h>
#include <WebCore/BString.h>
67
#include <WebCore/BackForwardList.h>
bfulgham@webkit.org's avatar
bfulgham@webkit.org committed
68
#include <WebCore/BitmapInfo.h>
69
#include <WebCore/CString.h>
aroben's avatar
aroben committed
70
#include <WebCore/Cache.h>
71
#include <WebCore/Chrome.h>
72
#include <WebCore/ContextMenu.h>
aroben's avatar
aroben committed
73
#include <WebCore/ContextMenuController.h>
74
#include <WebCore/CookieStorageWin.h>
aroben's avatar
aroben committed
75
76
77
78
79
80
#include <WebCore/Cursor.h>
#include <WebCore/Document.h>
#include <WebCore/DragController.h>
#include <WebCore/DragData.h>
#include <WebCore/Editor.h>
#include <WebCore/EventHandler.h>
ap@webkit.org's avatar
ap@webkit.org committed
81
#include <WebCore/EventNames.h>
weinig's avatar
weinig committed
82
#include <WebCore/FileSystem.h>
83
#include <WebCore/FloatQuad.h>
84
#include <WebCore/FocusController.h>
aroben's avatar
aroben committed
85
86
87
88
89
90
#include <WebCore/FrameLoader.h>
#include <WebCore/FrameTree.h>
#include <WebCore/FrameView.h>
#include <WebCore/FrameWin.h>
#include <WebCore/GDIObjectCounter.h>
#include <WebCore/GraphicsContext.h>
91
92
#include <WebCore/HTMLMediaElement.h>
#include <WebCore/HTMLNames.h>
aroben's avatar
aroben committed
93
#include <WebCore/HistoryItem.h>
94
#include <WebCore/HitTestRequest.h>
aroben's avatar
aroben committed
95
96
97
#include <WebCore/HitTestResult.h>
#include <WebCore/IntRect.h>
#include <WebCore/KeyboardEvent.h>
98
#include <WebCore/Language.h>
99
#include <WebCore/Logging.h>
weinig's avatar
weinig committed
100
#include <WebCore/MIMETypeRegistry.h>
aroben's avatar
aroben committed
101
102
#include <WebCore/Page.h>
#include <WebCore/PageCache.h>
103
#include <WebCore/PageGroup.h>
aroben's avatar
aroben committed
104
105
106
#include <WebCore/PlatformKeyboardEvent.h>
#include <WebCore/PlatformMouseEvent.h>
#include <WebCore/PlatformWheelEvent.h>
107
108
109
#include <WebCore/PluginDatabase.h>
#include <WebCore/PluginInfoStore.h>
#include <WebCore/PluginView.h>
110
#include <WebCore/PopupMenu.h>
aroben's avatar
aroben committed
111
#include <WebCore/ProgressTracker.h>
hyatt@apple.com's avatar
hyatt@apple.com committed
112
#include <WebCore/RenderTheme.h>
113
#include <WebCore/RenderView.h>
114
#include <WebCore/RenderWidget.h>
aroben's avatar
aroben committed
115
116
#include <WebCore/ResourceHandle.h>
#include <WebCore/ResourceHandleClient.h>
117
#include <WebCore/ScriptValue.h>
118
#include <WebCore/Scrollbar.h>
hyatt@apple.com's avatar
hyatt@apple.com committed
119
#include <WebCore/ScrollbarTheme.h>
abarth@webkit.org's avatar
abarth@webkit.org committed
120
#include <WebCore/SecurityOrigin.h>
aroben's avatar
aroben committed
121
122
#include <WebCore/SelectionController.h>
#include <WebCore/Settings.h>
mitz@apple.com's avatar
mitz@apple.com committed
123
#include <WebCore/SimpleFontData.h>
aroben's avatar
aroben committed
124
#include <WebCore/TypingCommand.h>
125
#include <WebCore/WindowMessageBroadcaster.h>
126

127
128
129
130
131
#if ENABLE(CLIENT_BASED_GEOLOCATION)
#include <WebCore/GeolocationController.h>
#include <WebCore/GeolocationError.h>
#endif

132
133
134
135
136
137
138
139
140
#if PLATFORM(CG)
#include <CoreGraphics/CGContext.h>
#endif

#if PLATFORM(CF)
#include <CoreFoundation/CoreFoundation.h>
#endif

#if USE(CFNETWORK)
weinig's avatar
weinig committed
141
#include <CFNetwork/CFURLCachePriv.h>
aroben's avatar
aroben committed
142
#include <CFNetwork/CFURLProtocolPriv.h>
143
#include <WebKitSystemInterface/WebKitSystemInterface.h> 
144
145
#endif

146
#include <ShlObj.h>
147
#include <comutil.h>
oliver's avatar
oliver committed
148
#include <dimm.h>
149
150
151
#include <oleacc.h>
#include <tchar.h>
#include <windowsx.h>
152
#include <wtf/HashSet.h>
aroben's avatar
aroben committed
153

154
155
156
157
158
159
160
161
162
163
// Soft link functions for gestures and panning feedback
SOFT_LINK_LIBRARY(USER32);
SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
SOFT_LINK_LIBRARY(Uxtheme);
SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));

aroben's avatar
aroben committed
164
using namespace WebCore;
165
using namespace std;
166
using JSC::JSLock;
weinig's avatar
weinig committed
167

168
static HMODULE accessibilityLib;
169
static HashSet<WebView*> pendingDeleteBackingStoreSet;
170

171
172
173
static String osVersion();
static String webKitVersion();

174
175
176
177
178
WebView* kit(Page* page)
{
    return page ? static_cast<WebChromeClient*>(page->chrome()->client())->webView() : 0;
}

weinig's avatar
weinig committed
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
208
209
210
211
class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
public:
    static PreferencesChangedOrRemovedObserver* sharedInstance();

private:
    PreferencesChangedOrRemovedObserver() {}
    ~PreferencesChangedOrRemovedObserver() {}

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
    virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
    virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }

public:
    // IWebNotificationObserver
    virtual HRESULT STDMETHODCALLTYPE onNotify( 
        /* [in] */ IWebNotification* notification);

private:
    HRESULT notifyPreferencesChanged(WebCacheModel);
    HRESULT notifyPreferencesRemoved(WebCacheModel);
};

PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
{
    static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
    return shared;
}

HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
{
    HRESULT hr = S_OK;

    COMPtr<IUnknown> unkPrefs;
212
    hr = notification->getObject(&unkPrefs);
weinig's avatar
weinig committed
213
214
215
216
    if (FAILED(hr))
        return hr;

    COMPtr<IWebPreferences> preferences(Query, unkPrefs);
darin@apple.com's avatar
darin@apple.com committed
217
    if (!preferences)
weinig's avatar
weinig committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
        return E_NOINTERFACE;

    WebCacheModel cacheModel;
    hr = preferences->cacheModel(&cacheModel);
    if (FAILED(hr))
        return hr;

    BSTR nameBSTR;
    hr = notification->name(&nameBSTR);
    if (FAILED(hr))
        return hr;
    BString name;
    name.adoptBSTR(nameBSTR);

    if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
        return notifyPreferencesChanged(cacheModel);

    if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
        return notifyPreferencesRemoved(cacheModel);

    ASSERT_NOT_REACHED();
    return E_FAIL;
}

HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
{
    HRESULT hr = S_OK;

sfalken@apple.com's avatar
sfalken@apple.com committed
246
    if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
weinig's avatar
weinig committed
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
        WebView::setCacheModel(cacheModel);
    else if (cacheModel < WebView::cacheModel()) {
        WebCacheModel sharedPreferencesCacheModel;
        hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
        if (FAILED(hr))
            return hr;
        WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
    }

    return hr;
}

HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
{
    HRESULT hr = S_OK;

    if (cacheModel == WebView::cacheModel()) {
        WebCacheModel sharedPreferencesCacheModel;
        hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
        if (FAILED(hr))
            return hr;
        WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
    }

    return hr;
}

aroben's avatar
aroben committed
274
275
276
277

const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";

const int WM_XP_THEMECHANGED = 0x031A;
278
const int WM_VISTA_MOUSEHWHEEL = 0x020E;
aroben's avatar
aroben committed
279

280
281
static const int maxToolTipWidth = 250;

282
283
static const int delayBeforeDeletingBackingStoreMsec = 5000;

aroben's avatar
aroben committed
284
285
static ATOM registerWebView();

weinig's avatar
weinig committed
286
287
288
289
static void initializeStaticObservers();

static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);

aroben's avatar
aroben committed
290
291
292
293
294
HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);

static bool continuousSpellCheckingEnabled;
static bool grammarCheckingEnabled;

weinig's avatar
weinig committed
295
296
297
static bool s_didSetCacheModel;
static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;

298
299
enum {
    UpdateActiveStateTimer = 1,
300
    DeleteBackingStoreTimer = 2,
301
302
};

aroben's avatar
aroben committed
303
304
305
306
307
// WebView ----------------------------------------------------------------

bool WebView::s_allowSiteSpecificHacks = false;

WebView::WebView()
308
    : m_refCount(0)
309
310
311
#if !ASSERT_DISABLED
    , m_deletionHasBegun(false)
#endif
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    , m_hostWindow(0)
    , m_viewWindow(0)
    , m_mainFrame(0)
    , m_page(0)
    , m_hasCustomDropTarget(false)
    , m_useBackForwardList(true)
    , m_userAgentOverridden(false)
    , m_zoomMultiplier(1.0f)
    , m_mouseActivated(false)
    , m_dragData(0)
    , m_currentCharacterCode(0)
    , m_isBeingDestroyed(false)
    , m_paintCount(0)
    , m_hasSpellCheckerDocumentTag(false)
    , m_smartInsertDeleteEnabled(false)
    , m_didClose(false)
    , m_inIMEComposition(0)
    , m_toolTipHwnd(0)
    , m_closeWindowTimer(this, &WebView::closeWindowTimerFired)
    , m_topLevelParent(0)
    , m_deleteBackingStoreTimerActive(false)
    , m_transparent(false)
    , m_selectTrailingWhitespaceEnabled(false)
    , m_lastPanX(0)
    , m_lastPanY(0)
    , m_xOverpan(0)
    , m_yOverpan(0)
339
#if USE(ACCELERATED_COMPOSITING)
340
    , m_isAcceleratedCompositing(false)
341
#endif
aroben's avatar
aroben committed
342
{
343
    JSC::initializeThreading();
ap@webkit.org's avatar
ap@webkit.org committed
344

aroben's avatar
aroben committed
345
346
347
348
    m_backingStoreSize.cx = m_backingStoreSize.cy = 0;

    CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);

weinig's avatar
weinig committed
349
350
351
352
353
354
355
356
    initializeStaticObservers();

    WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
    BOOL enabled;
    if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
        continuousSpellCheckingEnabled = !!enabled;
    if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
        grammarCheckingEnabled = !!enabled;
aroben's avatar
aroben committed
357
358
359

    WebViewCount++;
    gClassCount++;
360
    gClassNameCount.add("WebView");
aroben's avatar
aroben committed
361
362
363
364
365
366
}

WebView::~WebView()
{
    deleteBackingStore();

367
368
369
370
    // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
    if (::IsWindow(m_toolTipHwnd))
        ::DestroyWindow(m_toolTipHwnd);

weinig's avatar
weinig committed
371
372
    ASSERT(!m_page);
    ASSERT(!m_preferences);
373
    ASSERT(!m_viewWindow);
aroben's avatar
aroben committed
374
375
376

    WebViewCount--;
    gClassCount--;
377
    gClassNameCount.remove("WebView");
aroben's avatar
aroben committed
378
379
380
381
382
383
384
385
386
}

WebView* WebView::createInstance()
{
    WebView* instance = new WebView();
    instance->AddRef();
    return instance;
}

weinig's avatar
weinig committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
void initializeStaticObservers()
{
    static bool initialized;
    if (initialized)
        return;
    initialized = true;

    IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
    notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
    notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
}

static HashSet<WebView*>& allWebViewsSet()
{
    static HashSet<WebView*> allWebViewsSet;
    return allWebViewsSet;
}

void WebView::addToAllWebViewsSet()
{
    allWebViewsSet().add(this);
}

void WebView::removeFromAllWebViewsSet()
{
    allWebViewsSet().remove(this);
}

void WebView::setCacheModel(WebCacheModel cacheModel)
{
417
#if USE(CFNETWORK)
weinig's avatar
weinig committed
418
419
420
    if (s_didSetCacheModel && cacheModel == s_cacheModel)
        return;

mitz@apple.com's avatar
mitz@apple.com committed
421
    RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
422
    RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory());
weinig's avatar
weinig committed
423
424
425
426
427
428
429
430
431
432
433
    if (!cfurlCacheDirectory)
        cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());

    // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
    // count doesn't align exactly to a megabyte boundary.
    unsigned long long memSize = WebMemorySize() / 1024 / 1000;
    unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;

    unsigned cacheTotalCapacity = 0;
    unsigned cacheMinDeadCapacity = 0;
    unsigned cacheMaxDeadCapacity = 0;
mitz@apple.com's avatar
mitz@apple.com committed
434
    double deadDecodedDataDeletionInterval = 0;
weinig's avatar
weinig committed
435
436
437
438
439
440
441
442
443
444
445
446

    unsigned pageCacheCapacity = 0;

    CFIndex cfurlCacheMemoryCapacity = 0;
    CFIndex cfurlCacheDiskCapacity = 0;

    switch (cacheModel) {
    case WebCacheModelDocumentViewer: {
        // Page cache capacity (in pages)
        pageCacheCapacity = 0;

        // Object cache capacities (in bytes)
447
        if (memSize >= 2048)
448
            cacheTotalCapacity = 96 * 1024 * 1024;
weinig's avatar
weinig committed
449
450
        else if (memSize >= 1536)
            cacheTotalCapacity = 64 * 1024 * 1024;
451
        else if (memSize >= 1024)
weinig's avatar
weinig committed
452
            cacheTotalCapacity = 32 * 1024 * 1024;
453
        else if (memSize >= 512)
weinig's avatar
weinig committed
454
455
456
457
458
459
460
461
462
            cacheTotalCapacity = 16 * 1024 * 1024; 

        cacheMinDeadCapacity = 0;
        cacheMaxDeadCapacity = 0;

        // Foundation memory cache capacity (in bytes)
        cfurlCacheMemoryCapacity = 0;

        // Foundation disk cache capacity (in bytes)
463
        cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
weinig's avatar
weinig committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

        break;
    }
    case WebCacheModelDocumentBrowser: {
        // Page cache capacity (in pages)
        if (memSize >= 1024)
            pageCacheCapacity = 3;
        else if (memSize >= 512)
            pageCacheCapacity = 2;
        else if (memSize >= 256)
            pageCacheCapacity = 1;
        else
            pageCacheCapacity = 0;

        // Object cache capacities (in bytes)
479
        if (memSize >= 2048)
480
            cacheTotalCapacity = 96 * 1024 * 1024;
weinig's avatar
weinig committed
481
482
        else if (memSize >= 1536)
            cacheTotalCapacity = 64 * 1024 * 1024;
483
        else if (memSize >= 1024)
weinig's avatar
weinig committed
484
            cacheTotalCapacity = 32 * 1024 * 1024;
485
        else if (memSize >= 512)
weinig's avatar
weinig committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
            cacheTotalCapacity = 16 * 1024 * 1024; 

        cacheMinDeadCapacity = cacheTotalCapacity / 8;
        cacheMaxDeadCapacity = cacheTotalCapacity / 4;

        // Foundation memory cache capacity (in bytes)
        if (memSize >= 2048)
            cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
        else if (memSize >= 1024)
            cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
        else if (memSize >= 512)
            cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
        else
            cfurlCacheMemoryCapacity =      512 * 1024; 

        // Foundation disk cache capacity (in bytes)
        if (diskFreeSize >= 16384)
            cfurlCacheDiskCapacity = 50 * 1024 * 1024;
        else if (diskFreeSize >= 8192)
            cfurlCacheDiskCapacity = 40 * 1024 * 1024;
        else if (diskFreeSize >= 4096)
            cfurlCacheDiskCapacity = 30 * 1024 * 1024;
        else
            cfurlCacheDiskCapacity = 20 * 1024 * 1024;

        break;
    }
    case WebCacheModelPrimaryWebBrowser: {
        // Page cache capacity (in pages)
        // (Research indicates that value / page drops substantially after 3 pages.)
516
        if (memSize >= 2048)
weinig's avatar
weinig committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
            pageCacheCapacity = 5;
        else if (memSize >= 1024)
            pageCacheCapacity = 4;
        else if (memSize >= 512)
            pageCacheCapacity = 3;
        else if (memSize >= 256)
            pageCacheCapacity = 2;
        else
            pageCacheCapacity = 1;

        // Object cache capacities (in bytes)
        // (Testing indicates that value / MB depends heavily on content and
        // browsing pattern. Even growth above 128MB can have substantial 
        // value / MB for some content / browsing patterns.)
531
        if (memSize >= 2048)
532
            cacheTotalCapacity = 128 * 1024 * 1024;
weinig's avatar
weinig committed
533
        else if (memSize >= 1536)
534
            cacheTotalCapacity = 96 * 1024 * 1024;
weinig's avatar
weinig committed
535
536
        else if (memSize >= 1024)
            cacheTotalCapacity = 64 * 1024 * 1024;
537
        else if (memSize >= 512)
weinig's avatar
weinig committed
538
539
540
541
542
543
544
545
546
            cacheTotalCapacity = 32 * 1024 * 1024; 

        cacheMinDeadCapacity = cacheTotalCapacity / 4;
        cacheMaxDeadCapacity = cacheTotalCapacity / 2;

        // This code is here to avoid a PLT regression. We can remove it if we
        // can prove that the overall system gain would justify the regression.
        cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);

mitz@apple.com's avatar
mitz@apple.com committed
547
548
        deadDecodedDataDeletionInterval = 60;

weinig's avatar
weinig committed
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
        // Foundation memory cache capacity (in bytes)
        // (These values are small because WebCore does most caching itself.)
        if (memSize >= 1024)
            cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
        else if (memSize >= 512)
            cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
        else if (memSize >= 256)
            cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
        else
            cfurlCacheMemoryCapacity =      512 * 1024; 

        // Foundation disk cache capacity (in bytes)
        if (diskFreeSize >= 16384)
            cfurlCacheDiskCapacity = 175 * 1024 * 1024;
        else if (diskFreeSize >= 8192)
            cfurlCacheDiskCapacity = 150 * 1024 * 1024;
        else if (diskFreeSize >= 4096)
            cfurlCacheDiskCapacity = 125 * 1024 * 1024;
        else if (diskFreeSize >= 2048)
            cfurlCacheDiskCapacity = 100 * 1024 * 1024;
        else if (diskFreeSize >= 1024)
            cfurlCacheDiskCapacity = 75 * 1024 * 1024;
        else
            cfurlCacheDiskCapacity = 50 * 1024 * 1024;

        break;
    }
    default:
        ASSERT_NOT_REACHED();
578
    }
weinig's avatar
weinig committed
579
580

    // Don't shrink a big disk cache, since that would cause churn.
581
    cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
weinig's avatar
weinig committed
582
583

    cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
mitz@apple.com's avatar
mitz@apple.com committed
584
    cache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
weinig's avatar
weinig committed
585
586
    pageCache()->setCapacity(pageCacheCapacity);

587
588
    CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
    CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
weinig's avatar
weinig committed
589
590
591
592

    s_didSetCacheModel = true;
    s_cacheModel = cacheModel;
    return;
593
#endif
weinig's avatar
weinig committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
}

WebCacheModel WebView::cacheModel()
{
    return s_cacheModel;
}

bool WebView::didSetCacheModel()
{
    return s_didSetCacheModel;
}

WebCacheModel WebView::maxCacheModelInAnyInstance()
{
    WebCacheModel cacheModel = WebCacheModelDocumentViewer;

    HashSet<WebView*>::iterator end = allWebViewsSet().end();
    for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
        COMPtr<IWebPreferences> pref;
613
        if (FAILED((*it)->preferences(&pref)))
weinig's avatar
weinig committed
614
615
616
617
618
619
620
621
622
623
624
            continue;
        WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
        if (FAILED(pref->cacheModel(&prefCacheModel)))
            continue;

        cacheModel = max(cacheModel, prefCacheModel);
    }

    return cacheModel;
}

mitz@apple.com's avatar
mitz@apple.com committed
625
HRESULT STDMETHODCALLTYPE WebView::close()
aroben's avatar
aroben committed
626
{
aroben's avatar
aroben committed
627
    if (m_didClose)
mitz@apple.com's avatar
mitz@apple.com committed
628
        return S_OK;
aroben's avatar
aroben committed
629
630
631

    m_didClose = true;

632
633
634
635
#if USE(ACCELERATED_COMPOSITING)
    setAcceleratedCompositing(false);
#endif

636
637
    WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);

sfalken@apple.com's avatar
sfalken@apple.com committed
638
639
    if (m_uiDelegatePrivate)
        m_uiDelegatePrivate->webViewClosing(this);
640

weinig's avatar
weinig committed
641
642
    removeFromAllWebViewsSet();

643
644
645
646
    if (m_page) {
        if (Frame* frame = m_page->mainFrame())
            frame->loader()->detachFromParent();
    }
ggaren's avatar
ggaren committed
647

648
649
650
651
652
    if (m_mouseOutTracker) {
        m_mouseOutTracker->dwFlags = TME_CANCEL;
        ::TrackMouseEvent(m_mouseOutTracker.get());
        m_mouseOutTracker.set(0);
    }
653
    
654
655
656
657
658
659
660
661
662
663
664
665
    revokeDragDrop();

    if (m_viewWindow) {
        // We can't check IsWindow(m_viewWindow) here, because that will return true even while
        // we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
        if (!isBeingDestroyed())
            DestroyWindow(m_viewWindow);
        // Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
        // way, we clear it out to make sure we don't try to use it later.
        m_viewWindow = 0;
    }

ggaren's avatar
ggaren committed
666
667
668
669
670
671
    setHostWindow(0);

    setDownloadDelegate(0);
    setEditingDelegate(0);
    setFrameLoadDelegate(0);
    setFrameLoadDelegatePrivate(0);
672
    setHistoryDelegate(0);
ggaren's avatar
ggaren committed
673
674
675
676
    setPolicyDelegate(0);
    setResourceLoadDelegate(0);
    setUIDelegate(0);
    setFormDelegate(0);
677
    setPluginHalterDelegate(0);
ggaren's avatar
ggaren committed
678

679
680
681
    if (m_webInspector)
        m_webInspector->webViewClosed();

ggaren's avatar
ggaren committed
682
683
684
    delete m_page;
    m_page = 0;

beidson's avatar
beidson committed
685
    registerForIconNotification(false);
aroben's avatar
aroben committed
686
    IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
weinig's avatar
weinig committed
687
688
    notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));

689
690
691
692
693
694
695
696
697
698
699
700
    if (COMPtr<WebPreferences> preferences = m_preferences) {
        BSTR identifier = 0;
        preferences->identifier(&identifier);

        m_preferences = 0;
        preferences->didRemoveFromWebView();
        // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
        preferences = 0;
        if (identifier) {
            WebPreferences::removeReferenceForIdentifier(identifier);
            SysFreeString(identifier);
        }
701
    }
aroben's avatar
aroben committed
702
703

    deleteBackingStore();
mitz@apple.com's avatar
mitz@apple.com committed
704
    return S_OK;
aroben's avatar
aroben committed
705
706
}

hyatt@apple.com's avatar
hyatt@apple.com committed
707
void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
708
{
709
710
711
712
713
#if USE(ACCELERATED_COMPOSITING)
    if (isAcceleratedCompositing())
        setRootLayerNeedsDisplay();
#endif

hyatt@apple.com's avatar
hyatt@apple.com committed
714
715
716
717
    if (!repaintContentOnly) {
        RECT rect = windowRect;
        ::InvalidateRect(m_viewWindow, &rect, false);
    }
718
719
    if (contentChanged)
        addToDirtyRegion(windowRect);
hyatt@apple.com's avatar
hyatt@apple.com committed
720
721
    if (immediate) {
        if (repaintContentOnly)
hyatt@apple.com's avatar
hyatt@apple.com committed
722
            updateBackingStore(core(topLevelFrame())->view());
hyatt@apple.com's avatar
hyatt@apple.com committed
723
724
725
        else
            ::UpdateWindow(m_viewWindow);
    }
726
727
}

aroben's avatar
aroben committed
728
729
void WebView::deleteBackingStore()
{
730
731
    pendingDeleteBackingStoreSet.remove(this);

732
733
734
735
    if (m_deleteBackingStoreTimerActive) {
        KillTimer(m_viewWindow, DeleteBackingStoreTimer);
        m_deleteBackingStoreTimerActive = false;
    }
darin's avatar
darin committed
736
737
    m_backingStoreBitmap.clear();
    m_backingStoreDirtyRegion.clear();
aroben's avatar
aroben committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752

    m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
}

bool WebView::ensureBackingStore()
{
    RECT windowRect;
    ::GetClientRect(m_viewWindow, &windowRect);
    LONG width = windowRect.right - windowRect.left;
    LONG height = windowRect.bottom - windowRect.top;
    if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
        deleteBackingStore();

        m_backingStoreSize.cx = width;
        m_backingStoreSize.cy = height;
bfulgham@webkit.org's avatar
bfulgham@webkit.org committed
753
        BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
aroben's avatar
aroben committed
754
755

        void* pixels = NULL;
darin's avatar
darin committed
756
        m_backingStoreBitmap.set(::CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, &pixels, NULL, 0));
aroben's avatar
aroben committed
757
758
759
760
761
762
763
764
        return true;
    }

    return false;
}

void WebView::addToDirtyRegion(const IntRect& dirtyRect)
{
765
766
767
768
    // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
    // but it was being hit during our layout tests, and is being investigated in
    // http://webkit.org/b/29350.

aroben's avatar
aroben committed
769
770
771
772
773
774
775
776
777
778
779
    HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
                                     dirtyRect.right(), dirtyRect.bottom());
    addToDirtyRegion(newRegion);
}

void WebView::addToDirtyRegion(HRGN newRegion)
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);

    if (m_backingStoreDirtyRegion) {
        HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
darin's avatar
darin committed
780
        ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion.get(), newRegion, RGN_OR);
aroben's avatar
aroben committed
781
        ::DeleteObject(newRegion);
darin's avatar
darin committed
782
        m_backingStoreDirtyRegion.set(combinedRegion);
aroben's avatar
aroben committed
783
    } else
darin's avatar
darin committed
784
        m_backingStoreDirtyRegion.set(newRegion);
785

sfalken@apple.com's avatar
sfalken@apple.com committed
786
787
    if (m_uiDelegatePrivate)
        m_uiDelegatePrivate->webViewDidInvalidate(this);
aroben's avatar
aroben committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
}

void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);

    // If there's no backing store we don't need to update it
    if (!m_backingStoreBitmap) {
        if (m_uiDelegatePrivate)
            m_uiDelegatePrivate->webViewScrolled(this);

        return;
    }

    // Make a region to hold the invalidated scroll area.
    HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);

    // Collect our device context info and select the bitmap to scroll.
    HDC windowDC = ::GetDC(m_viewWindow);
    HDC bitmapDC = ::CreateCompatibleDC(windowDC);
darin's avatar
darin committed
808
    ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
aroben's avatar
aroben committed
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
    
    // Scroll the bitmap.
    RECT scrollRectWin(scrollViewRect);
    RECT clipRectWin(clipRect);
    ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
    RECT regionBox;
    ::GetRgnBox(updateRegion, &regionBox);

    // Flush.
    GdiFlush();

    // Add the dirty region to the backing store's dirty region.
    addToDirtyRegion(updateRegion);

    if (m_uiDelegatePrivate)
        m_uiDelegatePrivate->webViewScrolled(this);

    // Update the backing store.
    updateBackingStore(frameView, bitmapDC, false);

    // Clean up.
    ::DeleteDC(bitmapDC);
    ::ReleaseDC(m_viewWindow, windowDC);
}

834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
// This emulates the Mac smarts for painting rects intelligently.  This is very
// important for us, since we double buffer based off dirty rects.
static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
{
    ASSERT_ARG(region, region);

    const int cRectThreshold = 10;
    const float cWastedSpaceThreshold = 0.75f;

    rects.clear();

    DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
    if (!regionDataSize) {
        rects.append(dirtyRect);
        return;
    }

851
852
    Vector<unsigned char> buffer(regionDataSize);
    RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    GetRegionData(region, regionDataSize, regionData);
    if (regionData->rdh.nCount > cRectThreshold) {
        rects.append(dirtyRect);
        return;
    }

    double singlePixels = 0.0;
    unsigned i;
    RECT* rect;
    for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
        singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);

    double unionPixels = dirtyRect.width() * dirtyRect.height();
    double wastedSpace = 1.0 - (singlePixels / unionPixels);
    if (wastedSpace <= cWastedSpaceThreshold) {
        rects.append(dirtyRect);
        return;
    }

    for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
        rects.append(*rect);
}

876
void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
aroben's avatar
aroben committed
877
878
879
880
881
882
883
884
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);

    HDC windowDC = 0;
    HDC bitmapDC = dc;
    if (!dc) {
        windowDC = ::GetDC(m_viewWindow);
        bitmapDC = ::CreateCompatibleDC(windowDC);
darin's avatar
darin committed
885
        ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
aroben's avatar
aroben committed
886
887
888
889
    }

    if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
        // Do a layout first so that everything we render to the backing store is always current.
890
891
892
        if (Frame* coreFrame = core(m_mainFrame))
            if (FrameView* view = coreFrame->view())
                view->layoutIfNeededRecursive();
aroben's avatar
aroben committed
893

894
        Vector<IntRect> paintRects;
aroben's avatar
aroben committed
895
        if (!backingStoreCompletelyDirty) {
896
            RECT regionBox;
darin's avatar
darin committed
897
            ::GetRgnBox(m_backingStoreDirtyRegion.get(), &regionBox);
898
899
900
901
902
903
            getUpdateRects(m_backingStoreDirtyRegion.get(), regionBox, paintRects);
        } else {
            RECT clientRect;
            ::GetClientRect(m_viewWindow, &clientRect);
            paintRects.append(clientRect);
        }
aroben's avatar
aroben committed
904

905
        for (unsigned i = 0; i < paintRects.size(); ++i)
906
            paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
aroben's avatar
aroben committed
907

sfalken@apple.com's avatar
sfalken@apple.com committed
908
909
        if (m_uiDelegatePrivate)
            m_uiDelegatePrivate->webViewPainted(this);
910

darin's avatar
darin committed
911
        m_backingStoreDirtyRegion.clear();
aroben's avatar
aroben committed
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
    }

    if (!dc) {
        ::DeleteDC(bitmapDC);
        ::ReleaseDC(m_viewWindow, windowDC);
    }

    GdiFlush();
}

void WebView::paint(HDC dc, LPARAM options)
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);

    Frame* coreFrame = core(m_mainFrame);
    if (!coreFrame)
        return;
    FrameView* frameView = coreFrame->view();

    m_paintCount++;

    RECT rcPaint;
    HDC hdc;
darin's avatar
darin committed
935
    OwnPtr<HRGN> region;
aroben's avatar
aroben committed
936
937
    int regionType = NULLREGION;
    PAINTSTRUCT ps;
938
    WindowsToPaint windowsToPaint;
aroben's avatar
aroben committed
939
    if (!dc) {
darin's avatar
darin committed
940
941
        region.set(CreateRectRgn(0,0,0,0));
        regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
aroben's avatar
aroben committed
942
943
        hdc = BeginPaint(m_viewWindow, &ps);
        rcPaint = ps.rcPaint;
944
945
946
        // We're painting to the screen, and our child windows can handle
        // painting themselves to the screen.
        windowsToPaint = PaintWebViewOnly;
aroben's avatar
aroben committed
947
948
949
950
951
    } else {
        hdc = dc;
        ::GetClientRect(m_viewWindow, &rcPaint);
        if (options & PRF_ERASEBKGND)
            ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
952
953
954
        // Since we aren't painting to the screen, we want to paint all our
        // children into the HDC.
        windowsToPaint = PaintWebViewAndChildren;
aroben's avatar
aroben committed
955
956
957
958
    }

    HDC bitmapDC = ::CreateCompatibleDC(hdc);
    bool backingStoreCompletelyDirty = ensureBackingStore();
darin's avatar
darin committed
959
    ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
aroben's avatar
aroben committed
960
961

    // Update our backing store if needed.
962
    updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
aroben's avatar
aroben committed
963

964
965
966
967
968
969
970
971
972
973
974
975
#if USE(ACCELERATED_COMPOSITING)
    if (!isAcceleratedCompositing()) {
#endif
        // Now we blit the updated backing store
        IntRect windowDirtyRect = rcPaint;
        
        // Apply the same heuristic for this update region too.
        Vector<IntRect> blitRects;
        if (region && regionType == COMPLEXREGION)
            getUpdateRects(region.get(), windowDirtyRect, blitRects);
        else
            blitRects.append(windowDirtyRect);
aroben's avatar
aroben committed
976

977
978
979
980
981
982
        for (unsigned i = 0; i < blitRects.size(); ++i)
            paintIntoWindow(bitmapDC, hdc, blitRects[i]);
#if USE(ACCELERATED_COMPOSITING)
    } else
        updateRootLayerContents();
#endif
aroben's avatar
aroben committed
983
984
985
986
987
988
989

    ::DeleteDC(bitmapDC);

    if (!dc)
        EndPaint(m_viewWindow, &ps);

    m_paintCount--;
990

991
992
993
994
    if (active())
        cancelDeleteBackingStoreSoon();
    else
        deleteBackingStoreSoon();
aroben's avatar
aroben committed
995
996
}

997
void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
aroben's avatar
aroben committed
998
999
1000
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);

1001
1002
1003
    // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
    // but it was being hit during our layout tests, and is being investigated in
    // http://webkit.org/b/29350.
1004

1005
1006
    RECT rect = dirtyRect;

aroben's avatar
aroben committed
1007
1008
#if FLASH_BACKING_STORE_REDRAW
    HDC dc = ::GetDC(m_viewWindow);
darin's avatar
darin committed
1009
    OwnPtr<HBRUSH> yellowBrush = CreateSolidBrush(RGB(255, 255, 0));
1010
    FillRect(dc, &rect, yellowBrush.get());
aroben's avatar
aroben committed
1011
1012
1013
1014
1015
1016
    GdiFlush();
    Sleep(50);
    paintIntoWindow(bitmapDC, dc, dirtyRect);
    ::ReleaseDC(m_viewWindow, dc);
#endif

1017
    GraphicsContext gc(bitmapDC, m_transparent);
1018
    gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
1019
1020
1021
1022
1023
    gc.save();
    if (m_transparent)
        gc.clearRect(dirtyRect);
    else
        FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1024
1025
1026
1027
1028

    COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
    if (uiPrivate)
        uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);

1029
    if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
1030
1031
        gc.clip(dirtyRect);
        frameView->paint(&gc, dirtyRect);
aroben's avatar
aroben committed
1032
    }
1033
    gc.restore();
aroben's avatar
aroben committed
1034
1035
}

1036
void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
aroben's avatar
aroben committed
1037
1038
1039
{
    LOCAL_GDI_COUNTER(0, __FUNCTION__);
#if FLASH_WINDOW_REDRAW
darin's avatar
darin committed
1040
    OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
1041
1042
    RECT rect = dirtyRect;
    FillRect(windowDC, &rect, greenBrush.get());
aroben's avatar
aroben committed
1043
1044
1045
1046
1047
1048
    GdiFlush();
    Sleep(50);
#endif

    // Blit the dirty rect from the backing store into the same position
    // in the destination DC.
1049
1050
    BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
           dirtyRect.x(), dirtyRect.y(), SRCCOPY);
aroben's avatar
aroben committed
1051
1052
1053
1054
1055
1056
1057
}

void WebView::frameRect(RECT* rect)
{
    ::GetWindowRect(m_viewWindow, rect);
}

mjs's avatar
mjs committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
void WebView::closeWindowSoon()
{
    m_closeWindowTimer.startOneShot(0);
    AddRef();
}

void WebView::closeWindowTimerFired(WebCore::Timer<WebView>*)
{
    closeWindow();
    Release();
}

aroben's avatar
aroben committed
1070
1071
1072
1073
1074
1075
1076
1077
1078
void WebView::closeWindow()
{
    if (m_hasSpellCheckerDocumentTag) {
        if (m_editingDelegate)
            m_editingDelegate->closeSpellDocument(this);
        m_hasSpellCheckerDocumentTag = false;
    }

    COMPtr<IWebUIDelegate> ui;
1079
    if (SUCCEEDED(uiDelegate(&ui)))
aroben's avatar
aroben committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
        ui->webViewClose(this);
}

bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
{
    // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
    if (equalIgnoringCase(String(request.url().protocol()), "about"))
        return true;

pewtermoose@webkit.org's avatar
pewtermoose@webkit.org committed
1089
#if USE(CFNETWORK)
aroben's avatar
aroben committed
1090
1091
1092
1093
1094
    if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
        return true;

    // FIXME: Mac WebKit calls _representationExistsForURLScheme here
    return false;
pewtermoose@webkit.org's avatar
pewtermoose@webkit.org committed
1095
1096
1097
#else
    return true;
#endif
aroben's avatar
aroben committed
1098
1099
}

1100
1101
1102
1103
1104
String WebView::standardUserAgentWithApplicationName(const String& applicationName)
{
    return String::format("Mozilla/5.0 (Windows; U; %s; %s) AppleWebKit/%s (KHTML, like Gecko)%s%s", osVersion().latin1().data(), defaultLanguage().latin1().data(), webKitVersion().latin1().data(), (applicationName.length() ? " " : ""), applicationName.latin1().data());
}

aroben's avatar
aroben committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
Page* WebView::page()
{
    return m_page;
}

bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
{
    static const int contextMenuMargin = 1;

    // Translate the screen coordinates into window coordinates
    POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
    if (coords.x == -1 || coords.y == -1) {
        FrameView* view = m_page->mainFrame()->view();
        if (!view)
            return false;

        int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
        IntPoint location;

        // The context menu event was generated from the keyboard, so show the context menu by the current selection.
darin@apple.com's avatar
darin@apple.com committed
1125
1126
        Position start = m_page->mainFrame()->selection()->selection().start();
        Position end = m_page->mainFrame()->selection()->selection().end();
aroben's avatar
aroben committed
1127
1128
1129
1130
1131
1132
1133
1134

        if (!start.node() || !end.node())
            location = IntPoint(rightAligned ? view->contentsWidth() - contextMenuMargin : contextMenuMargin, contextMenuMargin);
        else {
            RenderObject* renderer = start.node()->renderer();
            if (!renderer)
                return false;

1135
1136
            // Calculate the rect of the first line of the selection (cribbed from -[WebCoreFrameBridge firstRectForDOMRange:],
            // now Frame::firstRectForRange(), which perhaps this should call).
aroben's avatar
aroben committed
1137
            int extraWidthToEndOfLine = 0;
mitz@apple.com's avatar
mitz@apple.com committed
1138
1139
1140
1141

            InlineBox* startInlineBox;
            int startCaretOffset;
            start.getInlineBoxAndOffset(DOWNSTREAM, startInlineBox, startCaretOffset);
1142
1143
1144
            IntRect startCaretRect = renderer->localCaretRect(startInlineBox, startCaretOffset, &extraWidthToEndOfLine);
            if (startCaretRect != IntRect())
                startCaretRect = renderer->localToAbsoluteQuad(FloatRect(startCaretRect)).enclosingBoundingBox();
mitz@apple.com's avatar
mitz@apple.com committed
1145
1146
1147
1148

            InlineBox* endInlineBox;
            int endCaretOffset;
            end.getInlineBoxAndOffset(UPSTREAM, endInlineBox, endCaretOffset);
1149
1150
1151
            IntRect endCaretRect = renderer->localCaretRect(endInlineBox, endCaretOffset);
            if (endCaretRect != IntRect())
                endCaretRect = renderer->localToAbsoluteQuad(FloatRect(endCaretRect)).enclosingBoundingBox();
aroben's avatar
aroben committed
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

            IntRect firstRect;
            if (startCaretRect.y() == endCaretRect.y())
                firstRect = IntRect(min(startCaretRect.x(), endCaretRect.x()), startCaretRect.y(), abs(endCaretRect.x() - startCaretRect.x()), max(startCaretRect.height(), endCaretRect.height()));
            else
                firstRect = IntRect(startCaretRect.x(), startCaretRect.y(), startCaretRect.width() + extraWidthToEndOfLine, startCaretRect.height());

            location = IntPoint(rightAligned ? firstRect.right() : firstRect.x(), firstRect.bottom());
        }

        location = view->contentsToWindow(location);
        // FIXME: The IntSize(0, -1) is a hack to get the hit-testing to result in the selected element.
        // Ideally we'd have the position of a context menu event be separate from its target node.
        coords = location + IntSize(0, -1);
    } else {
        if (!::ScreenToClient(m_viewWindow, &coords))
            return false;
    }

    lParam = MAKELPARAM(coords.x, coords.y);

    // The contextMenuController() holds onto the last context menu that was popped up on the
    // page until a new one is created. We need to clear this menu before propagating the event
    // through the DOM so that we can detect if we create a new menu for this event, since we
    // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
    // not run.
    m_page->contextMenuController()->clearContextMenu();

1180
1181
    IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
    HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
mitz@apple.com's avatar
mitz@apple.com committed
1182
    Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
mitz@apple.com's avatar
mitz@apple.com committed
1183
1184

    targetFrame->view()->setCursor(pointerCursor());
aroben's avatar
aroben committed
1185
    PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
mitz@apple.com's avatar
mitz@apple.com committed
1186
    bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
aroben's avatar
aroben committed
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
    if (!handledEvent)
        return false;

    // Show the menu
    ContextMenu* coreMenu = m_page->contextMenuController()->contextMenu();
    if (!coreMenu)
        return false;

    Node* node = coreMenu->hitTestResult().innerNonSharedNode();
    if (!node)
        return false;

    Frame* frame = node->document()->frame();
    if (!frame)
        return false;

    FrameView* view = frame->view();
    if (!view)
        return false;

    POINT point(view->contentsToWindow(coreMenu->hitTestResult().point()));

    // Translate the point to screen coordinates
1210
    if (!::ClientToScreen(m_viewWindow, &point))
aroben's avatar
aroben committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
        return false;

    BOOL hasCustomMenus = false;
    if (m_uiDelegate)
        m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);

    if (hasCustomMenus)
        m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformDescription(), &point);
    else {
        // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
        UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
            | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1223
        ::TrackPopupMenuEx(coreMenu->platformDescription(), flags, point.x, point.y, m_viewWindow, 0);
aroben's avatar
aroben committed
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
    }

    return true;
}

bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
{
    if (!m_uiDelegate)
        return false;

    BOOL hasCustomMenus = false;
    m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
    if (!hasCustomMenus)
        return false;

    m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
    return true;
}

bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
{
    if (!m_uiDelegate)
        return false;

    BOOL hasCustomMenus = false;
    m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
    if (!hasCustomMenus)
        return false;

    m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
    return true;
}

bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
    if (!m_uiDelegate)
        return false;

    HMENU menu = (HMENU)wParam;
    if (!menu)
        return false;

    BOOL hasCustomMenus = false;
    m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
    if (!hasCustomMenus)
        return false;

    m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
    return true;
}

bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
    if (!m_uiDelegate)
        return false;

    HMENU menu = (HMENU)wParam;
    if (!menu)
        return false;

    BOOL hasCustomMenus = false;
    m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
    if (!hasCustomMenus)
        return false;

    m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
    return true;
}

1293
void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
aroben's avatar
aroben committed
1294
1295
1296
{
    ContextMenu* menu = m_page->contextMenuController()->contextMenu();
    ASSERT(menu);
aroben's avatar
aroben committed
1297

1298
1299
1300
    ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam, (HMENU)lParam) : menu->itemWithAction((ContextMenuAction)wParam);
    if (!item)
        return;
aroben's avatar
aroben committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
    m_page->contextMenuController()->contextMenuItemSelected(item);
    delete item;
}

bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
    static LONG globalClickCount;
    static IntPoint globalPrevPoint;
    static MouseButton globalPrevButton;
    static LONG globalPrevMouseDownTime;

    // Create our event.
1313
1314
1315
1316
    // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
    // of the event to be at (MINSHORT, MINSHORT).
    LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
    PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
aroben's avatar
aroben committed
1317
1318
1319
1320
   
    bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
                           abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
    LONG messageTime = ::GetMessageTime();
1321

aroben's avatar
aroben committed
1322
    bool handled = false;
1323

aroben's avatar
aroben 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
1352
1353
1354
1355
1356
    if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
        // FIXME: I'm not sure if this is the "right" way to do this
        // but without this call, we never become focused since we don't allow
        // the default handling of mouse events.
        SetFocus(m_viewWindow);

        // Always start capturing events when the mouse goes down in our HWND.
        ::SetCapture(m_viewWindow);

        if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) && 
            insideThreshold &&
            mouseEvent.button() == globalPrevButton)
            globalClickCount++;
        else
            // Reset the click count.
            globalClickCount = 1;
        globalPrevMouseDownTime = messageTime;
        globalPrevButton = mouseEvent.button();
        globalPrevPoint = mouseEvent.pos();
        
        mouseEvent.setClickCount(globalClickCount);
        handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
    } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
        gl