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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 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 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 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 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 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 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
|
/*
* Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
* 1999 Lars Knoll <knoll@kde.org>
* 1999 Antti Koivisto <koivisto@kde.org>
* 2000 Simon Hausmann <hausmann@kde.org>
* 2000 Stefan Schimanski <1Stein@gmx.de>
* 2001 George Staikos <staikos@kde.org>
* Copyright (C) 2004-2023 Apple Inc. All rights reserved.
* Copyright (C) 2005 Alexey Proskuryakov <ap@nypop.com>
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008 Google Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "LocalFrame.h"
#include "AnimationTimelinesController.h"
#include "ApplyStyleCommand.h"
#include "BackForwardCache.h"
#include "BackForwardController.h"
#include "CSSComputedStyleDeclaration.h"
#include "CSSPropertyNames.h"
#include "CSSValuePool.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResourceLoader.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "DocumentLoader.h"
#include "DocumentType.h"
#include "Editing.h"
#include "Editor.h"
#include "EditorClient.h"
#include "ElementInlines.h"
#include "Event.h"
#include "EventHandler.h"
#include "EventNames.h"
#include "FloatQuad.h"
#include "FocusController.h"
#include "FrameDestructionObserver.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "GraphicsContext.h"
#include "GraphicsLayer.h"
#include "HTMLAttachmentElement.h"
#include "HTMLFormControlElement.h"
#include "HTMLFormElement.h"
#include "HTMLFrameElementBase.h"
#include "HTMLIFrameElement.h"
#include "HTMLNames.h"
#include "HTMLTableCellElement.h"
#include "HTMLTableRowElement.h"
#include "HitTestResult.h"
#include "ImageBuffer.h"
#include "InspectorInstrumentation.h"
#include "JSDOMWindow.h"
#include "JSNode.h"
#include "JSServiceWorkerGlobalScope.h"
#include "JSWindowProxy.h"
#include "LocalDOMWindow.h"
#include "LocalFrameLoaderClient.h"
#include "LocalFrameView.h"
#include "LocalizedStrings.h"
#include "Logging.h"
#include "Navigator.h"
#include "NodeList.h"
#include "NodeTraversal.h"
#include "Page.h"
#include "ProcessSyncClient.h"
#include "ProcessWarming.h"
#include "RemoteFrame.h"
#include "RenderLayerCompositor.h"
#include "RenderTableCell.h"
#include "RenderText.h"
#include "RenderTextControl.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ResourceMonitor.h"
#include "SVGDocument.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementTypeHelpers.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ScrollingCoordinator.h"
#include "ServiceWorkerGlobalScope.h"
#include "Settings.h"
#include "StyleProperties.h"
#include "StyleScope.h"
#include "TextNodeTraversal.h"
#include "TextResourceDecoder.h"
#include "UserContentController.h"
#include "UserContentURLPattern.h"
#include "UserGestureIndicator.h"
#include "UserScript.h"
#include "UserTypingGestureIndicator.h"
#include "VisibleUnits.h"
#include "markup.h"
#include "runtime_root.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/RegularExpression.h>
#include <wtf/HexNumber.h>
#include <wtf/RefCountedLeakCounter.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/TextStream.h>
#if ENABLE(DATA_DETECTION)
#include "DataDetectionResultsStorage.h"
#endif
#if ENABLE(CONTENT_EXTENSIONS) && USE(APPLE_INTERNAL_SDK) && __has_include(<WebKitAdditions/LocalFrameAdditions.h>)
#include <WebKitAdditions/LocalFrameAdditions.h>
#endif
#define FRAME_RELEASE_LOG(channel, fmt, ...) RELEASE_LOG(channel, "%p - Frame::" fmt, this, ##__VA_ARGS__)
#define FRAME_RELEASE_LOG_ERROR(channel, fmt, ...) RELEASE_LOG_ERROR(channel, "%p - Frame::" fmt, this, ##__VA_ARGS__)
namespace WebCore {
using namespace HTMLNames;
#if PLATFORM(IOS_FAMILY)
static const Seconds scrollFrequency { 1000_s / 60. };
#endif
DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, frameCounter, ("Frame"));
static inline float parentPageZoomFactor(LocalFrame* frame)
{
SUPPRESS_UNCOUNTED_LOCAL auto* parent = dynamicDowncast<LocalFrame>(frame->tree().parent());
if (!parent)
return 1;
return parent->pageZoomFactor();
}
static inline float parentTextZoomFactor(LocalFrame* frame)
{
SUPPRESS_UNCOUNTED_LOCAL auto* parent = dynamicDowncast<LocalFrame>(frame->tree().parent());
if (!parent)
return 1;
return parent->textZoomFactor();
}
static const LocalFrame& rootFrame(const LocalFrame& frame)
{
SUPPRESS_UNCOUNTED_LOCAL auto* parent = dynamicDowncast<LocalFrame>(frame.tree().parent());
if (parent)
return parent->rootFrame();
ASSERT(is<RemoteFrame>(frame.tree().parent()) || frame.isMainFrame());
return frame;
}
LocalFrame::LocalFrame(Page& page, ClientCreator&& clientCreator, FrameIdentifier identifier, SandboxFlags sandboxFlags, std::optional<ScrollbarMode> scrollingMode, HTMLFrameOwnerElement* ownerElement, Frame* parent, Frame* opener)
: Frame(page, identifier, FrameType::Local, ownerElement, parent, opener)
, m_loader(makeUniqueRefWithoutRefCountedCheck<FrameLoader>(*this, WTFMove(clientCreator)))
, m_script(makeUniqueRef<ScriptController>(*this))
, m_pageZoomFactor(parentPageZoomFactor(this))
, m_textZoomFactor(parentTextZoomFactor(this))
, m_rootFrame(WebCore::rootFrame(*this))
, m_sandboxFlags(sandboxFlags)
, m_eventHandler(makeUniqueRef<EventHandler>(*this))
{
ProcessWarming::initializeNames();
StaticCSSValuePool::init();
if (RefPtr localMainFrame = this->localMainFrame(); localMainFrame && parent)
localMainFrame->selfOnlyRef();
#ifndef NDEBUG
frameCounter.increment();
#endif
ASSERT(scrollingMode.has_value() ^ !!ownerElement);
m_scrollingMode = scrollingMode ? *scrollingMode : ownerElement->scrollingMode();
// Pause future ActiveDOMObjects if this frame is being created while the page is in a paused state.
if (RefPtr parent = dynamicDowncast<LocalFrame>(tree().parent()); parent && parent->activeDOMObjectsAndAnimationsSuspended())
suspendActiveDOMObjectsAndAnimations();
if (isRootFrame())
page.addRootFrame(*this);
ASSERT(isRootFrameIdentifier(frameID()) == isRootFrame());
}
void LocalFrame::init()
{
protectedLoader()->init();
}
Ref<LocalFrame> LocalFrame::createMainFrame(Page& page, ClientCreator&& clientCreator, FrameIdentifier identifier, SandboxFlags effectiveSandboxFlags, Frame* opener)
{
return adoptRef(*new LocalFrame(page, WTFMove(clientCreator), identifier, effectiveSandboxFlags, ScrollbarMode::Auto, nullptr, nullptr, opener));
}
Ref<LocalFrame> LocalFrame::createSubframe(Page& page, ClientCreator&& clientCreator, FrameIdentifier identifier, SandboxFlags effectiveSandboxFlags, HTMLFrameOwnerElement& ownerElement)
{
return adoptRef(*new LocalFrame(page, WTFMove(clientCreator), identifier, effectiveSandboxFlags, std::nullopt, &ownerElement, ownerElement.document().frame(), nullptr));
}
Ref<LocalFrame> LocalFrame::createProvisionalSubframe(Page& page, ClientCreator&& clientCreator, FrameIdentifier identifier, SandboxFlags effectiveSandboxFlags, ScrollbarMode scrollingMode, Frame& parent)
{
return adoptRef(*new LocalFrame(page, WTFMove(clientCreator), identifier, effectiveSandboxFlags, scrollingMode, nullptr, &parent, nullptr));
}
LocalFrame::~LocalFrame()
{
setView(nullptr);
Ref loader = this->loader();
if (!loader->isComplete())
loader->closeURL();
loader->clear(protectedDocument(), false);
checkedScript()->updatePlatformScriptObjects();
// FIXME: We should not be doing all this work inside the destructor
#ifndef NDEBUG
frameCounter.decrement();
#endif
disconnectOwnerElement();
while (auto* destructionObserver = m_destructionObservers.takeAny())
destructionObserver->frameDestroyed();
RefPtr localMainFrame = this->localMainFrame();
if (!isMainFrame() && localMainFrame)
localMainFrame->selfOnlyDeref();
detachFromPage();
}
RefPtr<const LocalFrame> LocalFrame::localMainFrame() const
{
return dynamicDowncast<const LocalFrame>(mainFrame());
}
RefPtr<LocalFrame> LocalFrame::localMainFrame()
{
return dynamicDowncast<LocalFrame>(mainFrame());
}
void LocalFrame::addDestructionObserver(FrameDestructionObserver& observer)
{
m_destructionObservers.add(observer);
}
void LocalFrame::removeDestructionObserver(FrameDestructionObserver& observer)
{
m_destructionObservers.remove(observer);
}
void LocalFrame::setView(RefPtr<LocalFrameView>&& view)
{
// We the custom scroll bars as early as possible to prevent m_doc->detach()
// from messing with the view such that its scroll bars won't be torn down.
// FIXME: We should revisit this.
if (RefPtr view = m_view)
view->prepareForDetach();
// Prepare for destruction now, so any unload event handlers get run and the LocalDOMWindow is
// notified. If we wait until the view is destroyed, then things won't be hooked up enough for
// these calls to work.
if (!view && m_doc && m_doc->backForwardCacheState() != Document::InBackForwardCache)
protectedDocument()->willBeRemovedFromFrame();
if (RefPtr view = m_view)
view->checkedLayoutContext()->unscheduleLayout();
m_eventHandler->clear();
RELEASE_ASSERT(!m_doc || !m_doc->hasLivingRenderTree());
m_view = WTFMove(view);
// Only one form submission is allowed per view of a part.
// Since this part may be getting reused as a result of being
// pulled from the back/forward cache, reset this flag.
protectedLoader()->resetMultipleFormSubmissionProtection();
}
Ref<Editor> LocalFrame::protectedEditor()
{
return editor();
}
Ref<const Editor> LocalFrame::protectedEditor() const
{
return editor();
}
void LocalFrame::setDocument(RefPtr<Document>&& newDocument)
{
ASSERT(!newDocument || newDocument->frame() == this);
if (m_documentIsBeingReplaced)
return;
m_documentIsBeingReplaced = true;
if (isMainFrame()) {
if (RefPtr page = this->page())
page->didChangeMainDocument(newDocument.get());
protectedLoader()->client().dispatchDidChangeMainDocument();
}
if (RefPtr previousDocument = m_doc) {
#if ENABLE(ATTACHMENT_ELEMENT)
for (Ref attachment : previousDocument->attachmentElementsByIdentifier().values())
protectedEditor()->didRemoveAttachmentElement(attachment);
#endif
if (previousDocument->backForwardCacheState() != Document::InBackForwardCache)
previousDocument->willBeRemovedFromFrame();
}
m_doc = newDocument.copyRef();
ASSERT(!m_doc || m_doc->domWindow());
ASSERT(!m_doc || m_doc->domWindow()->frame() == this);
// Don't use m_doc because it can be overwritten and we want to guarantee
// that the document is not destroyed during this function call.
if (newDocument)
newDocument->didBecomeCurrentDocumentInFrame();
#if ENABLE(ATTACHMENT_ELEMENT)
if (RefPtr document = m_doc) {
Ref editor = this->editor();
for (Ref attachment : document->attachmentElementsByIdentifier().values())
editor->didInsertAttachmentElement(attachment);
}
#endif
if (RefPtr page = this->page(); page && isMainFrame()) {
if (m_doc && !loader().stateMachine().isDisplayingInitialEmptyDocument())
page->mainFrameDidChangeToNonInitialEmptyDocument();
page->clearAXObjectCache();
}
InspectorInstrumentation::frameDocumentUpdated(*this);
#if ENABLE(WINDOW_PROXY_PROPERTY_ACCESS_NOTIFICATION)
m_accessedWindowProxyPropertiesViaOpener = { };
#endif
m_documentIsBeingReplaced = false;
}
void LocalFrame::frameDetached()
{
protectedLoader()->frameDetached();
}
bool LocalFrame::preventsParentFromBeingComplete() const
{
return !protectedLoader()->isComplete() && (!ownerElement() || !ownerElement()->isLazyLoadObserverActive());
}
void LocalFrame::changeLocation(FrameLoadRequest&& request)
{
protectedLoader()->changeLocation(WTFMove(request));
}
void LocalFrame::didFinishLoadInAnotherProcess()
{
protectedLoader()->provisionalLoadFailedInAnotherProcess();
}
void LocalFrame::invalidateContentEventRegionsIfNeeded(InvalidateContentEventRegionsReason reason)
{
if (!page() || !m_doc || !m_doc->renderView())
return;
bool needsUpdateForWheelEventHandlers = false;
bool needsUpdateForTouchActionElements = false;
bool needsUpdateForEditableElements = false;
bool needsUpdateForInteractionRegions = false;
#if ENABLE(WHEEL_EVENT_REGIONS)
needsUpdateForWheelEventHandlers = m_doc->hasWheelEventHandlers() || reason == InvalidateContentEventRegionsReason::EventHandlerChange;
#else
UNUSED_PARAM(reason);
#endif
#if ENABLE(TOUCH_ACTION_REGIONS)
// Document::mayHaveElementsWithNonAutoTouchAction never changes from true to false currently.
needsUpdateForTouchActionElements = m_doc->mayHaveElementsWithNonAutoTouchAction();
#endif
#if ENABLE(EDITABLE_REGION)
// Document::mayHaveEditableElements never changes from true to false currently.
needsUpdateForEditableElements = m_doc->mayHaveEditableElements() && page()->shouldBuildEditableRegion();
#endif
#if ENABLE(INTERACTION_REGIONS_IN_EVENT_REGION)
needsUpdateForInteractionRegions = page()->shouldBuildInteractionRegions();
#endif
if (!needsUpdateForTouchActionElements && !needsUpdateForEditableElements && !needsUpdateForWheelEventHandlers && !needsUpdateForInteractionRegions)
return;
if (!m_doc->renderView()->compositor().viewNeedsToInvalidateEventRegionOfEnclosingCompositingLayerForRepaint())
return;
if (RefPtr ownerElement = this->ownerElement())
ownerElement->protectedDocument()->invalidateEventRegionsForFrame(*ownerElement);
}
#if ENABLE(ORIENTATION_EVENTS)
void LocalFrame::orientationChanged()
{
Page::forEachDocumentFromMainFrame(*this, [newOrientation = orientation()] (Document& document) {
document.orientationChanged(newOrientation);
});
}
IntDegrees LocalFrame::orientation() const
{
if (RefPtr page = this->page())
return page->chrome().client().deviceOrientation();
return 0;
}
#endif // ENABLE(ORIENTATION_EVENTS)
static JSC::Yarr::RegularExpression createRegExpForLabels(const Vector<String>& labels)
{
// REVIEW- version of this call in FrameMac.mm caches based on the NSArray ptrs being
// the same across calls. We can't do that.
static NeverDestroyed<JSC::Yarr::RegularExpression> wordRegExp("\\w"_s);
StringBuilder pattern;
pattern.append('(');
for (unsigned i = 0, numLabels = labels.size(); i < numLabels; i++) {
auto& label = labels[i];
bool startsWithWordCharacter = false;
bool endsWithWordCharacter = false;
if (label.length()) {
StringView labelView { label };
startsWithWordCharacter = wordRegExp.get().match(labelView.left(1)) >= 0;
endsWithWordCharacter = wordRegExp.get().match(labelView.right(1)) >= 0;
}
// Search for word boundaries only if label starts/ends with "word characters".
// If we always searched for word boundaries, this wouldn't work for languages such as Japanese.
pattern.append(i ? "|"_s : ""_s, startsWithWordCharacter ? "\\b"_s : ""_s, label, endsWithWordCharacter ? "\\b"_s : ""_s);
}
pattern.append(')');
return JSC::Yarr::RegularExpression(pattern.toString(), { JSC::Yarr::Flags::IgnoreCase });
}
String LocalFrame::searchForLabelsAboveCell(const JSC::Yarr::RegularExpression& regExp, HTMLTableCellElement* cell, size_t* resultDistanceFromStartOfCell)
{
if (RefPtr aboveCell = cell->cellAbove()) {
// search within the above cell we found for a match
size_t lengthSearched = 0;
for (RefPtr textNode = TextNodeTraversal::firstWithin(*aboveCell); textNode; textNode = TextNodeTraversal::next(*textNode, aboveCell.get())) {
if (!textNode->renderer() || textNode->renderer()->style().usedVisibility() != Visibility::Visible)
continue;
// For each text chunk, run the regexp
String nodeString = textNode->data();
int pos = regExp.searchRev(nodeString);
if (pos >= 0) {
if (resultDistanceFromStartOfCell)
*resultDistanceFromStartOfCell = lengthSearched;
return nodeString.substring(pos, regExp.matchedLength());
}
lengthSearched += nodeString.length();
}
}
// Any reason in practice to search all cells in that are above cell?
if (resultDistanceFromStartOfCell)
*resultDistanceFromStartOfCell = notFound;
return String();
}
// FIXME: This should take an Element&.
String LocalFrame::searchForLabelsBeforeElement(const Vector<String>& labels, Element* element, size_t* resultDistance, bool* resultIsInCellAbove)
{
ASSERT(element);
JSC::Yarr::RegularExpression regExp = createRegExpForLabels(labels);
// We stop searching after we've seen this many chars
const unsigned int charsSearchedThreshold = 500;
// This is the absolute max we search. We allow a little more slop than
// charsSearchedThreshold, to make it more likely that we'll search whole nodes.
const unsigned int maxCharsSearched = 600;
// If the starting element is within a table, the cell that contains it
RefPtr<HTMLTableCellElement> startingTableCell;
bool searchedCellAbove = false;
if (resultDistance)
*resultDistance = notFound;
if (resultIsInCellAbove)
*resultIsInCellAbove = false;
// walk backwards in the node tree, until another element, or form, or end of tree
int unsigned lengthSearched = 0;
RefPtr<Node> n;
for (n = NodeTraversal::previous(*element); n && lengthSearched < charsSearchedThreshold; n = NodeTraversal::previous(*n)) {
// We hit another form element or the start of the form - bail out
if (is<HTMLFormElement>(*n))
break;
if (RefPtr element = dynamicDowncast<Element>(*n); element && element->isValidatedFormListedElement())
break;
if (n->hasTagName(tdTag) && !startingTableCell)
startingTableCell = downcast<HTMLTableCellElement>(n);
else if (is<HTMLTableRowElement>(*n) && startingTableCell) {
String result = searchForLabelsAboveCell(regExp, startingTableCell.get(), resultDistance);
if (!result.isEmpty()) {
if (resultIsInCellAbove)
*resultIsInCellAbove = true;
return result;
}
searchedCellAbove = true;
} else if (n->isTextNode() && n->renderer() && n->renderer()->style().usedVisibility() == Visibility::Visible) {
// For each text chunk, run the regexp
String nodeString = n->nodeValue();
// add 100 for slop, to make it more likely that we'll search whole nodes
if (lengthSearched + nodeString.length() > maxCharsSearched)
nodeString = nodeString.right(charsSearchedThreshold - lengthSearched);
int pos = regExp.searchRev(nodeString);
if (pos >= 0) {
if (resultDistance)
*resultDistance = lengthSearched;
return nodeString.substring(pos, regExp.matchedLength());
}
lengthSearched += nodeString.length();
}
}
// If we started in a cell, but bailed because we found the start of the form or the
// previous element, we still might need to search the row above us for a label.
if (startingTableCell && !searchedCellAbove) {
String result = searchForLabelsAboveCell(regExp, startingTableCell.get(), resultDistance);
if (!result.isEmpty()) {
if (resultIsInCellAbove)
*resultIsInCellAbove = true;
return result;
}
}
return String();
}
static String matchLabelsAgainstString(const Vector<String>& labels, const String& stringToMatch)
{
if (stringToMatch.isEmpty())
return String();
String mutableStringToMatch = stringToMatch;
// Make numbers and _'s in field names behave like word boundaries, e.g., "address2"
replace(mutableStringToMatch, JSC::Yarr::RegularExpression("\\d"_s), " "_s);
mutableStringToMatch = makeStringByReplacingAll(mutableStringToMatch, '_', ' ');
JSC::Yarr::RegularExpression regExp = createRegExpForLabels(labels);
// Use the largest match we can find in the whole string
int pos;
int length;
int bestPos = -1;
int bestLength = -1;
int start = 0;
do {
pos = regExp.match(mutableStringToMatch, start);
if (pos != -1) {
length = regExp.matchedLength();
if (length >= bestLength) {
bestPos = pos;
bestLength = length;
}
start = pos + 1;
}
} while (pos != -1);
if (bestPos != -1)
return mutableStringToMatch.substring(bestPos, bestLength);
return String();
}
String LocalFrame::matchLabelsAgainstElement(const Vector<String>& labels, Element* element)
{
// Match against the name element, then against the id element if no match is found for the name element.
// See 7538330 for one popular site that benefits from the id element check.
// FIXME: This code is mirrored in FrameMac.mm. It would be nice to make the Mac code call the platform-agnostic
// code, which would require converting the NSArray of NSStrings to a Vector of Strings somewhere along the way.
String resultFromNameAttribute = matchLabelsAgainstString(labels, element->getNameAttribute());
if (!resultFromNameAttribute.isEmpty())
return resultFromNameAttribute;
return matchLabelsAgainstString(labels, element->attributeWithoutSynchronization(idAttr));
}
#if PLATFORM(IOS_FAMILY)
void LocalFrame::setSelectionChangeCallbacksDisabled(bool selectionChangeCallbacksDisabled)
{
m_selectionChangeCallbacksDisabled = selectionChangeCallbacksDisabled;
}
bool LocalFrame::selectionChangeCallbacksDisabled() const
{
return m_selectionChangeCallbacksDisabled;
}
#endif // PLATFORM(IOS_FAMILY)
bool LocalFrame::requestDOMPasteAccess(DOMPasteAccessCategory pasteAccessCategory)
{
if (settings().javaScriptCanAccessClipboard() && settings().domPasteAllowed())
return true;
if (!m_doc)
return false;
if (editor().isPastingFromMenuOrKeyBinding())
return true;
if (!settings().domPasteAccessRequestsEnabled())
return false;
auto gestureToken = UserGestureIndicator::currentUserGesture();
if (!gestureToken || !gestureToken->processingUserGesture() || !gestureToken->canRequestDOMPaste())
return false;
switch (gestureToken->domPasteAccessPolicy()) {
case DOMPasteAccessPolicy::Granted:
return true;
case DOMPasteAccessPolicy::Denied:
return false;
case DOMPasteAccessPolicy::NotRequestedYet: {
auto* client = editor().client();
if (!client)
return false;
auto response = client->requestDOMPasteAccess(pasteAccessCategory, frameID(), m_doc->originIdentifierForPasteboard());
gestureToken->didRequestDOMPasteAccess(response);
switch (response) {
case DOMPasteAccessResponse::GrantedForCommand:
case DOMPasteAccessResponse::GrantedForGesture:
return true;
case DOMPasteAccessResponse::DeniedForGesture:
return false;
}
}
}
ASSERT_NOT_REACHED();
return false;
}
void LocalFrame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot shouldAdjustViewSize)
{
if (!view() || !document())
return;
RefPtr document = m_doc;
// In setting printing, we should not validate resources already cached for the document.
// See https://bugs.webkit.org/show_bug.cgi?id=43704
ResourceCacheValidationSuppressor validationSuppressor(document->cachedResourceLoader());
document->setPrinting(printing);
protectedView()->adjustMediaTypeForPrinting(printing);
// FIXME: Consider invoking Page::updateRendering or an equivalent.
document->styleScope().didChangeStyleSheetEnvironment();
document->evaluateMediaQueriesAndReportChanges();
if (!view())
return;
Ref frameView = *view();
if (shouldUsePrintingLayout())
frameView->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio, shouldAdjustViewSize);
else {
frameView->forceLayout();
if (shouldAdjustViewSize == AdjustViewSize)
frameView->adjustViewSize();
}
// Subframes of the one we're printing don't lay out to the page size.
for (RefPtr child = tree().firstChild(); child; child = child->tree().nextSibling()) {
if (RefPtr localFrame = dynamicDowncast<LocalFrame>(child.get()))
localFrame->setPrinting(printing, FloatSize(), FloatSize(), 0, shouldAdjustViewSize);
}
}
bool LocalFrame::shouldUsePrintingLayout() const
{
// Only top frame being printed should be fit to page size.
// Subframes should be constrained by parents only.
SUPPRESS_UNCOUNTED_LOCAL auto* parent = dynamicDowncast<LocalFrame>(tree().parent());
return m_doc->printing() && (!parent || !parent->m_doc->printing());
}
FloatSize LocalFrame::resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize)
{
FloatSize resultSize;
if (!contentRenderer())
return FloatSize();
if (contentRenderer()->writingMode().isHorizontal()) {
ASSERT(std::abs(originalSize.width()) > std::numeric_limits<float>::epsilon());
float ratio = originalSize.height() / originalSize.width();
resultSize.setWidth(floorf(expectedSize.width()));
resultSize.setHeight(floorf(resultSize.width() * ratio));
} else {
ASSERT(std::abs(originalSize.height()) > std::numeric_limits<float>::epsilon());
float ratio = originalSize.width() / originalSize.height();
resultSize.setHeight(floorf(expectedSize.height()));
resultSize.setWidth(floorf(resultSize.height() * ratio));
}
return resultSize;
}
void LocalFrame::injectUserScripts(UserScriptInjectionTime injectionTime)
{
if (!page())
return;
if (loader().stateMachine().creatingInitialEmptyDocument() && !settings().shouldInjectUserScriptsInInitialEmptyDocument())
return;
RefPtr page = this->page();
bool pageWasNotified = page->hasBeenNotifiedToInjectUserScripts();
page->protectedUserContentProvider()->forEachUserScript([this, protectedThis = Ref { *this }, injectionTime, pageWasNotified] (DOMWrapperWorld& world, const UserScript& script) {
if (script.injectionTime() == injectionTime) {
if (script.waitForNotificationBeforeInjecting() == WaitForNotificationBeforeInjecting::Yes && !pageWasNotified)
addUserScriptAwaitingNotification(world, script);
else
injectUserScriptImmediately(world, script);
}
});
}
void LocalFrame::injectUserScriptImmediately(DOMWrapperWorld& world, const UserScript& script)
{
Ref loader = this->loader();
#if ENABLE(APP_BOUND_DOMAINS)
if (loader->client().shouldEnableInAppBrowserPrivacyProtections()) {
if (RefPtr document = this->document())
document->addConsoleMessage(MessageSource::Security, MessageLevel::Warning, "Ignoring user script injection for non-app bound domain."_s);
FRAME_RELEASE_LOG_ERROR(Loading, "injectUserScriptImmediately: Ignoring user script injection for non app-bound domain");
return;
}
loader->client().notifyPageOfAppBoundBehavior();
#endif
RefPtr document = this->document();
if (!document)
return;
RefPtr page = document->protectedPage();
if (!page)
return;
if (script.injectedFrames() == UserContentInjectedFrames::InjectInTopFrameOnly && !isMainFrame())
return;
if (!UserContentURLPattern::matchesPatterns(document->url(), script.allowlist(), script.blocklist()))
return;
page->setHasInjectedUserScript();
loader->client().willInjectUserScript(world);
checkedScript()->evaluateInWorldIgnoringException(ScriptSourceCode(script.source(), JSC::SourceTaintedOrigin::Untainted, URL(script.url())), world);
}
void LocalFrame::addUserScriptAwaitingNotification(DOMWrapperWorld& world, const UserScript& script)
{
m_userScriptsAwaitingNotification.append({ world, makeUniqueRef<UserScript>(script) });
}
void LocalFrame::injectUserScriptsAwaitingNotification()
{
for (const auto& [world, script] : std::exchange(m_userScriptsAwaitingNotification, { }))
injectUserScriptImmediately(world, script.get());
}
RenderView* LocalFrame::contentRenderer() const
{
return document() ? document()->renderView() : nullptr;
}
LocalFrame* LocalFrame::frameForWidget(const Widget& widget)
{
SUPPRESS_UNCOUNTED_LOCAL auto* renderer = RenderWidget::find(widget);
if (renderer)
return renderer->frameOwnerElement().document().frame();
// Assume all widgets are either a FrameView or owned by a RenderWidget.
// FIXME: That assumption is not right for scroll bars!
return &downcast<LocalFrameView>(widget).frame();
}
void LocalFrame::clearTimers(LocalFrameView *view, Document *document)
{
if (!view)
return;
view->checkedLayoutContext()->unscheduleLayout();
if (CheckedPtr timelines = document->timelinesController())
timelines->suspendAnimations();
view->protectedFrame()->checkedEventHandler()->stopAutoscrollTimer();
}
void LocalFrame::clearTimers()
{
clearTimers(protectedView().get(), protectedDocument().get());
}
Ref<const FrameLoader> LocalFrame::protectedLoader() const
{
return m_loader.get();
}
Ref<FrameLoader> LocalFrame::protectedLoader()
{
return m_loader.get();
}
CheckedRef<ScriptController> LocalFrame::checkedScript()
{
return m_script.get();
}
CheckedRef<const ScriptController> LocalFrame::checkedScript() const
{
return m_script.get();
}
void LocalFrame::willDetachPage()
{
if (RefPtr parent = dynamicDowncast<LocalFrame>(tree().parent()))
parent->protectedLoader()->checkLoadComplete();
for (auto& observer : m_destructionObservers)
observer.willDetachPage();
// FIXME: It's unclear as to why this is called more than once, but it is,
// so page() could be NULL.
if (RefPtr<Page> page = this->page()) {
CheckedRef focusController = page->focusController();
if (focusController->focusedFrame() == this)
focusController->setFocusedFrame(nullptr);
}
CheckedRef script = this->script();
script->clearScriptObjects();
script->updatePlatformScriptObjects();
// We promise that the Frame is always connected to a Page while the render tree is live.
//
// The render tree can be torn down in a few different ways, but the two important ones are:
//
// - When calling Frame::setView() with a null FrameView*. This is always done before calling
// Frame::willDetachPage (this function.) Hence the assertion below.
//
// - When adding a document to the back/forward cache, the tree is torn down before instantiating
// the CachedPage+CachedFrame object tree.
ASSERT(!document() || !document()->renderView());
}
String LocalFrame::displayStringModifiedByEncoding(const String& str) const
{
return document() ? document()->displayStringModifiedByEncoding(str) : str;
}
VisiblePosition LocalFrame::visiblePositionForPoint(const IntPoint& framePoint) const
{
constexpr OptionSet<HitTestRequest::Type> hitType { HitTestRequest::Type::ReadOnly, HitTestRequest::Type::Active, HitTestRequest::Type::AllowVisibleChildFrameContentOnly };
HitTestResult result = eventHandler().hitTestResultAtPoint(framePoint, hitType);
RefPtr node = result.innerNonSharedNode();
if (!node)
return VisiblePosition();
CheckedPtr renderer = node->renderer();
if (!renderer)
return VisiblePosition();
VisiblePosition visiblePos = renderer->positionForPoint(result.localPoint(), HitTestSource::User, nullptr);
if (visiblePos.isNull())
visiblePos = firstPositionInOrBeforeNode(node.get());
return visiblePos;
}
Document* LocalFrame::documentAtPoint(const IntPoint& point)
{
if (!view())
return nullptr;
IntPoint pt = protectedView()->windowToContents(point);
HitTestResult result = HitTestResult(pt);
if (contentRenderer()) {
constexpr OptionSet<HitTestRequest::Type> hitType { HitTestRequest::Type::ReadOnly, HitTestRequest::Type::Active, HitTestRequest::Type::DisallowUserAgentShadowContent, HitTestRequest::Type::AllowChildFrameContent };
result = checkedEventHandler()->hitTestResultAtPoint(pt, hitType);
}
return result.innerNode() ? &result.innerNode()->document() : 0;
}
std::optional<SimpleRange> LocalFrame::rangeForPoint(const IntPoint& framePoint)
{
auto position = visiblePositionForPoint(framePoint);
SUPPRESS_UNCOUNTED_LOCAL auto containerText = position.deepEquivalent().containerText();
if (!containerText || !containerText->renderer() || containerText->renderer()->style().usedUserSelect() == UserSelect::None)
return std::nullopt;
if (auto previousCharacterRange = makeSimpleRange(position.previous(), position)) {
if (protectedEditor()->firstRectForRange(*previousCharacterRange).contains(framePoint))
return *previousCharacterRange;
}
if (auto nextCharacterRange = makeSimpleRange(position, position.next())) {
if (protectedEditor()->firstRectForRange(*nextCharacterRange).contains(framePoint))
return *nextCharacterRange;
}
return std::nullopt;
}
void LocalFrame::createView(const IntSize& viewportSize, const std::optional<Color>& backgroundColor, const IntSize& fixedLayoutSize, bool useFixedLayout, ScrollbarMode horizontalScrollbarMode, bool horizontalLock, ScrollbarMode verticalScrollbarMode, bool verticalLock)
{
ASSERT(page());
bool isRootFrame = this->isRootFrame();
if (isRootFrame && view())
protectedView()->setParentVisible(false);
setView(nullptr);
RefPtr<LocalFrameView> frameView;
if (isRootFrame) {
frameView = LocalFrameView::create(*this, viewportSize);
frameView->setFixedLayoutSize(fixedLayoutSize);
frameView->setUseFixedLayout(useFixedLayout);
} else
frameView = LocalFrameView::create(*this);
frameView->setScrollbarModes(horizontalScrollbarMode, verticalScrollbarMode, horizontalLock, verticalLock);
setView(frameView.copyRef());
frameView->updateBackgroundRecursively(backgroundColor);
if (isRootFrame)
frameView->setParentVisible(true);
if (CheckedPtr ownerRenderer = this->ownerRenderer())
ownerRenderer->setWidget(frameView);
protectedView()->setCanHaveScrollbars(scrollingMode() != ScrollbarMode::AlwaysOff);
}
LocalDOMWindow* LocalFrame::window() const
{
return document() ? document()->domWindow() : nullptr;
}
RefPtr<LocalDOMWindow> LocalFrame::protectedWindow() const
{
return window();
}
DOMWindow* LocalFrame::virtualWindow() const
{
return window();
}
void LocalFrame::reinitializeDocumentSecurityContext()
{
if (RefPtr document = this->document())
document->initSecurityContext();
}
void LocalFrame::disconnectView()
{
setView(nullptr);
}
FrameView* LocalFrame::virtualView() const
{
return m_view.get();
}
FrameLoaderClient& LocalFrame::loaderClient()
{
return loader().client();
}
void LocalFrame::documentURLForConsoleLog(CompletionHandler<void(const URL&)>&& completionHandler)
{
RefPtr document = this->document();
if (!document)
return completionHandler({ });
completionHandler(document->url());
}
String LocalFrame::trackedRepaintRectsAsText() const
{
if (!m_view)
return String();
return protectedView()->trackedRepaintRectsAsText();
}
void LocalFrame::setPageZoomFactor(float factor)
{
setPageAndTextZoomFactors(factor, m_textZoomFactor);
}
void LocalFrame::setTextZoomFactor(float factor)
{
setPageAndTextZoomFactors(m_pageZoomFactor, factor);
}
void LocalFrame::setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor)
{
if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
return;
RefPtr page = this->page();
if (!page)
return;
RefPtr document = this->document();
if (!document)
return;
protectedEditor()->dismissCorrectionPanelAsIgnored();
// Respect SVGs zoomAndPan="disabled" property in standalone SVG documents.
// FIXME: How to handle compound documents + zoomAndPan="disabled"? Needs SVG WG clarification.
if (RefPtr svgDocument = dynamicDowncast<SVGDocument>(*document); svgDocument && !svgDocument->zoomAndPanEnabled())
return;
std::optional<ScrollPosition> scrollPositionAfterZoomed;
if (m_pageZoomFactor != pageZoomFactor) {
// Compute the scroll position with scale after zooming to stay the same position in the content.
if (RefPtr view = this->view()) {
scrollPositionAfterZoomed = view->scrollPosition();
scrollPositionAfterZoomed->scale(pageZoomFactor / m_pageZoomFactor);
}
}
m_pageZoomFactor = pageZoomFactor;
m_textZoomFactor = textZoomFactor;
document->resolveStyle(Document::ResolveStyleType::Rebuild);
for (RefPtr child = tree().firstChild(); child; child = child->tree().nextSibling()) {
if (RefPtr localFrame = dynamicDowncast<LocalFrame>(child.get()))
localFrame->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
}
if (RefPtr view = this->view()) {
if (document->renderView() && document->renderView()->needsLayout() && view->didFirstLayout())
view->checkedLayoutContext()->layout();
// Scrolling to the calculated position must be done after the layout.
if (scrollPositionAfterZoomed)
view->setScrollPosition(scrollPositionAfterZoomed.value());
}
}
float LocalFrame::frameScaleFactor() const
{
RefPtr page = this->page();
// Main frame is scaled with respect to he container but inner frames are not scaled with respect to the main frame.
if (!page || !isMainFrame())
return 1;
if (page->delegatesScaling())
return 1;
return page->pageScaleFactor();
}
void LocalFrame::suspendActiveDOMObjectsAndAnimations()
{
bool wasSuspended = activeDOMObjectsAndAnimationsSuspended();
m_activeDOMObjectsAndAnimationsSuspendedCount++;
if (wasSuspended)
return;
// FIXME: Suspend/resume calls will not match if the frame is navigated, and gets a new document.
clearTimers(); // Suspends animations and pending relayouts.
if (RefPtr document = m_doc)
document->suspendScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
}
void LocalFrame::resumeActiveDOMObjectsAndAnimations()
{
if (!activeDOMObjectsAndAnimationsSuspended())
return;
m_activeDOMObjectsAndAnimationsSuspendedCount--;
if (activeDOMObjectsAndAnimationsSuspended())
return;
if (!m_doc)
return;
Ref document = *m_doc;
// FIXME: Suspend/resume calls will not match if the frame is navigated, and gets a new document.
document->resumeScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
// Frame::clearTimers() suspended animations and pending relayouts.
if (CheckedPtr timelines = document->timelinesController())
timelines->resumeAnimations();
if (RefPtr view = m_view)
view->checkedLayoutContext()->scheduleLayout();
}
void LocalFrame::deviceOrPageScaleFactorChanged()
{
for (RefPtr child = tree().firstChild(); child; child = child->tree().nextSibling()) {
if (RefPtr localFrame = dynamicDowncast<LocalFrame>(child.get()))
localFrame->deviceOrPageScaleFactorChanged();
}
if (CheckedPtr root = contentRenderer())
root->compositor().deviceOrPageScaleFactorChanged();
}
void LocalFrame::dropChildren()
{
ASSERT(isMainFrame());
while (RefPtr child = tree().firstChild())
tree().removeChild(*child);
}
FloatSize LocalFrame::screenSize() const
{
if (!m_overrideScreenSize.isEmpty())
return m_overrideScreenSize;
auto defaultSize = screenRect(protectedView().get()).size();
RefPtr document = this->document();
if (!document)
return defaultSize;
RefPtr page = this->page();
if (!page)
return defaultSize;
if (page->shouldApplyScreenFingerprintingProtections(*document))
return page->chrome().client().screenSizeForFingerprintingProtections(*this, defaultSize);
return defaultSize;
}
void LocalFrame::setOverrideScreenSize(FloatSize&& screenSize)
{
if (m_overrideScreenSize == screenSize)
return;
m_overrideScreenSize = WTFMove(screenSize);
if (RefPtr document = this->document())
document->updateViewportArguments();
}
void LocalFrame::selfOnlyRef()
{
ASSERT(isMainFrame());
if (m_selfOnlyRefCount++)
return;
ref();
}
void LocalFrame::selfOnlyDeref()
{
ASSERT(isMainFrame());
ASSERT(m_selfOnlyRefCount);
if (--m_selfOnlyRefCount)
return;
if (hasOneRef())
dropChildren();
deref();
}
String LocalFrame::debugDescription() const
{
StringBuilder builder;
builder.append("Frame 0x"_s, hex(reinterpret_cast<uintptr_t>(this), Lowercase));
if (isMainFrame())
builder.append(" (main frame)"_s);
if (RefPtr document = this->document())
builder.append(' ', document->documentURI());
return builder.toString();
}
TextStream& operator<<(TextStream& ts, const LocalFrame& frame)
{
ts << frame.debugDescription();
return ts;
}
void LocalFrame::resetScript()
{
ASSERT(windowProxy().frame() == this);
windowProxy().detachFromFrame();
resetWindowProxy();
m_script = makeUniqueRef<ScriptController>(*this);
}
LocalFrame* LocalFrame::fromJSContext(JSContextRef context)
{
JSC::JSGlobalObject* globalObjectObj = toJS(context);
if (auto* window = JSC::jsDynamicCast<JSDOMWindow*>(globalObjectObj))
return dynamicDowncast<LocalFrame>(window->wrapped().frame());
if (auto* serviceWorkerGlobalScope = JSC::jsDynamicCast<JSServiceWorkerGlobalScope*>(globalObjectObj))
return serviceWorkerGlobalScope->wrapped().serviceWorkerPage() ? dynamicDowncast<LocalFrame>(serviceWorkerGlobalScope->wrapped().serviceWorkerPage()->mainFrame()) : nullptr;
return nullptr;
}
LocalFrame* LocalFrame::contentFrameFromWindowOrFrameElement(JSContextRef context, JSValueRef valueRef)
{
ASSERT(context);
ASSERT(valueRef);
JSC::JSGlobalObject* globalObject = toJS(context);
JSC::JSValue value = toJS(globalObject, valueRef);
if (RefPtr window = JSDOMWindow::toWrapped(globalObject->vm(), value))
return dynamicDowncast<LocalFrame>(window->frame());
auto* jsNode = JSC::jsDynamicCast<JSNode*>(value);
if (!jsNode)
return nullptr;
RefPtr frameOwner = dynamicDowncast<HTMLFrameOwnerElement>(jsNode->wrapped());
return frameOwner ? dynamicDowncast<LocalFrame>(frameOwner->contentFrame()) : nullptr;
}
CheckedRef<EventHandler> LocalFrame::checkedEventHandler()
{
return m_eventHandler.get();
}
CheckedRef<const EventHandler> LocalFrame::checkedEventHandler() const
{
return m_eventHandler.get();
}
void LocalFrame::documentURLOrOriginDidChange()
{
if (!isMainFrame())
return;
RefPtr page = this->protectedPage();
RefPtr document = this->protectedDocument();
if (page && document)
page->setMainFrameURLAndOrigin(document->url(), document->protectedSecurityOrigin());
}
#if ENABLE(DATA_DETECTION)
DataDetectionResultsStorage& LocalFrame::dataDetectionResults()
{
if (!m_dataDetectionResults)
m_dataDetectionResults = makeUnique<DataDetectionResultsStorage>();
return *m_dataDetectionResults;
}
#endif
void LocalFrame::frameWasDisconnectedFromOwner() const
{
if (!m_doc)
return;
if (RefPtr window = m_doc->domWindow())
window->willDetachDocumentFromFrame();
protectedDocument()->detachFromFrame();
}
CheckedRef<FrameSelection> LocalFrame::checkedSelection() const
{
return document()->selection();
}
void LocalFrame::storageAccessExceptionReceivedForDomain(const RegistrableDomain& domain)
{
m_storageAccessExceptionDomains.add(domain);
}
bool LocalFrame::requestSkipUserActivationCheckForStorageAccess(const RegistrableDomain& domain)
{
auto iter = m_storageAccessExceptionDomains.find(domain);
if (iter == m_storageAccessExceptionDomains.end())
return false;
// We only allow the domain to skip check once.
m_storageAccessExceptionDomains.remove(iter);
return true;
}
#if ENABLE(WINDOW_PROXY_PROPERTY_ACCESS_NOTIFICATION)
void LocalFrame::didAccessWindowProxyPropertyViaOpener(WindowProxyProperty property)
{
// FIXME: until we support restricted openers, report all property accesses as "other" to reduce
// the number of events logged.
property = WindowProxyProperty::Other;
if (m_accessedWindowProxyPropertiesViaOpener.contains(property))
return;
auto origin = SecurityOriginData::fromFrame(this);
if (origin.isNull() || origin.isOpaque())
return;
if (!opener() || !opener()->page())
return;
auto openerMainFrameOrigin = opener()->page()->mainFrameOrigin().data();
if (openerMainFrameOrigin.isNull() || openerMainFrameOrigin.isOpaque())
return;
auto site = RegistrableDomain(origin);
auto openerMainFrameSite = RegistrableDomain(openerMainFrameOrigin);
if (site == openerMainFrameSite)
return;
m_accessedWindowProxyPropertiesViaOpener.add(property);
protectedLoader()->client().didAccessWindowProxyPropertyViaOpener(WTFMove(openerMainFrameOrigin), property);
}
#endif
String LocalFrame::customUserAgent() const
{
if (RefPtr documentLoader = loader().activeDocumentLoader())
return documentLoader->customUserAgent();
return { };
}
String LocalFrame::customUserAgentAsSiteSpecificQuirks() const
{
if (RefPtr documentLoader = loader().activeDocumentLoader())
return documentLoader->customUserAgentAsSiteSpecificQuirks();
return { };
}
String LocalFrame::customNavigatorPlatform() const
{
if (RefPtr documentLoader = loader().activeDocumentLoader())
return documentLoader->customNavigatorPlatform();
return { };
}
OptionSet<AdvancedPrivacyProtections> LocalFrame::advancedPrivacyProtections() const
{
if (auto* documentLoader = loader().activeDocumentLoader())
return documentLoader->advancedPrivacyProtections();
return { };
}
SandboxFlags LocalFrame::effectiveSandboxFlags() const
{
auto effectiveSandboxFlags = m_sandboxFlags;
if (RefPtr document = this->document())
effectiveSandboxFlags.add(document->sandboxFlags());
return effectiveSandboxFlags;
}
void LocalFrame::updateSandboxFlags(SandboxFlags flags, NotifyUIProcess notifyUIProcess)
{
Frame::updateSandboxFlags(flags, notifyUIProcess);
m_sandboxFlags = flags;
}
void LocalFrame::updateScrollingMode()
{
if (!ownerElement())
return;
m_scrollingMode = ownerElement()->scrollingMode();
if (RefPtr view = this->view())
view->setCanHaveScrollbars(m_scrollingMode != ScrollbarMode::AlwaysOff);
}
void LocalFrame::setScrollingMode(ScrollbarMode scrollingMode)
{
m_scrollingMode = scrollingMode;
if (RefPtr view = this->view())
view->setCanHaveScrollbars(m_scrollingMode != ScrollbarMode::AlwaysOff);
}
#if ENABLE(CONTENT_EXTENSIONS)
static String generateResourceMonitorErrorHTML(OptionSet<ColorScheme> colorScheme)
{
#if PLATFORM(COCOA) && HAVE(CUSTOM_IFRAME_UNLOADING_HTML)
#if HAVE(CUSTOM_IFRAME_UNLOADING_HTML_WITH_COLOR_SCHEME)
return generateResourceMonitorErrorHTMLForCocoa(colorScheme);
#else
UNUSED_PARAM(colorScheme);
return generateResourceMonitorErrorHTMLForCocoa();
#endif
#else
constexpr auto lightAndDarkColorScheme = ":root { color-scheme: light dark } "_s;
constexpr auto darkOnlyColorScheme = ":root { color-scheme: only dark } "_s;
constexpr auto lightStyle = "p { color: black } "_s;
constexpr auto darkStyle = "p { color: white } "_s;
constexpr auto empty = ""_s;
bool needDarkStyle = colorScheme.contains(ColorScheme::Dark);
bool needLightStyle = !needDarkStyle || colorScheme.contains(ColorScheme::Light);
bool conditionalStyle = needDarkStyle && needLightStyle;
const auto& colorSchemeStyle = conditionalStyle ? lightAndDarkColorScheme : needDarkStyle ? darkOnlyColorScheme : empty;
const auto& darkStyleOpen = conditionalStyle ? "@media (prefers-color-scheme: dark) { "_s : empty;
const auto& darkStyleClose = conditionalStyle ? "} "_s : empty;
return makeString(
"<style> body { background-color: gray }"_s,
colorSchemeStyle,
lightStyle,
darkStyleOpen,
(needDarkStyle ? darkStyle : empty),
darkStyleClose,
"</style><p>"_s,
WEB_UI_STRING("This frame is hidden for using too many system resources.", "Description HTML for frame unloaded by ResourceMonitor"),
"</p>"_s
);
#endif
}
void LocalFrame::showResourceMonitoringError()
{
RefPtr iframeElement = dynamicDowncast<HTMLIFrameElement>(ownerElement());
RefPtr document = this->document();
if (!iframeElement || !document)
return;
URL url;
URL mainFrameURL;
if (document)
url = document->url();
if (RefPtr page = protectedPage())
mainFrameURL = page->mainFrameURL();
FRAME_RELEASE_LOG(ResourceMonitoring, "Detected excessive network usage in frame at %" SENSITIVE_LOG_STRING " and main frame at %" SENSITIVE_LOG_STRING ": unloading", url.isValid() ? url.string().utf8().data() : "invalid", mainFrameURL.isValid() ? mainFrameURL.string().utf8().data() : "invalid");
document->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Error, makeString("Frame was unloaded because its network usage exceeded the limit: "_s, ResourceMonitorChecker::singleton().networkUsageThreshold(), " bytes, url="_s, url.string()));
for (RefPtr<Frame> frame = this; frame; frame = frame->tree().traverseNext()) {
if (RefPtr localFrame = dynamicDowncast<LocalFrame>(frame)) {
if (RefPtr window = localFrame->window())
window->removeAllEventListeners();
}
}
OptionSet<ColorScheme> colorScheme { ColorScheme::Light };
#if ENABLE(DARK_MODE_CSS)
if (CheckedPtr style = iframeElement->existingComputedStyle())
colorScheme = document->resolvedColorScheme(style.get());
#endif
iframeElement->setSrcdoc(generateResourceMonitorErrorHTML(colorScheme));
}
void LocalFrame::reportResourceMonitoringWarning()
{
URL url;
URL mainFrameURL;
if (RefPtr document = protectedDocument())
url = document->url();
if (RefPtr page = protectedPage())
mainFrameURL = page->mainFrameURL();
FRAME_RELEASE_LOG(ResourceMonitoring, "Detected excessive network usage in frame at %" SENSITIVE_LOG_STRING " and main frame at %" SENSITIVE_LOG_STRING ": not unloading due to global limits", url.isValid() ? url.string().utf8().data() : "invalid", mainFrameURL.isValid() ? mainFrameURL.string().utf8().data() : "invalid");
if (RefPtr document = this->document())
document->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Warning, "Frame's network usage exceeded the limit."_s);
}
#endif
} // namespace WebCore
#undef FRAME_RELEASE_LOG_ERROR
|