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
|
/*
* Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
*
* 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 "core/html/HTMLCanvasElement.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/HTMLNames.h"
#include "core/InputTypeNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/TaskRunnerHelper.h"
#include "core/fileapi/File.h"
#include "core/frame/ImageBitmap.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLSelectElement.h"
#include "core/html/ImageData.h"
#include "core/html/canvas/CanvasAsyncBlobCreator.h"
#include "core/html/canvas/CanvasContextCreationAttributes.h"
#include "core/html/canvas/CanvasFontCache.h"
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/canvas/CanvasRenderingContextFactory.h"
#include "core/imagebitmap/ImageBitmapOptions.h"
#include "core/layout/HitTestCanvasResult.h"
#include "core/layout/LayoutHTMLCanvas.h"
#include "core/layout/api/LayoutViewItem.h"
#include "core/layout/compositing/PaintLayerCompositor.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/PaintTiming.h"
#include "platform/Histogram.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/graphics/Canvas2DImageBufferSurface.h"
#include "platform/graphics/CanvasMetrics.h"
#include "platform/graphics/ExpensiveCanvasHeuristicParameters.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/RecordingImageBufferSurface.h"
#include "platform/graphics/StaticBitmapImage.h"
#include "platform/graphics/UnacceleratedImageBufferSurface.h"
#include "platform/graphics/gpu/AcceleratedImageBufferSurface.h"
#include "platform/image-encoders/ImageEncoderUtils.h"
#include "platform/transforms/AffineTransform.h"
#include "public/platform/Platform.h"
#include "public/platform/WebTraceLocation.h"
#include "wtf/CheckedNumeric.h"
#include "wtf/PtrUtil.h"
#include <math.h>
#include <memory>
#include <v8.h>
namespace blink {
using namespace HTMLNames;
namespace {
// These values come from the WhatWG spec.
const int DefaultWidth = 300;
const int DefaultHeight = 150;
#if OS(ANDROID)
// We estimate that the max limit for android phones is a quarter of that for
// desktops based on local experimental results on Android One.
const int MaxGlobalAcceleratedImageBufferCount = 25;
#else
const int MaxGlobalAcceleratedImageBufferCount = 100;
#endif
// We estimate the max limit of GPU allocated memory for canvases before Chrome
// becomes laggy by setting the total allocated memory for accelerated canvases
// to be equivalent to memory used by 100 accelerated canvases, each has a size
// of 1000*500 and 2d context.
// Each such canvas occupies 4000000 = 1000 * 500 * 2 * 4 bytes, where 2 is the
// gpuBufferCount in ImageBuffer::updateGPUMemoryUsage() and 4 means four bytes
// per pixel per buffer.
const int MaxGlobalGPUMemoryUsage =
4000000 * MaxGlobalAcceleratedImageBufferCount;
// A default value of quality argument for toDataURL and toBlob
// It is in an invalid range (outside 0.0 - 1.0) so that it will not be
// misinterpreted as a user-input value
const int UndefinedQualityValue = -1.0;
sk_sp<SkImage> createTransparentSkImage(const IntSize& size) {
if (!ImageBuffer::canCreateImageBuffer(size))
return nullptr;
sk_sp<SkSurface> surface =
SkSurface::MakeRasterN32Premul(size.width(), size.height());
return surface ? surface->makeImageSnapshot() : nullptr;
}
PassRefPtr<Image> createTransparentImage(const IntSize& size) {
sk_sp<SkImage> image = createTransparentSkImage(size);
return image ? StaticBitmapImage::create(image) : nullptr;
}
} // namespace
inline HTMLCanvasElement::HTMLCanvasElement(Document& document)
: HTMLElement(canvasTag, document),
ContextLifecycleObserver(&document),
PageVisibilityObserver(document.page()),
m_size(DefaultWidth, DefaultHeight),
m_context(this, nullptr),
m_ignoreReset(false),
m_externallyAllocatedMemory(0),
m_originClean(true),
m_didFailToCreateImageBuffer(false),
m_imageBufferIsClear(false),
m_numFramesSinceLastRenderingModeSwitch(0),
m_pendingRenderingModeSwitch(false) {
CanvasMetrics::countCanvasContextUsage(CanvasMetrics::CanvasCreated);
UseCounter::count(document, UseCounter::HTMLCanvasElement);
}
DEFINE_NODE_FACTORY(HTMLCanvasElement)
HTMLCanvasElement::~HTMLCanvasElement() {
v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
-m_externallyAllocatedMemory);
}
void HTMLCanvasElement::dispose() {
if (placeholderFrame())
releasePlaceholderFrame();
if (m_context) {
m_context->detachCanvas();
m_context = nullptr;
}
if (m_imageBuffer) {
m_imageBuffer->setClient(nullptr);
m_imageBuffer = nullptr;
}
}
void HTMLCanvasElement::parseAttribute(
const AttributeModificationParams& params) {
if (params.name == widthAttr || params.name == heightAttr)
reset();
HTMLElement::parseAttribute(params);
}
LayoutObject* HTMLCanvasElement::createLayoutObject(
const ComputedStyle& style) {
LocalFrame* frame = document().frame();
if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
return new LayoutHTMLCanvas(this);
return HTMLElement::createLayoutObject(style);
}
Node::InsertionNotificationRequest HTMLCanvasElement::insertedInto(
ContainerNode* node) {
setIsInCanvasSubtree(true);
return HTMLElement::insertedInto(node);
}
void HTMLCanvasElement::setHeight(int value, ExceptionState& exceptionState) {
setIntegralAttribute(heightAttr, value);
}
void HTMLCanvasElement::setWidth(int value, ExceptionState& exceptionState) {
setIntegralAttribute(widthAttr, value);
}
void HTMLCanvasElement::setSize(const IntSize& newSize) {
if (newSize == size())
return;
m_ignoreReset = true;
setIntegralAttribute(widthAttr, newSize.width());
setIntegralAttribute(heightAttr, newSize.height());
m_ignoreReset = false;
reset();
}
HTMLCanvasElement::ContextFactoryVector&
HTMLCanvasElement::renderingContextFactories() {
DCHECK(isMainThread());
DEFINE_STATIC_LOCAL(ContextFactoryVector, s_contextFactories,
(CanvasRenderingContext::ContextTypeCount));
return s_contextFactories;
}
CanvasRenderingContextFactory* HTMLCanvasElement::getRenderingContextFactory(
int type) {
DCHECK(type < CanvasRenderingContext::ContextTypeCount);
return renderingContextFactories()[type].get();
}
void HTMLCanvasElement::registerRenderingContextFactory(
std::unique_ptr<CanvasRenderingContextFactory> renderingContextFactory) {
CanvasRenderingContext::ContextType type =
renderingContextFactory->getContextType();
DCHECK(type < CanvasRenderingContext::ContextTypeCount);
DCHECK(!renderingContextFactories()[type]);
renderingContextFactories()[type] = std::move(renderingContextFactory);
}
CanvasRenderingContext* HTMLCanvasElement::getCanvasRenderingContext(
const String& type,
const CanvasContextCreationAttributes& attributes) {
CanvasRenderingContext::ContextType contextType =
CanvasRenderingContext::contextTypeFromId(type);
// Unknown type.
if (contextType == CanvasRenderingContext::ContextTypeCount)
return nullptr;
// Log the aliased context type used.
if (!m_context) {
DEFINE_STATIC_LOCAL(
EnumerationHistogram, contextTypeHistogram,
("Canvas.ContextType", CanvasRenderingContext::ContextTypeCount));
contextTypeHistogram.count(contextType);
}
contextType = CanvasRenderingContext::resolveContextTypeAliases(contextType);
CanvasRenderingContextFactory* factory =
getRenderingContextFactory(contextType);
if (!factory)
return nullptr;
// FIXME - The code depends on the context not going away once created, to
// prevent JS from seeing a dangling pointer. So for now we will disallow the
// context from being changed once it is created.
if (m_context) {
if (m_context->getContextType() == contextType)
return m_context.get();
factory->onError(this,
"Canvas has an existing context of a different type");
return nullptr;
}
m_context = factory->create(this, attributes, document());
if (!m_context)
return nullptr;
if (m_context->is3d()) {
updateExternallyAllocatedMemory();
}
LayoutObject* layoutObject = this->layoutObject();
if (layoutObject && m_context->is2d() &&
!m_context->creationAttributes().alpha()) {
// In the alpha false case, canvas is initially opaque even though there is
// no ImageBuffer, so we need to trigger an invalidation.
didDraw(FloatRect(0, 0, size().width(), size().height()));
}
setNeedsCompositingUpdate();
return m_context.get();
}
bool HTMLCanvasElement::shouldBeDirectComposited() const {
return (m_context && m_context->isAccelerated()) ||
(hasImageBuffer() && buffer()->isExpensiveToPaint()) ||
(!!m_surfaceLayerBridge);
}
bool HTMLCanvasElement::isPaintable() const {
return (m_context && m_context->isPaintable()) ||
ImageBuffer::canCreateImageBuffer(size());
}
bool HTMLCanvasElement::isAccelerated() const {
return m_context && m_context->isAccelerated();
}
void HTMLCanvasElement::didDraw(const FloatRect& rect) {
if (rect.isEmpty())
return;
m_imageBufferIsClear = false;
clearCopiedImage();
if (layoutObject())
layoutObject()->setMayNeedPaintInvalidation();
if (m_context && m_context->is2d() && m_context->shouldAntialias() &&
page() && page()->deviceScaleFactor() > 1.0f) {
FloatRect inflatedRect = rect;
inflatedRect.inflate(1);
m_dirtyRect.unite(inflatedRect);
} else {
m_dirtyRect.unite(rect);
}
if (m_context && m_context->is2d() && hasImageBuffer())
buffer()->didDraw(rect);
}
void HTMLCanvasElement::didFinalizeFrame() {
notifyListenersCanvasChanged();
if (m_dirtyRect.isEmpty())
return;
// Propagate the m_dirtyRect accumulated so far to the compositor
// before restarting with a blank dirty rect.
FloatRect srcRect(0, 0, size().width(), size().height());
LayoutBox* ro = layoutBox();
// Canvas content updates do not need to be propagated as
// paint invalidations if the canvas is accelerated, since
// the canvas contents are sent separately through a texture layer.
if (ro && (!m_context || !m_context->isAccelerated())) {
// If ro->contentBoxRect() is larger than srcRect the canvas's image is
// being stretched, so we need to account for color bleeding caused by the
// interpollation filter.
if (ro->contentBoxRect().width() > srcRect.width() ||
ro->contentBoxRect().height() > srcRect.height()) {
m_dirtyRect.inflate(0.5);
}
m_dirtyRect.intersect(srcRect);
LayoutRect mappedDirtyRect(enclosingIntRect(
mapRect(m_dirtyRect, srcRect, FloatRect(ro->contentBoxRect()))));
// For querying PaintLayer::compositingState()
// FIXME: is this invalidation using the correct compositing state?
DisableCompositingQueryAsserts disabler;
ro->invalidatePaintRectangle(mappedDirtyRect);
}
m_dirtyRect = FloatRect();
m_numFramesSinceLastRenderingModeSwitch++;
if (RuntimeEnabledFeatures::
enableCanvas2dDynamicRenderingModeSwitchingEnabled() &&
!RuntimeEnabledFeatures::canvas2dFixedRenderingModeEnabled()) {
if (m_context->is2d() && hasImageBuffer() && buffer()->isAccelerated() &&
m_numFramesSinceLastRenderingModeSwitch >=
ExpensiveCanvasHeuristicParameters::MinFramesBeforeSwitch &&
!m_pendingRenderingModeSwitch) {
if (!m_context->isAccelerationOptimalForCanvasContent()) {
// The switch must be done asynchronously in order to avoid switching
// during the paint invalidation step.
Platform::current()->currentThread()->getWebTaskRunner()->postTask(
BLINK_FROM_HERE,
WTF::bind(
[](WeakPtr<ImageBuffer> buffer) {
if (buffer) {
buffer->disableAcceleration();
}
},
m_imageBuffer->m_weakPtrFactory.createWeakPtr()));
m_numFramesSinceLastRenderingModeSwitch = 0;
m_pendingRenderingModeSwitch = true;
}
}
}
if (m_pendingRenderingModeSwitch && buffer() && !buffer()->isAccelerated()) {
m_pendingRenderingModeSwitch = false;
}
m_context->incrementFrameCount();
}
void HTMLCanvasElement::didDisableAcceleration() {
// We must force a paint invalidation on the canvas even if it's
// content did not change because it layer was destroyed.
didDraw(FloatRect(0, 0, size().width(), size().height()));
}
void HTMLCanvasElement::restoreCanvasMatrixClipStack(SkCanvas* canvas) const {
if (m_context)
m_context->restoreCanvasMatrixClipStack(canvas);
}
void HTMLCanvasElement::doDeferredPaintInvalidation() {
DCHECK(!m_dirtyRect.isEmpty());
if (!m_context->is2d()) {
didFinalizeFrame();
} else {
FloatRect srcRect(0, 0, size().width(), size().height());
m_dirtyRect.intersect(srcRect);
LayoutBox* lb = layoutBox();
FloatRect invalidationRect;
if (lb) {
FloatRect mappedDirtyRect =
mapRect(m_dirtyRect, srcRect, FloatRect(lb->contentBoxRect()));
if (m_context->isAccelerated()) {
// Accelerated 2D canvases need the dirty rect to be expressed relative
// to the content box, as opposed to the layout box.
mappedDirtyRect.move(-lb->contentBoxOffset());
}
invalidationRect = mappedDirtyRect;
} else {
invalidationRect = m_dirtyRect;
}
if (hasImageBuffer()) {
m_imageBuffer->finalizeFrame(invalidationRect);
} else {
didFinalizeFrame();
}
}
DCHECK(m_dirtyRect.isEmpty());
}
void HTMLCanvasElement::reset() {
if (m_ignoreReset)
return;
m_dirtyRect = FloatRect();
bool ok;
bool hadImageBuffer = hasImageBuffer();
int w = getAttribute(widthAttr).toInt(&ok);
if (!ok || w < 0)
w = DefaultWidth;
int h = getAttribute(heightAttr).toInt(&ok);
if (!ok || h < 0)
h = DefaultHeight;
if (m_context && m_context->is2d())
m_context->reset();
IntSize oldSize = size();
IntSize newSize(w, h);
// If the size of an existing buffer matches, we can just clear it instead of
// reallocating. This optimization is only done for 2D canvases for now.
if (hadImageBuffer && oldSize == newSize && m_context && m_context->is2d() &&
!buffer()->isRecording()) {
if (!m_imageBufferIsClear) {
m_imageBufferIsClear = true;
m_context->clearRect(0, 0, width(), height());
}
return;
}
setSurfaceSize(newSize);
if (m_context && m_context->is3d() && oldSize != size())
m_context->reshape(width(), height());
if (LayoutObject* layoutObject = this->layoutObject()) {
if (layoutObject->isCanvas()) {
if (oldSize != size()) {
toLayoutHTMLCanvas(layoutObject)->canvasSizeChanged();
if (layoutBox() && layoutBox()->hasAcceleratedCompositing())
layoutBox()->contentChanged(CanvasChanged);
}
if (hadImageBuffer)
layoutObject->setShouldDoFullPaintInvalidation();
}
}
}
bool HTMLCanvasElement::paintsIntoCanvasBuffer() const {
if (placeholderFrame())
return false;
DCHECK(m_context);
if (!m_context->isAccelerated())
return true;
if (layoutBox() && layoutBox()->hasAcceleratedCompositing())
return false;
return true;
}
void HTMLCanvasElement::notifyListenersCanvasChanged() {
if (m_listeners.size() == 0)
return;
if (!originClean()) {
m_listeners.clear();
return;
}
bool listenerNeedsNewFrameCapture = false;
for (const CanvasDrawListener* listener : m_listeners) {
if (listener->needsNewFrame()) {
listenerNeedsNewFrameCapture = true;
}
}
if (listenerNeedsNewFrameCapture) {
SourceImageStatus status;
RefPtr<Image> sourceImage = getSourceImageForCanvas(
&status, PreferNoAcceleration, SnapshotReasonCanvasListenerCapture,
FloatSize());
if (status != NormalSourceImageStatus)
return;
// TODO(ccameron): Canvas should produce sRGB images.
// https://crbug.com/672299
sk_sp<SkImage> image = sourceImage->imageForCurrentFrame(
ColorBehavior::transformToGlobalTarget());
for (CanvasDrawListener* listener : m_listeners) {
if (listener->needsNewFrame()) {
listener->sendNewFrame(image);
}
}
}
}
void HTMLCanvasElement::paint(GraphicsContext& context, const LayoutRect& r) {
// FIXME: crbug.com/438240; there is a bug with the new CSS blending and
// compositing feature.
if (!m_context && !placeholderFrame())
return;
const ComputedStyle* style = ensureComputedStyle();
SkFilterQuality filterQuality =
(style && style->imageRendering() == ImageRenderingPixelated)
? kNone_SkFilterQuality
: kLow_SkFilterQuality;
if (is3D()) {
m_context->setFilterQuality(filterQuality);
} else if (hasImageBuffer()) {
m_imageBuffer->setFilterQuality(filterQuality);
}
if (hasImageBuffer() && !m_imageBufferIsClear)
PaintTiming::from(document()).markFirstContentfulPaint();
if (!paintsIntoCanvasBuffer() && !document().printing())
return;
if (placeholderFrame()) {
DCHECK(document().printing());
context.drawImage(placeholderFrame().get(), pixelSnappedIntRect(r));
return;
}
// TODO(junov): Paint is currently only implemented by ImageBitmap contexts.
// We could improve the abstraction by making all context types paint
// themselves (implement paint()).
if (m_context->paint(context, pixelSnappedIntRect(r)))
return;
m_context->paintRenderingResultsToCanvas(FrontBuffer);
if (hasImageBuffer()) {
if (!context.contextDisabled()) {
SkBlendMode compositeOperator =
!m_context || m_context->creationAttributes().alpha()
? SkBlendMode::kSrcOver
: SkBlendMode::kSrc;
buffer()->draw(context, pixelSnappedIntRect(r), 0, compositeOperator);
}
} else {
// When alpha is false, we should draw to opaque black.
if (!m_context->creationAttributes().alpha())
context.fillRect(FloatRect(r), Color(0, 0, 0));
}
if (is3D() && paintsIntoCanvasBuffer())
m_context->markLayerComposited();
}
bool HTMLCanvasElement::is3D() const {
return m_context && m_context->is3d();
}
bool HTMLCanvasElement::isAnimated2D() const {
return m_context && m_context->is2d() && hasImageBuffer() &&
m_imageBuffer->wasDrawnToAfterSnapshot();
}
void HTMLCanvasElement::setSurfaceSize(const IntSize& size) {
m_size = size;
m_didFailToCreateImageBuffer = false;
discardImageBuffer();
clearCopiedImage();
if (m_context && m_context->is2d() && m_context->isContextLost()) {
m_context->didSetSurfaceSize();
}
}
const AtomicString HTMLCanvasElement::imageSourceURL() const {
return AtomicString(
toDataURLInternal(ImageEncoderUtils::DefaultMimeType, 0, FrontBuffer));
}
void HTMLCanvasElement::prepareSurfaceForPaintingIfNeeded() const {
DCHECK(m_context &&
m_context->is2d()); // This function is called by the 2d context
if (buffer())
m_imageBuffer->prepareSurfaceForPaintingIfNeeded();
}
ImageData* HTMLCanvasElement::toImageData(SourceDrawingBuffer sourceBuffer,
SnapshotReason reason) const {
ImageData* imageData;
if (is3D()) {
// Get non-premultiplied data because of inaccurate premultiplied alpha
// conversion of buffer()->toDataURL().
imageData = m_context->paintRenderingResultsToImageData(sourceBuffer);
if (imageData)
return imageData;
m_context->paintRenderingResultsToCanvas(sourceBuffer);
imageData = ImageData::create(m_size);
if (imageData && hasImageBuffer()) {
sk_sp<SkImage> snapshot =
buffer()->newSkImageSnapshot(PreferNoAcceleration, reason);
if (snapshot) {
SkImageInfo imageInfo = SkImageInfo::Make(
width(), height(), kRGBA_8888_SkColorType, kUnpremul_SkAlphaType);
snapshot->readPixels(imageInfo, imageData->data()->data(),
imageInfo.minRowBytes(), 0, 0);
}
}
return imageData;
}
imageData = ImageData::create(m_size);
if ((!m_context || !imageData) && !placeholderFrame())
return imageData;
DCHECK((m_context && m_context->is2d()) || placeholderFrame());
sk_sp<SkImage> snapshot;
if (hasImageBuffer()) {
snapshot = buffer()->newSkImageSnapshot(PreferNoAcceleration, reason);
} else if (placeholderFrame()) {
DCHECK(placeholderFrame()->originClean());
// TODO(ccameron): Canvas should produce sRGB images.
// https://crbug.com/672299
snapshot = placeholderFrame()->imageForCurrentFrame(
ColorBehavior::transformToGlobalTarget());
}
if (snapshot) {
SkImageInfo imageInfo = SkImageInfo::Make(
width(), height(), kRGBA_8888_SkColorType, kUnpremul_SkAlphaType);
snapshot->readPixels(imageInfo, imageData->data()->data(),
imageInfo.minRowBytes(), 0, 0);
}
return imageData;
}
String HTMLCanvasElement::toDataURLInternal(
const String& mimeType,
const double& quality,
SourceDrawingBuffer sourceBuffer) const {
if (!isPaintable())
return String("data:,");
String encodingMimeType = ImageEncoderUtils::toEncodingMimeType(
mimeType, ImageEncoderUtils::EncodeReasonToDataURL);
Optional<ScopedUsHistogramTimer> timer;
if (encodingMimeType == "image/png") {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scopedUsCounterPNG,
new CustomCountHistogram("Blink.Canvas.ToDataURL.PNG", 0, 10000000,
50));
timer.emplace(scopedUsCounterPNG);
} else if (encodingMimeType == "image/jpeg") {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scopedUsCounterJPEG,
new CustomCountHistogram("Blink.Canvas.ToDataURL.JPEG", 0, 10000000,
50));
timer.emplace(scopedUsCounterJPEG);
} else if (encodingMimeType == "image/webp") {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, scopedUsCounterWEBP,
new CustomCountHistogram("Blink.Canvas.ToDataURL.WEBP", 0, 10000000,
50));
timer.emplace(scopedUsCounterWEBP);
} else {
// Currently we only support three encoding types.
NOTREACHED();
}
ImageData* imageData = toImageData(sourceBuffer, SnapshotReasonToDataURL);
if (!imageData) // allocation failure
return String("data:,");
return ImageDataBuffer(imageData->size(), imageData->data()->data())
.toDataURL(encodingMimeType, quality);
}
String HTMLCanvasElement::toDataURL(const String& mimeType,
const ScriptValue& qualityArgument,
ExceptionState& exceptionState) const {
if (!originClean()) {
exceptionState.throwSecurityError("Tainted canvases may not be exported.");
return String();
}
double quality = UndefinedQualityValue;
if (!qualityArgument.isEmpty()) {
v8::Local<v8::Value> v8Value = qualityArgument.v8Value();
if (v8Value->IsNumber()) {
quality = v8Value.As<v8::Number>()->Value();
}
}
return toDataURLInternal(mimeType, quality, BackBuffer);
}
void HTMLCanvasElement::toBlob(BlobCallback* callback,
const String& mimeType,
const ScriptValue& qualityArgument,
ExceptionState& exceptionState) {
if (!originClean()) {
exceptionState.throwSecurityError("Tainted canvases may not be exported.");
return;
}
if (!isPaintable()) {
// If the canvas element's bitmap has no pixels
TaskRunnerHelper::get(TaskType::CanvasBlobSerialization, &document())
->postTask(BLINK_FROM_HERE,
WTF::bind(&BlobCallback::handleEvent,
wrapPersistent(callback), nullptr));
return;
}
double startTime = WTF::monotonicallyIncreasingTime();
double quality = UndefinedQualityValue;
if (!qualityArgument.isEmpty()) {
v8::Local<v8::Value> v8Value = qualityArgument.v8Value();
if (v8Value->IsNumber()) {
quality = v8Value.As<v8::Number>()->Value();
}
}
String encodingMimeType = ImageEncoderUtils::toEncodingMimeType(
mimeType, ImageEncoderUtils::EncodeReasonToBlobCallback);
ImageData* imageData = toImageData(BackBuffer, SnapshotReasonToBlob);
if (!imageData) {
// ImageData allocation faillure
TaskRunnerHelper::get(TaskType::CanvasBlobSerialization, &document())
->postTask(BLINK_FROM_HERE,
WTF::bind(&BlobCallback::handleEvent,
wrapPersistent(callback), nullptr));
return;
}
CanvasAsyncBlobCreator* asyncCreator = CanvasAsyncBlobCreator::create(
imageData->data(), encodingMimeType, imageData->size(), callback,
startTime, &document());
asyncCreator->scheduleAsyncBlobCreation(quality);
}
void HTMLCanvasElement::addListener(CanvasDrawListener* listener) {
m_listeners.add(listener);
}
void HTMLCanvasElement::removeListener(CanvasDrawListener* listener) {
m_listeners.remove(listener);
}
SecurityOrigin* HTMLCanvasElement::getSecurityOrigin() const {
return document().getSecurityOrigin();
}
bool HTMLCanvasElement::originClean() const {
if (document().settings() &&
document().settings()->getDisableReadingFromCanvas())
return false;
if (placeholderFrame())
return placeholderFrame()->originClean();
return m_originClean;
}
bool HTMLCanvasElement::shouldAccelerate(AccelerationCriteria criteria) const {
if (m_context && !m_context->is2d())
return false;
if (RuntimeEnabledFeatures::forceDisplayList2dCanvasEnabled())
return false;
if (!RuntimeEnabledFeatures::accelerated2dCanvasEnabled())
return false;
// The following is necessary for handling the special case of canvases in the
// dev tools overlay, which run in a process that supports accelerated 2d
// canvas but in a special compositing context that does not.
if (layoutBox() && !layoutBox()->hasAcceleratedCompositing())
return false;
CheckedNumeric<int> checkedCanvasPixelCount = size().width();
checkedCanvasPixelCount *= size().height();
if (!checkedCanvasPixelCount.IsValid())
return false;
int canvasPixelCount = checkedCanvasPixelCount.ValueOrDie();
if (RuntimeEnabledFeatures::displayList2dCanvasEnabled()) {
#if 0
// TODO(junov): re-enable this code once we solve the problem of recording
// GPU-backed images to an SkPicture for cross-context rendering crbug.com/490328
// If the compositor provides GPU acceleration to display list canvases, we
// prefer that over direct acceleration.
if (document().viewportDescription().matchesHeuristicsForGpuRasterization())
return false;
#endif
// If the GPU resources would be very expensive, prefer a display list.
if (canvasPixelCount > ExpensiveCanvasHeuristicParameters::
PreferDisplayListOverGpuSizeThreshold)
return false;
}
// Do not use acceleration for small canvas.
if (criteria != IgnoreResourceLimitCriteria) {
Settings* settings = document().settings();
if (!settings ||
canvasPixelCount < settings->getMinimumAccelerated2dCanvasSize())
return false;
// When GPU allocated memory runs low (due to having created too many
// accelerated canvases), the compositor starves and browser becomes laggy.
// Thus, we should stop allocating more GPU memory to new canvases created
// when the current memory usage exceeds the threshold.
if (ImageBuffer::getGlobalGPUMemoryUsage() >= MaxGlobalGPUMemoryUsage)
return false;
// Allocating too many GPU resources can makes us run into the driver's
// resource limits. So we need to keep the number of texture resources
// under tight control
if (ImageBuffer::getGlobalAcceleratedImageBufferCount() >=
MaxGlobalAcceleratedImageBufferCount)
return false;
}
return true;
}
namespace {
class UnacceleratedSurfaceFactory
: public RecordingImageBufferFallbackSurfaceFactory {
public:
virtual std::unique_ptr<ImageBufferSurface> createSurface(
const IntSize& size,
OpacityMode opacityMode,
sk_sp<SkColorSpace> colorSpace,
SkColorType colorType) {
return WTF::wrapUnique(new UnacceleratedImageBufferSurface(
size, opacityMode, InitializeImagePixels, colorSpace, colorType));
}
virtual ~UnacceleratedSurfaceFactory() {}
};
} // namespace
bool HTMLCanvasElement::shouldUseDisplayList() {
if (m_context->colorSpace() != kLegacyCanvasColorSpace)
return false;
if (RuntimeEnabledFeatures::forceDisplayList2dCanvasEnabled())
return true;
if (!RuntimeEnabledFeatures::displayList2dCanvasEnabled())
return false;
return true;
}
std::unique_ptr<ImageBufferSurface>
HTMLCanvasElement::createWebGLImageBufferSurface(OpacityMode opacityMode) {
DCHECK(is3D());
// If 3d, but the use of the canvas will be for non-accelerated content
// then make a non-accelerated ImageBuffer. This means copying the internal
// Image will require a pixel readback, but that is unavoidable in this case.
auto surface = WTF::wrapUnique(new AcceleratedImageBufferSurface(
size(), opacityMode, m_context->skColorSpace(), m_context->colorType()));
if (surface->isValid())
return std::move(surface);
return nullptr;
}
std::unique_ptr<ImageBufferSurface>
HTMLCanvasElement::createAcceleratedImageBufferSurface(
OpacityMode opacityMode,
int* msaaSampleCount) {
if (document().settings()) {
*msaaSampleCount =
document().settings()->getAccelerated2dCanvasMSAASampleCount();
}
// Avoid creating |contextProvider| until we're sure we want to try use it,
// since it costs us GPU memory.
std::unique_ptr<WebGraphicsContext3DProvider> contextProvider(
Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
if (!contextProvider) {
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::Accelerated2DCanvasGPUContextLost);
return nullptr;
}
if (contextProvider->isSoftwareRendering())
return nullptr; // Don't use accelerated canvas with swiftshader.
std::unique_ptr<ImageBufferSurface> surface =
WTF::wrapUnique(new Canvas2DImageBufferSurface(
std::move(contextProvider), size(), *msaaSampleCount, opacityMode,
Canvas2DLayerBridge::EnableAcceleration, m_context->skColorSpace(),
m_context->colorType()));
if (!surface->isValid()) {
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::GPUAccelerated2DCanvasImageBufferCreationFailed);
return nullptr;
}
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::GPUAccelerated2DCanvasImageBufferCreated);
return surface;
}
std::unique_ptr<ImageBufferSurface>
HTMLCanvasElement::createUnacceleratedImageBufferSurface(
OpacityMode opacityMode) {
if (shouldUseDisplayList()) {
auto surface = WTF::wrapUnique(new RecordingImageBufferSurface(
size(), WTF::wrapUnique(new UnacceleratedSurfaceFactory), opacityMode,
m_context->skColorSpace(), m_context->colorType()));
if (surface->isValid()) {
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::DisplayList2DCanvasImageBufferCreated);
return std::move(surface);
}
// We fallback to a non-display-list surface without recording a metric
// here.
}
auto surfaceFactory = WTF::makeUnique<UnacceleratedSurfaceFactory>();
auto surface = surfaceFactory->createSurface(
size(), opacityMode, m_context->skColorSpace(), m_context->colorType());
if (surface->isValid()) {
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::Unaccelerated2DCanvasImageBufferCreated);
return surface;
}
CanvasMetrics::countCanvasContextUsage(
CanvasMetrics::Unaccelerated2DCanvasImageBufferCreationFailed);
return nullptr;
}
void HTMLCanvasElement::createImageBuffer() {
createImageBufferInternal(nullptr);
if (m_didFailToCreateImageBuffer && m_context->is2d() && !size().isEmpty())
m_context->loseContext(CanvasRenderingContext::SyntheticLostContext);
}
void HTMLCanvasElement::createImageBufferInternal(
std::unique_ptr<ImageBufferSurface> externalSurface) {
DCHECK(!m_imageBuffer);
m_didFailToCreateImageBuffer = true;
m_imageBufferIsClear = true;
if (!ImageBuffer::canCreateImageBuffer(size()))
return;
OpacityMode opacityMode =
!m_context || m_context->creationAttributes().alpha() ? NonOpaque
: Opaque;
int msaaSampleCount = 0;
std::unique_ptr<ImageBufferSurface> surface;
if (externalSurface) {
if (externalSurface->isValid())
surface = std::move(externalSurface);
} else if (is3D()) {
surface = createWebGLImageBufferSurface(opacityMode);
} else {
if (shouldAccelerate(NormalAccelerationCriteria)) {
surface =
createAcceleratedImageBufferSurface(opacityMode, &msaaSampleCount);
}
if (!surface) {
surface = createUnacceleratedImageBufferSurface(opacityMode);
}
}
if (!surface)
return;
DCHECK(surface->isValid());
m_imageBuffer = ImageBuffer::create(std::move(surface));
DCHECK(m_imageBuffer);
m_imageBuffer->setClient(this);
m_didFailToCreateImageBuffer = false;
updateExternallyAllocatedMemory();
if (is3D()) {
// Early out for WebGL canvases
return;
}
// Enabling MSAA overrides a request to disable antialiasing. This is true
// regardless of whether the rendering mode is accelerated or not. For
// consistency, we don't want to apply AA in accelerated canvases but not in
// unaccelerated canvases.
if (!msaaSampleCount && document().settings() &&
!document().settings()->getAntialiased2dCanvasEnabled())
m_context->setShouldAntialias(false);
if (m_context)
setNeedsCompositingUpdate();
}
void HTMLCanvasElement::notifySurfaceInvalid() {
if (m_context && m_context->is2d())
m_context->loseContext(CanvasRenderingContext::RealLostContext);
}
DEFINE_TRACE(HTMLCanvasElement) {
visitor->trace(m_listeners);
visitor->trace(m_context);
ContextLifecycleObserver::trace(visitor);
PageVisibilityObserver::trace(visitor);
HTMLElement::trace(visitor);
}
DEFINE_TRACE_WRAPPERS(HTMLCanvasElement) {
visitor->traceWrappers(m_context);
HTMLElement::traceWrappers(visitor);
}
void HTMLCanvasElement::updateExternallyAllocatedMemory() const {
int bufferCount = 0;
if (m_imageBuffer) {
bufferCount++;
if (m_imageBuffer->isAccelerated()) {
// The number of internal GPU buffers vary between one (stable
// non-displayed state) and three (triple-buffered animations).
// Adding 2 is a pessimistic but relevant estimate.
// Note: These buffers might be allocated in GPU memory.
bufferCount += 2;
}
}
if (m_copiedImage)
bufferCount++;
// Four bytes per pixel per buffer.
CheckedNumeric<intptr_t> checkedExternallyAllocatedMemory = 4 * bufferCount;
if (is3D()) {
checkedExternallyAllocatedMemory +=
m_context->externallyAllocatedBytesPerPixel();
}
checkedExternallyAllocatedMemory *= width();
checkedExternallyAllocatedMemory *= height();
intptr_t externallyAllocatedMemory =
checkedExternallyAllocatedMemory.ValueOrDefault(
std::numeric_limits<intptr_t>::max());
// Subtracting two intptr_t that are known to be positive will never
// underflow.
v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(
externallyAllocatedMemory - m_externallyAllocatedMemory);
m_externallyAllocatedMemory = externallyAllocatedMemory;
}
SkCanvas* HTMLCanvasElement::drawingCanvas() const {
return buffer() ? m_imageBuffer->canvas() : nullptr;
}
void HTMLCanvasElement::disableDeferral(DisableDeferralReason reason) const {
if (buffer())
m_imageBuffer->disableDeferral(reason);
}
SkCanvas* HTMLCanvasElement::existingDrawingCanvas() const {
if (!hasImageBuffer())
return nullptr;
return m_imageBuffer->canvas();
}
ImageBuffer* HTMLCanvasElement::buffer() const {
DCHECK(m_context);
DCHECK(m_context->getContextType() !=
CanvasRenderingContext::ContextImageBitmap);
if (!hasImageBuffer() && !m_didFailToCreateImageBuffer)
const_cast<HTMLCanvasElement*>(this)->createImageBuffer();
return m_imageBuffer.get();
}
void HTMLCanvasElement::createImageBufferUsingSurfaceForTesting(
std::unique_ptr<ImageBufferSurface> surface) {
discardImageBuffer();
setIntegralAttribute(widthAttr, surface->size().width());
setIntegralAttribute(heightAttr, surface->size().height());
createImageBufferInternal(std::move(surface));
}
void HTMLCanvasElement::ensureUnacceleratedImageBuffer() {
DCHECK(m_context);
if ((hasImageBuffer() && !m_imageBuffer->isAccelerated()) ||
m_didFailToCreateImageBuffer)
return;
discardImageBuffer();
OpacityMode opacityMode =
m_context->creationAttributes().alpha() ? NonOpaque : Opaque;
m_imageBuffer = ImageBuffer::create(size(), opacityMode);
m_didFailToCreateImageBuffer = !m_imageBuffer;
}
PassRefPtr<Image> HTMLCanvasElement::copiedImage(
SourceDrawingBuffer sourceBuffer,
AccelerationHint hint,
SnapshotReason snapshotReason) const {
if (!isPaintable())
return nullptr;
if (!m_context)
return createTransparentImage(size());
if (m_context->getContextType() ==
CanvasRenderingContext::ContextImageBitmap) {
RefPtr<Image> image = m_context->getImage(hint, snapshotReason);
if (image)
return m_context->getImage(hint, snapshotReason);
// Special case: transferFromImageBitmap is not yet called.
sk_sp<SkSurface> surface =
SkSurface::MakeRasterN32Premul(width(), height());
return StaticBitmapImage::create(surface->makeImageSnapshot());
}
bool needToUpdate = !m_copiedImage;
// The concept of SourceDrawingBuffer is valid on only WebGL.
if (m_context->is3d())
needToUpdate |= m_context->paintRenderingResultsToCanvas(sourceBuffer);
if (needToUpdate && buffer()) {
m_copiedImage = buffer()->newImageSnapshot(hint, snapshotReason);
updateExternallyAllocatedMemory();
}
return m_copiedImage;
}
void HTMLCanvasElement::discardImageBuffer() {
m_imageBuffer.reset();
m_dirtyRect = FloatRect();
updateExternallyAllocatedMemory();
}
void HTMLCanvasElement::clearCopiedImage() {
if (m_copiedImage) {
m_copiedImage.clear();
updateExternallyAllocatedMemory();
}
}
AffineTransform HTMLCanvasElement::baseTransform() const {
DCHECK(hasImageBuffer() && !m_didFailToCreateImageBuffer);
return m_imageBuffer->baseTransform();
}
void HTMLCanvasElement::pageVisibilityChanged() {
if (!m_context)
return;
bool hidden = !page()->isPageVisible();
m_context->setIsHidden(hidden);
if (hidden) {
clearCopiedImage();
if (is3D()) {
discardImageBuffer();
}
}
}
void HTMLCanvasElement::contextDestroyed(ExecutionContext*) {
if (m_context)
m_context->stop();
}
void HTMLCanvasElement::styleDidChange(const ComputedStyle* oldStyle,
const ComputedStyle& newStyle) {
if (m_context)
m_context->styleDidChange(oldStyle, newStyle);
}
void HTMLCanvasElement::didMoveToNewDocument(Document& oldDocument) {
ContextLifecycleObserver::setContext(&document());
PageVisibilityObserver::setContext(document().page());
HTMLElement::didMoveToNewDocument(oldDocument);
}
void HTMLCanvasElement::willDrawImageTo2DContext(CanvasImageSource* source) {
if (ExpensiveCanvasHeuristicParameters::EnableAccelerationToAvoidReadbacks &&
source->isAccelerated() && !buffer()->isAccelerated() &&
shouldAccelerate(IgnoreResourceLimitCriteria)) {
OpacityMode opacityMode =
m_context->creationAttributes().alpha() ? NonOpaque : Opaque;
int msaaSampleCount = 0;
std::unique_ptr<ImageBufferSurface> surface =
createAcceleratedImageBufferSurface(opacityMode, &msaaSampleCount);
if (surface) {
buffer()->setSurface(std::move(surface));
}
}
}
PassRefPtr<Image> HTMLCanvasElement::getSourceImageForCanvas(
SourceImageStatus* status,
AccelerationHint hint,
SnapshotReason reason,
const FloatSize&) const {
if (!width() || !height()) {
*status = ZeroSizeCanvasSourceImageStatus;
return nullptr;
}
if (!isPaintable()) {
*status = InvalidSourceImageStatus;
return nullptr;
}
if (placeholderFrame()) {
*status = NormalSourceImageStatus;
return placeholderFrame();
}
if (!m_context) {
RefPtr<Image> result = createTransparentImage(size());
*status = result ? NormalSourceImageStatus : InvalidSourceImageStatus;
return result;
}
if (m_context->getContextType() == CanvasRenderingContext::ContextImageBitmap)
return m_context->getImage(hint, reason);
sk_sp<SkImage> skImage;
// TODO(ccameron): Canvas should produce sRGB images.
// https://crbug.com/672299
if (m_context->is3d()) {
// Because WebGL sources always require making a copy of the back buffer, we
// use paintRenderingResultsToCanvas instead of getImage in order to keep a
// cached copy of the backing in the canvas's ImageBuffer.
renderingContext()->paintRenderingResultsToCanvas(BackBuffer);
if (hasImageBuffer()) {
skImage = buffer()->newSkImageSnapshot(hint, reason);
} else {
skImage = createTransparentSkImage(size());
}
} else {
if (ExpensiveCanvasHeuristicParameters::
DisableAccelerationToAvoidReadbacks &&
!RuntimeEnabledFeatures::canvas2dFixedRenderingModeEnabled() &&
hint == PreferNoAcceleration && m_context->isAccelerated() &&
hasImageBuffer()) {
buffer()->disableAcceleration();
}
RefPtr<Image> image = renderingContext()->getImage(hint, reason);
if (image) {
skImage =
image->imageForCurrentFrame(ColorBehavior::transformToGlobalTarget());
} else {
skImage = createTransparentSkImage(size());
}
}
if (skImage) {
*status = NormalSourceImageStatus;
return StaticBitmapImage::create(std::move(skImage));
}
*status = InvalidSourceImageStatus;
return nullptr;
}
bool HTMLCanvasElement::wouldTaintOrigin(SecurityOrigin*) const {
return !originClean();
}
FloatSize HTMLCanvasElement::elementSize(const FloatSize&) const {
if (m_context &&
m_context->getContextType() ==
CanvasRenderingContext::ContextImageBitmap) {
RefPtr<Image> image =
m_context->getImage(PreferNoAcceleration, SnapshotReasonDrawImage);
if (image)
return FloatSize(image->width(), image->height());
return FloatSize(0, 0);
}
if (placeholderFrame())
return FloatSize(placeholderFrame()->size());
return FloatSize(width(), height());
}
IntSize HTMLCanvasElement::bitmapSourceSize() const {
return IntSize(width(), height());
}
ScriptPromise HTMLCanvasElement::createImageBitmap(
ScriptState* scriptState,
EventTarget& eventTarget,
Optional<IntRect> cropRect,
const ImageBitmapOptions& options,
ExceptionState& exceptionState) {
DCHECK(eventTarget.toLocalDOMWindow());
if ((cropRect &&
!ImageBitmap::isSourceSizeValid(cropRect->width(), cropRect->height(),
exceptionState)) ||
!ImageBitmap::isSourceSizeValid(bitmapSourceSize().width(),
bitmapSourceSize().height(),
exceptionState))
return ScriptPromise();
if (!ImageBitmap::isResizeOptionValid(options, exceptionState))
return ScriptPromise();
return ImageBitmapSource::fulfillImageBitmap(
scriptState,
isPaintable() ? ImageBitmap::create(this, cropRect, options) : nullptr);
}
bool HTMLCanvasElement::isOpaque() const {
return m_context && !m_context->creationAttributes().alpha();
}
bool HTMLCanvasElement::isSupportedInteractiveCanvasFallback(
const Element& element) {
if (!element.isDescendantOf(this))
return false;
// An element is a supported interactive canvas fallback element if it is one
// of the following:
// https://html.spec.whatwg.org/multipage/scripting.html#supported-interactive-canvas-fallback-element
// An a element that represents a hyperlink and that does not have any img
// descendants.
if (isHTMLAnchorElement(element))
return !Traversal<HTMLImageElement>::firstWithin(element);
// A button element
if (isHTMLButtonElement(element))
return true;
// An input element whose type attribute is in one of the Checkbox or Radio
// Button states. An input element that is a button but its type attribute is
// not in the Image Button state.
if (isHTMLInputElement(element)) {
const HTMLInputElement& inputElement = toHTMLInputElement(element);
if (inputElement.type() == InputTypeNames::checkbox ||
inputElement.type() == InputTypeNames::radio ||
inputElement.isTextButton())
return true;
}
// A select element with a "multiple" attribute or with a display size greater
// than 1.
if (isHTMLSelectElement(element)) {
const HTMLSelectElement& selectElement = toHTMLSelectElement(element);
if (selectElement.isMultiple() || selectElement.size() > 1)
return true;
}
// An option element that is in a list of options of a select element with a
// "multiple" attribute or with a display size greater than 1.
if (isHTMLOptionElement(element) && element.parentNode() &&
isHTMLSelectElement(*element.parentNode())) {
const HTMLSelectElement& selectElement =
toHTMLSelectElement(*element.parentNode());
if (selectElement.isMultiple() || selectElement.size() > 1)
return true;
}
// An element that would not be interactive content except for having the
// tabindex attribute specified.
if (element.fastHasAttribute(HTMLNames::tabindexAttr))
return true;
// A non-interactive table, caption, thead, tbody, tfoot, tr, td, or th
// element.
if (isHTMLTableElement(element) ||
element.hasTagName(HTMLNames::captionTag) ||
element.hasTagName(HTMLNames::theadTag) ||
element.hasTagName(HTMLNames::tbodyTag) ||
element.hasTagName(HTMLNames::tfootTag) ||
element.hasTagName(HTMLNames::trTag) ||
element.hasTagName(HTMLNames::tdTag) ||
element.hasTagName(HTMLNames::thTag))
return true;
return false;
}
HitTestCanvasResult* HTMLCanvasElement::getControlAndIdIfHitRegionExists(
const LayoutPoint& location) {
if (m_context && m_context->is2d())
return m_context->getControlAndIdIfHitRegionExists(location);
return HitTestCanvasResult::create(String(), nullptr);
}
String HTMLCanvasElement::getIdFromControl(const Element* element) {
if (m_context)
return m_context->getIdFromControl(element);
return String();
}
void HTMLCanvasElement::createLayer() {
DCHECK(!m_surfaceLayerBridge);
m_surfaceLayerBridge = WTF::wrapUnique(new CanvasSurfaceLayerBridge(this));
// Creates a placeholder layer first before Surface is created.
m_surfaceLayerBridge->createSolidColorLayer();
}
void HTMLCanvasElement::OnWebLayerReplaced() {
setNeedsCompositingUpdate();
}
} // namespace blink
|