/
WebFrameImpl.cpp
2013 lines (1700 loc) · 65.3 KB
/
WebFrameImpl.cpp
1
2
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
114
115
116
117
118
119
120
121
122
123
124
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
208
209
210
211
212
213
214
215
216
217
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
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
288
289
290
291
292
293
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
644
645
646
647
648
649
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
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
805
806
807
808
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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
908
909
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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER 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.
*/
// How ownership works
// -------------------
//
// Big oh represents a refcounted relationship: owner O--- ownee
//
// WebView (for the toplevel frame only)
// O
// |
// Page O------- Frame (m_mainFrame) O-------O FrameView
// ||
// ||
// FrameLoader O-------- WebFrame (via FrameLoaderClient)
//
// FrameLoader and Frame are formerly one object that was split apart because
// it got too big. They basically have the same lifetime, hence the double line.
//
// WebFrame is refcounted and has one ref on behalf of the FrameLoader/Frame.
// This is not a normal reference counted pointer because that would require
// changing WebKit code that we don't control. Instead, it is created with this
// ref initially and it is removed when the FrameLoader is getting destroyed.
//
// WebFrames are created in two places, first in WebViewImpl when the root
// frame is created, and second in WebFrame::CreateChildFrame when sub-frames
// are created. WebKit will hook up this object to the FrameLoader/Frame
// and the refcount will be correct.
//
// How frames are destroyed
// ------------------------
//
// The main frame is never destroyed and is re-used. The FrameLoader is re-used
// and a reference to the main frame is kept by the Page.
//
// When frame content is replaced, all subframes are destroyed. This happens
// in FrameLoader::detachFromParent for each subframe.
//
// Frame going away causes the FrameLoader to get deleted. In FrameLoader's
// destructor, it notifies its client with frameLoaderDestroyed. This calls
// WebFrame::Closing and then derefs the WebFrame and will cause it to be
// deleted (unless an external someone is also holding a reference).
#include "config.h"
#include "WebFrameImpl.h"
#include "Chrome.h"
#include "ChromiumBridge.h"
#include "ClipboardUtilitiesChromium.h"
#include "Console.h"
#include "Document.h"
#include "DocumentFragment.h" // Only needed for ReplaceSelectionCommand.h :(
#include "DocumentLoader.h"
#include "DocumentMarker.h"
#include "DOMUtilitiesPrivate.h"
#include "DOMWindow.h"
#include "Editor.h"
#include "EventHandler.h"
#include "FormState.h"
#include "FrameLoader.h"
#include "FrameLoadRequest.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HistoryItem.h"
#include "HTMLCollection.h"
#include "HTMLFormElement.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHeadElement.h"
#include "HTMLInputElement.h"
#include "HTMLLinkElement.h"
#include "HTMLNames.h"
#include "InspectorController.h"
#include "markup.h"
#include "Page.h"
#include "PlatformContextSkia.h"
#include "PrintContext.h"
#include "RenderFrame.h"
#include "RenderTreeAsText.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ReplaceSelectionCommand.h"
#include "ResourceHandle.h"
#include "ResourceRequest.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ScriptValue.h"
#include "ScrollbarTheme.h"
#include "ScrollTypes.h"
#include "SelectionController.h"
#include "Settings.h"
#include "SkiaUtils.h"
#include "SubstituteData.h"
#include "TextAffinity.h"
#include "TextIterator.h"
#include "WebAnimationControllerImpl.h"
#include "WebConsoleMessage.h"
#include "WebDataSourceImpl.h"
#include "WebDocument.h"
#include "WebFindOptions.h"
#include "WebFormElement.h"
#include "WebFrameClient.h"
#include "WebHistoryItem.h"
#include "WebInputElement.h"
#include "WebPasswordAutocompleteListener.h"
#include "WebRange.h"
#include "WebRect.h"
#include "WebScriptSource.h"
#include "WebSecurityOrigin.h"
#include "WebSize.h"
#include "WebURLError.h"
#include "WebVector.h"
#include "WebViewImpl.h"
#include "XPathResult.h"
#include <algorithm>
#include <wtf/CurrentTime.h>
#if OS(DARWIN)
#include "LocalCurrentGraphicsContext.h"
#endif
#if OS(LINUX)
#include <gdk/gdk.h>
#endif
using namespace WebCore;
namespace WebKit {
static int frameCount = 0;
// Key for a StatsCounter tracking how many WebFrames are active.
static const char* const webFrameActiveCount = "WebFrameActiveCount";
static const char* const osdType = "application/opensearchdescription+xml";
static const char* const osdRel = "search";
// Backend for contentAsPlainText, this is a recursive function that gets
// the text for the current frame and all of its subframes. It will append
// the text of each frame in turn to the |output| up to |maxChars| length.
//
// The |frame| must be non-null.
static void frameContentAsPlainText(size_t maxChars, Frame* frame,
Vector<UChar>* output)
{
Document* doc = frame->document();
if (!doc)
return;
if (!frame->view())
return;
// TextIterator iterates over the visual representation of the DOM. As such,
// it requires you to do a layout before using it (otherwise it'll crash).
if (frame->view()->needsLayout())
frame->view()->layout();
// Select the document body.
RefPtr<Range> range(doc->createRange());
ExceptionCode exception = 0;
range->selectNodeContents(doc->body(), exception);
if (!exception) {
// The text iterator will walk nodes giving us text. This is similar to
// the plainText() function in TextIterator.h, but we implement the maximum
// size and also copy the results directly into a wstring, avoiding the
// string conversion.
for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
const UChar* chars = it.characters();
if (!chars) {
if (it.length()) {
// It appears from crash reports that an iterator can get into a state
// where the character count is nonempty but the character pointer is
// null. advance()ing it will then just add that many to the null
// pointer which won't be caught in a null check but will crash.
//
// A null pointer and 0 length is common for some nodes.
//
// IF YOU CATCH THIS IN A DEBUGGER please let brettw know. We don't
// currently understand the conditions for this to occur. Ideally, the
// iterators would never get into the condition so we should fix them
// if we can.
ASSERT_NOT_REACHED();
break;
}
// Just got a null node, we can forge ahead!
continue;
}
size_t toAppend =
std::min(static_cast<size_t>(it.length()), maxChars - output->size());
output->append(chars, toAppend);
if (output->size() >= maxChars)
return; // Filled up the buffer.
}
}
// The separator between frames when the frames are converted to plain text.
const UChar frameSeparator[] = { '\n', '\n' };
const size_t frameSeparatorLen = 2;
// Recursively walk the children.
FrameTree* frameTree = frame->tree();
for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) {
// Make sure the frame separator won't fill up the buffer, and give up if
// it will. The danger is if the separator will make the buffer longer than
// maxChars. This will cause the computation above:
// maxChars - output->size()
// to be a negative number which will crash when the subframe is added.
if (output->size() >= maxChars - frameSeparatorLen)
return;
output->append(frameSeparator, frameSeparatorLen);
frameContentAsPlainText(maxChars, curChild, output);
if (output->size() >= maxChars)
return; // Filled up the buffer.
}
}
// Simple class to override some of PrintContext behavior.
class ChromePrintContext : public PrintContext, public Noncopyable {
public:
ChromePrintContext(Frame* frame)
: PrintContext(frame)
, m_printedPageWidth(0)
{
}
void begin(float width)
{
ASSERT(!m_printedPageWidth);
m_printedPageWidth = width;
PrintContext::begin(m_printedPageWidth);
}
float getPageShrink(int pageNumber) const
{
IntRect pageRect = m_pageRects[pageNumber];
return m_printedPageWidth / pageRect.width();
}
// Spools the printed page, a subrect of m_frame. Skip the scale step.
// NativeTheme doesn't play well with scaling. Scaling is done browser side
// instead. Returns the scale to be applied.
float spoolPage(GraphicsContext& ctx, int pageNumber)
{
IntRect pageRect = m_pageRects[pageNumber];
float scale = m_printedPageWidth / pageRect.width();
ctx.save();
ctx.translate(static_cast<float>(-pageRect.x()),
static_cast<float>(-pageRect.y()));
ctx.clip(pageRect);
m_frame->view()->paintContents(&ctx, pageRect);
ctx.restore();
return scale;
}
private:
// Set when printing.
float m_printedPageWidth;
};
static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
{
return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
}
// WebFrame -------------------------------------------------------------------
class WebFrameImpl::DeferredScopeStringMatches {
public:
DeferredScopeStringMatches(WebFrameImpl* webFrame,
int identifier,
const WebString& searchText,
const WebFindOptions& options,
bool reset)
: m_timer(this, &DeferredScopeStringMatches::doTimeout)
, m_webFrame(webFrame)
, m_identifier(identifier)
, m_searchText(searchText)
, m_options(options)
, m_reset(reset)
{
m_timer.startOneShot(0.0);
}
private:
void doTimeout(Timer<DeferredScopeStringMatches>*)
{
m_webFrame->callScopeStringMatches(
this, m_identifier, m_searchText, m_options, m_reset);
}
Timer<DeferredScopeStringMatches> m_timer;
RefPtr<WebFrameImpl> m_webFrame;
int m_identifier;
WebString m_searchText;
WebFindOptions m_options;
bool m_reset;
};
// WebFrame -------------------------------------------------------------------
int WebFrame::instanceCount()
{
return frameCount;
}
WebFrame* WebFrame::frameForEnteredContext()
{
Frame* frame =
ScriptController::retrieveFrameForEnteredContext();
return WebFrameImpl::fromFrame(frame);
}
WebFrame* WebFrame::frameForCurrentContext()
{
Frame* frame =
ScriptController::retrieveFrameForCurrentContext();
return WebFrameImpl::fromFrame(frame);
}
WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
{
return WebFrameImpl::fromFrameOwnerElement(
PassRefPtr<Element>(element).get());
}
WebString WebFrameImpl::name() const
{
return m_frame->tree()->name();
}
void WebFrameImpl::clearName()
{
m_frame->tree()->clearName();
}
WebURL WebFrameImpl::url() const
{
const WebDataSource* ds = dataSource();
if (!ds)
return WebURL();
return ds->request().url();
}
WebURL WebFrameImpl::favIconURL() const
{
FrameLoader* frameLoader = m_frame->loader();
// The URL to the favicon may be in the header. As such, only
// ask the loader for the favicon if it's finished loading.
if (frameLoader->state() == FrameStateComplete) {
const KURL& url = frameLoader->iconURL();
if (!url.isEmpty())
return url;
}
return WebURL();
}
WebURL WebFrameImpl::openSearchDescriptionURL() const
{
FrameLoader* frameLoader = m_frame->loader();
if (frameLoader->state() == FrameStateComplete
&& m_frame->document() && m_frame->document()->head()
&& !m_frame->tree()->parent()) {
HTMLHeadElement* head = m_frame->document()->head();
if (head) {
RefPtr<HTMLCollection> children = head->children();
for (Node* child = children->firstItem(); child; child = children->nextItem()) {
HTMLLinkElement* linkElement = toHTMLLinkElement(child);
if (linkElement
&& linkElement->type() == osdType
&& linkElement->rel() == osdRel
&& !linkElement->href().isEmpty())
return linkElement->href();
}
}
}
return WebURL();
}
WebString WebFrameImpl::encoding() const
{
return frame()->loader()->encoding();
}
WebSize WebFrameImpl::scrollOffset() const
{
FrameView* view = frameView();
if (view)
return view->scrollOffset();
return WebSize();
}
WebSize WebFrameImpl::contentsSize() const
{
return frame()->view()->contentsSize();
}
int WebFrameImpl::contentsPreferredWidth() const
{
if (m_frame->document() && m_frame->document()->renderView())
return m_frame->document()->renderView()->minPrefWidth();
return 0;
}
int WebFrameImpl::documentElementScrollHeight() const
{
if (m_frame->document() && m_frame->document()->documentElement())
return m_frame->document()->documentElement()->scrollHeight();
return 0;
}
bool WebFrameImpl::hasVisibleContent() const
{
return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
}
WebView* WebFrameImpl::view() const
{
return viewImpl();
}
WebFrame* WebFrameImpl::opener() const
{
Frame* opener = 0;
if (m_frame)
opener = m_frame->loader()->opener();
return fromFrame(opener);
}
WebFrame* WebFrameImpl::parent() const
{
Frame* parent = 0;
if (m_frame)
parent = m_frame->tree()->parent();
return fromFrame(parent);
}
WebFrame* WebFrameImpl::top() const
{
if (m_frame)
return fromFrame(m_frame->tree()->top());
return 0;
}
WebFrame* WebFrameImpl::firstChild() const
{
return fromFrame(frame()->tree()->firstChild());
}
WebFrame* WebFrameImpl::lastChild() const
{
return fromFrame(frame()->tree()->lastChild());
}
WebFrame* WebFrameImpl::nextSibling() const
{
return fromFrame(frame()->tree()->nextSibling());
}
WebFrame* WebFrameImpl::previousSibling() const
{
return fromFrame(frame()->tree()->previousSibling());
}
WebFrame* WebFrameImpl::traverseNext(bool wrap) const
{
return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
}
WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
{
return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
}
WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
{
return fromFrame(frame()->tree()->child(name));
}
WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
{
if (xpath.isEmpty())
return 0;
Document* document = m_frame->document();
ExceptionCode ec = 0;
PassRefPtr<XPathResult> xpathResult =
document->evaluate(xpath,
document,
0, // namespace
XPathResult::ORDERED_NODE_ITERATOR_TYPE,
0, // XPathResult object
ec);
if (!xpathResult.get())
return 0;
Node* node = xpathResult->iterateNext(ec);
if (!node || !node->isFrameOwnerElement())
return 0;
HTMLFrameOwnerElement* frameElement =
static_cast<HTMLFrameOwnerElement*>(node);
return fromFrame(frameElement->contentFrame());
}
WebDocument WebFrameImpl::document() const
{
if (!m_frame || !m_frame->document())
return WebDocument();
return WebDocument(m_frame->document());
}
void WebFrameImpl::forms(WebVector<WebFormElement>& results) const
{
if (!m_frame)
return;
RefPtr<HTMLCollection> forms = m_frame->document()->forms();
size_t formCount = forms->length();
WebVector<WebFormElement> temp(formCount);
for (size_t i = 0; i < formCount; ++i) {
Node* node = forms->item(i);
// Strange but true, sometimes item can be 0.
if (node && node->isHTMLElement())
temp[i] = static_cast<HTMLFormElement*>(node);
}
results.swap(temp);
}
WebAnimationController* WebFrameImpl::animationController()
{
return &m_animationController;
}
WebSecurityOrigin WebFrameImpl::securityOrigin() const
{
if (!m_frame || !m_frame->document())
return WebSecurityOrigin();
return WebSecurityOrigin(m_frame->document()->securityOrigin());
}
void WebFrameImpl::grantUniversalAccess()
{
ASSERT(m_frame && m_frame->document());
if (m_frame && m_frame->document())
m_frame->document()->securityOrigin()->grantUniversalAccess();
}
NPObject* WebFrameImpl::windowObject() const
{
if (!m_frame)
return 0;
return m_frame->script()->windowScriptNPObject();
}
void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
{
ASSERT(m_frame);
if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
return;
String key = name;
#if USE(V8)
m_frame->script()->bindToWindowObject(m_frame, key, object);
#else
notImplemented();
#endif
}
void WebFrameImpl::executeScript(const WebScriptSource& source)
{
m_frame->script()->executeScript(
ScriptSourceCode(source.code, source.url, source.startLine));
}
void WebFrameImpl::executeScriptInIsolatedWorld(
int worldId, const WebScriptSource* sourcesIn, unsigned numSources,
int extensionGroup)
{
Vector<ScriptSourceCode> sources;
for (unsigned i = 0; i < numSources; ++i) {
sources.append(ScriptSourceCode(
sourcesIn[i].code, sourcesIn[i].url, sourcesIn[i].startLine));
}
m_frame->script()->evaluateInIsolatedWorld(worldId, sources, extensionGroup);
}
void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
{
ASSERT(frame());
MessageLevel webCoreMessageLevel;
switch (message.level) {
case WebConsoleMessage::LevelTip:
webCoreMessageLevel = TipMessageLevel;
break;
case WebConsoleMessage::LevelLog:
webCoreMessageLevel = LogMessageLevel;
break;
case WebConsoleMessage::LevelWarning:
webCoreMessageLevel = WarningMessageLevel;
break;
case WebConsoleMessage::LevelError:
webCoreMessageLevel = ErrorMessageLevel;
break;
default:
ASSERT_NOT_REACHED();
return;
}
frame()->domWindow()->console()->addMessage(
OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text,
1, String());
}
void WebFrameImpl::collectGarbage()
{
if (!m_frame)
return;
if (!m_frame->settings()->isJavaScriptEnabled())
return;
// FIXME: Move this to the ScriptController and make it JS neutral.
#if USE(V8)
m_frame->script()->collectGarbage();
#else
notImplemented();
#endif
}
#if USE(V8)
// Returns the V8 context for this frame, or an empty handle if there is none.
v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
{
if (!m_frame)
return v8::Local<v8::Context>();
return V8Proxy::mainWorldContext(m_frame);
}
#endif
bool WebFrameImpl::insertStyleText(
const WebString& css, const WebString& id) {
Document* document = frame()->document();
if (!document)
return false;
Element* documentElement = document->documentElement();
if (!documentElement)
return false;
ExceptionCode err = 0;
if (!id.isEmpty()) {
Element* oldElement = document->getElementById(id);
if (oldElement) {
Node* parent = oldElement->parent();
if (!parent)
return false;
parent->removeChild(oldElement, err);
}
}
RefPtr<Element> stylesheet = document->createElement(
HTMLNames::styleTag, false);
if (!id.isEmpty())
stylesheet->setAttribute(HTMLNames::idAttr, id);
stylesheet->setTextContent(css, err);
ASSERT(!err);
Node* first = documentElement->firstChild();
bool success = documentElement->insertBefore(stylesheet, first, err);
ASSERT(success);
return success;
}
void WebFrameImpl::reload(bool ignoreCache)
{
m_frame->loader()->history()->saveDocumentAndScrollState();
stopLoading(); // Make sure existing activity stops.
m_frame->loader()->reload(ignoreCache);
}
void WebFrameImpl::loadRequest(const WebURLRequest& request)
{
ASSERT(!request.isNull());
const ResourceRequest& resourceRequest = request.toResourceRequest();
if (resourceRequest.url().protocolIs("javascript")) {
loadJavaScriptURL(resourceRequest.url());
return;
}
stopLoading(); // Make sure existing activity stops.
m_frame->loader()->load(resourceRequest, false);
}
void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
{
RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
ASSERT(historyItem.get());
stopLoading(); // Make sure existing activity stops.
// If there is no currentItem, which happens when we are navigating in
// session history after a crash, we need to manufacture one otherwise WebKit
// hoarks. This is probably the wrong thing to do, but it seems to work.
RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem();
if (!currentItem) {
currentItem = HistoryItem::create();
currentItem->setLastVisitWasFailure(true);
m_frame->loader()->history()->setCurrentItem(currentItem.get());
viewImpl()->setCurrentHistoryItem(currentItem.get());
}
m_frame->loader()->history()->goToItem(
historyItem.get(), FrameLoadTypeIndexedBackForward);
}
void WebFrameImpl::loadData(const WebData& data,
const WebString& mimeType,
const WebString& textEncoding,
const WebURL& baseURL,
const WebURL& unreachableURL,
bool replace)
{
SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
ASSERT(substData.isValid());
// If we are loading substitute data to replace an existing load, then
// inherit all of the properties of that original request. This way,
// reload will re-attempt the original request. It is essential that
// we only do this when there is an unreachableURL since a non-empty
// unreachableURL informs FrameLoader::reload to load unreachableURL
// instead of the currently loaded URL.
ResourceRequest request;
if (replace && !unreachableURL.isEmpty())
request = m_frame->loader()->originalRequest();
request.setURL(baseURL);
stopLoading(); // Make sure existing activity stops.
m_frame->loader()->load(request, substData, false);
if (replace) {
// Do this to force WebKit to treat the load as replacing the currently
// loaded page.
m_frame->loader()->setReplacing();
}
}
void WebFrameImpl::loadHTMLString(const WebData& data,
const WebURL& baseURL,
const WebURL& unreachableURL,
bool replace)
{
loadData(data,
WebString::fromUTF8("text/html"),
WebString::fromUTF8("UTF-8"),
baseURL,
unreachableURL,
replace);
}
bool WebFrameImpl::isLoading() const
{
if (!m_frame)
return false;
return m_frame->loader()->isLoading();
}
void WebFrameImpl::stopLoading()
{
if (!m_frame)
return;
// FIXME: Figure out what we should really do here. It seems like a bug
// that FrameLoader::stopLoading doesn't call stopAllLoaders.
m_frame->loader()->stopAllLoaders();
m_frame->loader()->stopLoading(UnloadEventPolicyNone);
}
WebDataSource* WebFrameImpl::provisionalDataSource() const
{
FrameLoader* frameLoader = m_frame->loader();
// We regard the policy document loader as still provisional.
DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
if (!docLoader)
docLoader = frameLoader->policyDocumentLoader();
return DataSourceForDocLoader(docLoader);
}
WebDataSource* WebFrameImpl::dataSource() const
{
return DataSourceForDocLoader(m_frame->loader()->documentLoader());
}
WebHistoryItem WebFrameImpl::previousHistoryItem() const
{
// We use the previous item here because documentState (filled-out forms)
// only get saved to history when it becomes the previous item. The caller
// is expected to query the history item after a navigation occurs, after
// the desired history item has become the previous entry.
return WebHistoryItem(viewImpl()->previousHistoryItem());
}
WebHistoryItem WebFrameImpl::currentHistoryItem() const
{
m_frame->loader()->history()->saveDocumentAndScrollState();
return WebHistoryItem(m_frame->page()->backForwardList()->currentItem());
}
void WebFrameImpl::enableViewSourceMode(bool enable)
{
if (m_frame)
m_frame->setInViewSourceMode(enable);
}
bool WebFrameImpl::isViewSourceModeEnabled() const
{
if (m_frame)
return m_frame->inViewSourceMode();
return false;
}
void WebFrameImpl::setReferrerForRequest(
WebURLRequest& request, const WebURL& referrerURL) {
String referrer;
if (referrerURL.isEmpty())
referrer = m_frame->loader()->outgoingReferrer();
else
referrer = referrerURL.spec().utf16();
if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
return;
request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
}
void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
{
ResourceResponse response;
m_frame->loader()->client()->dispatchWillSendRequest(
0, 0, request.toMutableResourceRequest(), response);
}
void WebFrameImpl::commitDocumentData(const char* data, size_t dataLen)
{
DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
// Set the text encoding. This calls begin() for us. It is safe to call
// this multiple times (Mac does: page/mac/WebCoreFrameBridge.mm).
bool userChosen = true;
String encoding = documentLoader->overrideEncoding();
if (encoding.isNull()) {
userChosen = false;
encoding = documentLoader->response().textEncodingName();
}
m_frame->loader()->setEncoding(encoding, userChosen);
// NOTE: mac only does this if there is a document
m_frame->loader()->addData(data, dataLen);
}
unsigned WebFrameImpl::unloadListenerCount() const
{
return frame()->domWindow()->pendingUnloadEventListeners();
}
bool WebFrameImpl::isProcessingUserGesture() const
{
return frame()->loader()->isProcessingUserGesture();
}
bool WebFrameImpl::willSuppressOpenerInNewFrame() const
{
return frame()->loader()->suppressOpenerInNewFrame();
}
void WebFrameImpl::replaceSelection(const WebString& text)
{
RefPtr<DocumentFragment> fragment = createFragmentFromText(
frame()->selection()->toNormalizedRange().get(), text);
applyCommand(ReplaceSelectionCommand::create(
frame()->document(), fragment.get(), false, true, true));
}
void WebFrameImpl::insertText(const WebString& text)
{
frame()->editor()->insertText(text, 0);
}
void WebFrameImpl::setMarkedText(
const WebString& text, unsigned location, unsigned length)
{
Editor* editor = frame()->editor();
editor->confirmComposition(text);
Vector<CompositionUnderline> decorations;
editor->setComposition(text, decorations, location, length);
}
void WebFrameImpl::unmarkText()
{
frame()->editor()->confirmCompositionWithoutDisturbingSelection();
}
bool WebFrameImpl::hasMarkedText() const
{
return frame()->editor()->hasComposition();
}
WebRange WebFrameImpl::markedRange() const
{
return frame()->editor()->compositionRange();
}
bool WebFrameImpl::executeCommand(const WebString& name)
{
ASSERT(frame());
if (name.length() <= 2)
return false;
// Since we don't have NSControl, we will convert the format of command
// string and call the function on Editor directly.
String command = name;
// Make sure the first letter is upper case.
command.replace(0, 1, command.substring(0, 1).upper());
// Remove the trailing ':' if existing.
if (command[command.length() - 1] == UChar(':'))
command = command.substring(0, command.length() - 1);
bool rv = true;
// Specially handling commands that Editor::execCommand does not directly
// support.
if (command == "DeleteToEndOfParagraph") {
Editor* editor = frame()->editor();
if (!editor->deleteWithDirection(SelectionController::FORWARD,
ParagraphBoundary,
true,
false)) {
editor->deleteWithDirection(SelectionController::FORWARD,
CharacterGranularity,
true,
false);
}
} else if (command == "Indent")
frame()->editor()->indent();
else if (command == "Outdent")
frame()->editor()->outdent();
else if (command == "DeleteBackward")
rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute();
else if (command == "DeleteForward")