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
|
/*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org>
* Copyright (C) 2008 Nuanti Ltd.
* Copyright (C) 2009 Brent Fulgham <bfulgham@webkit.org>
* Copyright (C) 2010, 2011 Igalia S.L.
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
* Copyright (C) 2012, Intel Corporation
*
* 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 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 INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "CairoOperations.h"
#if USE(CAIRO)
#include "CairoUniquePtr.h"
#include "CairoUtilities.h"
#include "DrawErrorUnderline.h"
#include "FloatConversion.h"
#include "FloatRect.h"
#include "Gradient.h"
#include "GraphicsContext.h"
#include "GraphicsContextCairo.h"
#include "Image.h"
#include "ImageBuffer.h"
#include "NativeImage.h"
#include "Path.h"
#include "ShadowBlur.h"
#include <algorithm>
#include <cairo.h>
namespace WebCore {
namespace Cairo {
enum PatternAdjustment { NoAdjustment, AdjustPatternForGlobalAlpha };
enum AlphaPreservation { DoNotPreserveAlpha, PreserveAlpha };
static void reduceSourceByAlpha(cairo_t* cr, float alpha)
{
if (alpha >= 1)
return;
cairo_push_group(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_paint_with_alpha(cr, alpha);
cairo_pop_group_to_source(cr);
}
static void prepareCairoContextSource(cairo_t* cr, cairo_pattern_t* pattern, cairo_pattern_t* gradient, const Color& color, float globalAlpha)
{
if (pattern) {
// Pattern source
cairo_set_source(cr, pattern);
reduceSourceByAlpha(cr, globalAlpha);
} else if (gradient) {
// Gradient source
cairo_set_source(cr, gradient);
} else {
// Solid color source
if (globalAlpha < 1)
setSourceRGBAFromColor(cr, color.colorWithAlphaMultipliedBy(globalAlpha));
else
setSourceRGBAFromColor(cr, color);
}
}
static void clipForPatternFilling(cairo_t* cr, const FloatSize& patternSize, const AffineTransform& patternTransform, bool repeatX, bool repeatY)
{
// Hold current cairo path in a variable for restoring it after configuring the pattern clip rectangle.
CairoUniquePtr<cairo_path_t> currentPath(cairo_copy_path(cr));
cairo_new_path(cr);
// Initialize clipping extent from current cairo clip extents, then shrink if needed according to pattern.
// Inspired by GraphicsContextQt::drawRepeatPattern.
double x1, y1, x2, y2;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
FloatRect clipRect(x1, y1, x2 - x1, y2 - y1);
FloatRect patternRect = patternTransform.mapRect(FloatRect(FloatPoint(), patternSize));
if (!repeatX) {
clipRect.setX(patternRect.x());
clipRect.setWidth(patternRect.width());
}
if (!repeatY) {
clipRect.setY(patternRect.y());
clipRect.setHeight(patternRect.height());
}
if (!repeatX || !repeatY) {
cairo_rectangle(cr, clipRect.x(), clipRect.y(), clipRect.width(), clipRect.height());
cairo_clip(cr);
}
// Restoring cairo path.
cairo_append_path(cr, currentPath.get());
}
static void prepareForFilling(cairo_t* cr, const Cairo::FillSource& fillSource, PatternAdjustment patternAdjustment)
{
cairo_set_fill_rule(cr, fillSource.fillRule == WindRule::EvenOdd ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
bool adjustForAlpha = patternAdjustment == AdjustPatternForGlobalAlpha;
auto* gradient = fillSource.gradient.base.get();
if (adjustForAlpha && fillSource.gradient.alphaAdjusted)
gradient = fillSource.gradient.alphaAdjusted.get();
prepareCairoContextSource(cr, fillSource.pattern.object.get(), gradient,
fillSource.color, adjustForAlpha ? fillSource.globalAlpha : 1);
if (fillSource.pattern.object) {
clipForPatternFilling(cr, fillSource.pattern.size, fillSource.pattern.transform,
fillSource.pattern.repeatX, fillSource.pattern.repeatY);
}
}
static void prepareForStroking(cairo_t* cr, const Cairo::StrokeSource& strokeSource, AlphaPreservation alphaPreservation)
{
bool preserveAlpha = alphaPreservation == PreserveAlpha;
auto* gradient = strokeSource.gradient.base.get();
if (preserveAlpha && strokeSource.gradient.alphaAdjusted)
gradient = strokeSource.gradient.alphaAdjusted.get();
prepareCairoContextSource(cr, strokeSource.pattern.get(), gradient,
strokeSource.color, preserveAlpha ? strokeSource.globalAlpha : 1);
}
static void drawPatternToCairoContext(cairo_t* cr, cairo_pattern_t* pattern, const FloatRect& destRect, float alpha)
{
cairo_translate(cr, destRect.x(), destRect.y());
cairo_set_source(cr, pattern);
cairo_rectangle(cr, 0, 0, destRect.width(), destRect.height());
cairo_clip(cr);
cairo_paint_with_alpha(cr, std::max<float>(0, std::min<float>(1.0, alpha)));
}
static inline void fillRectWithColor(cairo_t* cr, const FloatRect& rect, const Color& color)
{
if (!color.isVisible() && cairo_get_operator(cr) == CAIRO_OPERATOR_OVER)
return;
setSourceRGBAFromColor(cr, color);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill(cr);
}
enum PathDrawingStyle {
Fill = 1,
Stroke = 2,
FillAndStroke = Fill + Stroke
};
static void drawShadowLayerBuffer(GraphicsContextCairo& platformContext, ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize, const ShadowState& shadowState)
{
if (auto nativeImage = platformContext.nativeImageForDrawing(layerImage))
drawPlatformImage(platformContext, nativeImage->platformImage().get(), FloatRect(roundedIntPoint(layerOrigin), layerSize), FloatRect(FloatPoint(), layerSize), { shadowState.globalCompositeOperator }, shadowState.globalAlpha, ShadowState());
}
// FIXME: This is mostly same as drawShadowLayerBuffer, so we should merge two.
static void drawShadowImage(GraphicsContextCairo& platformContext, ImageBuffer& layerImage, const FloatRect& destRect, const FloatRect& srcRect, const ShadowState& shadowState)
{
if (auto nativeImage = platformContext.nativeImageForDrawing(layerImage))
drawPlatformImage(platformContext, nativeImage->platformImage().get(), destRect, srcRect, { shadowState.globalCompositeOperator }, shadowState.globalAlpha, ShadowState());
}
static void fillShadowBuffer(GraphicsContextCairo& platformContext, ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize, const ShadowState& shadowState)
{
platformContext.save();
if (auto nativeImage = platformContext.nativeImageForDrawing(layerImage))
clipToImageBuffer(platformContext, nativeImage->platformImage().get(), FloatRect(layerOrigin, expandedIntSize(layerSize)));
FillSource fillSource;
fillSource.globalAlpha = shadowState.globalAlpha;
fillSource.color = shadowState.color;
fillRect(platformContext, FloatRect(layerOrigin, expandedIntSize(layerSize)), fillSource, ShadowState());
platformContext.restore();
}
static inline void drawPathShadow(GraphicsContextCairo& platformContext, const FillSource& fillSource, const StrokeSource& strokeSource, const ShadowState& shadowState, PathDrawingStyle drawingStyle)
{
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
if (shadow.type() == ShadowBlur::NoShadow)
return;
// Calculate the extents of the rendered solid paths.
cairo_t* cairoContext = platformContext.cr();
CairoUniquePtr<cairo_path_t> path(cairo_copy_path(cairoContext));
FloatRect solidFigureExtents;
double x0 = 0;
double x1 = 0;
double y0 = 0;
double y1 = 0;
if (drawingStyle & Stroke) {
cairo_stroke_extents(cairoContext, &x0, &y0, &x1, &y1);
solidFigureExtents = FloatRect(x0, y0, x1 - x0, y1 - y0);
}
if (drawingStyle & Fill) {
cairo_fill_extents(cairoContext, &x0, &y0, &x1, &y1);
FloatRect fillExtents(x0, y0, x1 - x0, y1 - y0);
solidFigureExtents.unite(fillExtents);
}
shadow.drawShadowLayer(State::getCTM(platformContext), State::getClipBounds(platformContext), solidFigureExtents,
[cairoContext, drawingStyle, &path, &fillSource, &strokeSource](GraphicsContext& shadowContext)
{
cairo_t* cairoShadowContext = shadowContext.platformContext()->cr();
// It's important to copy the context properties to the new shadow
// context to preserve things such as the fill rule and stroke width.
copyContextProperties(cairoContext, cairoShadowContext);
if (drawingStyle & Fill) {
cairo_save(cairoShadowContext);
cairo_append_path(cairoShadowContext, path.get());
prepareForFilling(cairoShadowContext, fillSource, NoAdjustment);
cairo_fill(cairoShadowContext);
cairo_restore(cairoShadowContext);
}
if (drawingStyle & Stroke) {
cairo_append_path(cairoShadowContext, path.get());
prepareForStroking(cairoShadowContext, strokeSource, DoNotPreserveAlpha);
cairo_stroke(cairoShadowContext);
}
},
[&platformContext, &shadowState, &cairoContext, &path](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
// The original path may still be hanging around on the context and endShadowLayer
// will take care of properly creating a path to draw the result shadow. We remove the path
// temporarily and then restore it.
// See: https://bugs.webkit.org/show_bug.cgi?id=108897
cairo_new_path(cairoContext);
drawShadowLayerBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
cairo_append_path(cairoContext, path.get());
});
}
static inline void fillCurrentCairoPath(GraphicsContextCairo& platformContext, const FillSource& fillSource)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
prepareForFilling(cr, fillSource, AdjustPatternForGlobalAlpha);
cairo_fill(cr);
cairo_restore(cr);
}
static void drawGlyphsToContext(cairo_t* context, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs, FontSmoothingMode fontSmoothingMode)
{
cairo_matrix_t originalTransform;
if (syntheticBoldOffset)
cairo_get_matrix(context, &originalTransform);
cairo_set_scaled_font(context, scaledFont);
// The scaled font defaults to FontSmoothingMode::AutoSmoothing. Only override antialiasing settings if its not auto.
if (fontSmoothingMode != FontSmoothingMode::AutoSmoothing) {
CairoUniquePtr<cairo_font_options_t> fontOptionsSmoothing(cairo_font_options_create());
cairo_scaled_font_get_font_options(scaledFont, fontOptionsSmoothing.get());
switch (fontSmoothingMode) {
case FontSmoothingMode::Antialiased:
// Don't use CAIRO_ANTIALIAS_GRAY in Windows. It is mapped to ANTIALIASED_QUALITY which looks jaggy and faint.
#if !OS(WINDOWS)
cairo_font_options_set_antialias(fontOptionsSmoothing.get(), CAIRO_ANTIALIAS_GRAY);
break;
#endif
case FontSmoothingMode::SubpixelAntialiased:
cairo_font_options_set_antialias(fontOptionsSmoothing.get(), CAIRO_ANTIALIAS_SUBPIXEL);
break;
case FontSmoothingMode::NoSmoothing:
cairo_font_options_set_antialias(fontOptionsSmoothing.get(), CAIRO_ANTIALIAS_NONE);
break;
default:
ASSERT_NOT_REACHED();
}
cairo_set_font_options(context, fontOptionsSmoothing.get());
}
cairo_show_glyphs(context, glyphs.data(), glyphs.size());
if (syntheticBoldOffset) {
cairo_translate(context, syntheticBoldOffset, 0);
cairo_show_glyphs(context, glyphs.data(), glyphs.size());
cairo_set_matrix(context, &originalTransform);
}
}
static void drawGlyphsShadow(GraphicsContextCairo& platformContext, const ShadowState& shadowState, TextDrawingModeFlags textDrawingMode, const GraphicsDropShadow& dropShadow, const FloatPoint& point, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs, FontSmoothingMode fontSmoothingMode)
{
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
if (!textDrawingMode.contains(TextDrawingMode::Fill) || shadow.type() == ShadowBlur::NoShadow)
return;
if (!shadowState.isRequired(platformContext)) {
// Optimize non-blurry shadows, by just drawing text without the ShadowBlur.
cairo_t* context = platformContext.cr();
cairo_save(context);
cairo_translate(context, dropShadow.offset.width(), dropShadow.offset.height());
setSourceRGBAFromColor(context, dropShadow.color);
drawGlyphsToContext(context, scaledFont, syntheticBoldOffset, glyphs, fontSmoothingMode);
cairo_restore(context);
return;
}
cairo_text_extents_t extents;
cairo_scaled_font_glyph_extents(scaledFont, glyphs.data(), glyphs.size(), &extents);
FloatRect fontExtentsRect(point.x() + extents.x_bearing, point.y() + extents.y_bearing, extents.width, extents.height);
shadow.drawShadowLayer(State::getCTM(platformContext), State::getClipBounds(platformContext), fontExtentsRect,
[scaledFont, syntheticBoldOffset, &glyphs, fontSmoothingMode](GraphicsContext& shadowContext)
{
drawGlyphsToContext(shadowContext.platformContext()->cr(), scaledFont, syntheticBoldOffset, glyphs, fontSmoothingMode);
},
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
drawShadowLayerBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
});
}
static bool cairoSurfaceHasAlpha(cairo_surface_t* surface)
{
return cairo_surface_get_content(surface) != CAIRO_CONTENT_COLOR;
}
// FIXME: Fix GraphicsContext::computeLineBoundsAndAntialiasingModeForText()
// to be a static public function that operates on CTM and strokeThickness
// arguments instead of using an underlying GraphicsContext object.
FloatRect computeLineBoundsAndAntialiasingModeForText(GraphicsContextCairo& platformContext, const FloatPoint& point, float width, bool printing, Color& color, float strokeThickness)
{
FloatPoint origin = point;
float thickness = std::max(strokeThickness, 0.5f);
if (printing)
return FloatRect(origin, FloatSize(width, thickness));
AffineTransform transform = Cairo::State::getCTM(platformContext);
// Just compute scale in x dimension, assuming x and y scales are equal.
float scale = transform.b() ? std::hypot(transform.a(), transform.b()) : transform.a();
if (scale < 1.0) {
// This code always draws a line that is at least one-pixel line high,
// which tends to visually overwhelm text at small scales. To counter this
// effect, an alpha is applied to the underline color when text is at small scales.
static const float minimumUnderlineAlpha = 0.4f;
float shade = scale > minimumUnderlineAlpha ? scale : minimumUnderlineAlpha;
color = color.colorWithAlphaMultipliedBy(shade);
}
FloatPoint devicePoint = transform.mapPoint(point);
// Visual overflow might occur here due to integral roundf/ceilf. visualOverflowForDecorations adjusts the overflow value for underline decoration.
FloatPoint deviceOrigin = FloatPoint(roundf(devicePoint.x()), ceilf(devicePoint.y()));
if (auto inverse = transform.inverse())
origin = inverse.value().mapPoint(deviceOrigin);
return FloatRect(origin, FloatSize(width, thickness));
};
// FIXME: Replace once GraphicsContext::dashedLineCornerWidthForStrokeWidth()
// is refactored as a static public function.
static float dashedLineCornerWidthForStrokeWidth(float strokeWidth, StrokeStyle strokeStyle, float strokeThickness)
{
return strokeStyle == StrokeStyle::DottedStroke ? strokeThickness : std::min(2.0f * strokeThickness, std::max(strokeThickness, strokeWidth / 3.0f));
}
// FIXME: Replace once GraphicsContext::dashedLinePatternWidthForStrokeWidth()
// is refactored as a static public function.
static float dashedLinePatternWidthForStrokeWidth(float strokeWidth, StrokeStyle strokeStyle, float strokeThickness)
{
return strokeStyle == StrokeStyle::DottedStroke ? strokeThickness : std::min(3.0f * strokeThickness, std::max(strokeThickness, strokeWidth / 3.0f));
}
// FIXME: Replace once GraphicsContext::dashedLinePatternOffsetForPatternAndStrokeWidth()
// is refactored as a static public function.
static float dashedLinePatternOffsetForPatternAndStrokeWidth(float patternWidth, float strokeWidth)
{
// Pattern starts with full fill and ends with the empty fill.
// 1. Let's start with the empty phase after the corner.
// 2. Check if we've got odd or even number of patterns and whether they fully cover the line.
// 3. In case of even number of patterns and/or remainder, move the pattern start position
// so that the pattern is balanced between the corners.
float patternOffset = patternWidth;
int numberOfSegments = std::floor(strokeWidth / patternWidth);
bool oddNumberOfSegments = numberOfSegments % 2;
float remainder = strokeWidth - (numberOfSegments * patternWidth);
if (oddNumberOfSegments && remainder)
patternOffset -= remainder / 2.0f;
else if (!oddNumberOfSegments) {
if (remainder)
patternOffset += patternOffset - (patternWidth + remainder) / 2.0f;
else
patternOffset += patternWidth / 2.0f;
}
return patternOffset;
}
// FIXME: Replace once GraphicsContext::centerLineAndCutOffCorners()
// is refactored as a static public function.
static Vector<FloatPoint> centerLineAndCutOffCorners(bool isVerticalLine, float cornerWidth, FloatPoint point1, FloatPoint point2)
{
// Center line and cut off corners for pattern painting.
if (isVerticalLine) {
float centerOffset = (point2.x() - point1.x()) / 2.0f;
point1.move(centerOffset, cornerWidth);
point2.move(-centerOffset, -cornerWidth);
} else {
float centerOffset = (point2.y() - point1.y()) / 2.0f;
point1.move(cornerWidth, centerOffset);
point2.move(-cornerWidth, -centerOffset);
}
return { point1, point2 };
}
namespace State {
void setStrokeThickness(GraphicsContextCairo& platformContext, float strokeThickness)
{
cairo_set_line_width(platformContext.cr(), strokeThickness);
}
void setStrokeStyle(GraphicsContextCairo& platformContext, StrokeStyle strokeStyle)
{
static const double dashPattern[] = { 5.0, 5.0 };
static const double dotPattern[] = { 1.0, 1.0 };
cairo_t* cr = platformContext.cr();
switch (strokeStyle) {
case StrokeStyle::NoStroke:
// FIXME: is it the right way to emulate NoStroke?
cairo_set_line_width(cr, 0);
break;
case StrokeStyle::SolidStroke:
case StrokeStyle::DoubleStroke:
case StrokeStyle::WavyStroke:
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=94110 - Needs platform support.
cairo_set_dash(cr, 0, 0, 0);
break;
case StrokeStyle::DottedStroke:
cairo_set_dash(cr, dotPattern, 2, 0);
break;
case StrokeStyle::DashedStroke:
cairo_set_dash(cr, dashPattern, 2, 0);
break;
}
}
void setCompositeOperation(GraphicsContextCairo& platformContext, CompositeOperator compositeOperation, BlendMode blendMode)
{
cairo_set_operator(platformContext.cr(), toCairoOperator(compositeOperation, blendMode));
}
void setShouldAntialias(GraphicsContextCairo& platformContext, bool enable)
{
// When true, use the default Cairo backend antialias mode (usually this
// enables standard 'grayscale' antialiasing); false to explicitly disable
// antialiasing.
cairo_set_antialias(platformContext.cr(), enable ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
}
void setCTM(GraphicsContextCairo& platformContext, const AffineTransform& transform)
{
const cairo_matrix_t matrix = toCairoMatrix(transform);
cairo_set_matrix(platformContext.cr(), &matrix);
}
AffineTransform getCTM(GraphicsContextCairo& platformContext)
{
cairo_matrix_t m;
cairo_get_matrix(platformContext.cr(), &m);
return AffineTransform(m.xx, m.yx, m.xy, m.yy, m.x0, m.y0);
}
IntRect getClipBounds(GraphicsContextCairo& platformContext)
{
double x1, x2, y1, y2;
cairo_clip_extents(platformContext.cr(), &x1, &y1, &x2, &y2);
return enclosingIntRect(FloatRect(x1, y1, x2 - x1, y2 - y1));
}
bool isAcceleratedContext(GraphicsContextCairo& platformContext)
{
return cairo_surface_get_type(cairo_get_target(platformContext.cr())) == CAIRO_SURFACE_TYPE_GL;
}
} // namespace State
FillSource::FillSource(const GraphicsContextState& state)
: globalAlpha(state.alpha())
, fillRule(state.fillRule())
{
if (auto fillPattern = state.fillBrush().pattern()) {
pattern.object = adoptRef(fillPattern->createPlatformPattern(AffineTransform()));
auto& patternImage = fillPattern->tileImage();
pattern.size = patternImage.size();
pattern.transform = fillPattern->patternSpaceTransform();
pattern.repeatX = fillPattern->repeatX();
pattern.repeatY = fillPattern->repeatY();
} else if (auto fillGradient = state.fillBrush().gradient()) {
gradient.base = fillGradient->createPattern(1, state.fillBrush().gradientSpaceTransform());
if (state.alpha() != 1)
gradient.alphaAdjusted = fillGradient->createPattern(state.alpha(), state.fillBrush().gradientSpaceTransform());
} else
color = state.fillBrush().color();
}
FillSource::FillSource(const GraphicsContextState& state, Gradient& useGradient, const AffineTransform& gradientSpaceTransform)
: globalAlpha(state.alpha())
, fillRule(state.fillRule())
{
gradient.base = useGradient.createPattern(1, gradientSpaceTransform);
if (state.alpha() != 1)
gradient.alphaAdjusted = useGradient.createPattern(state.alpha(), gradientSpaceTransform);
}
StrokeSource::StrokeSource(const GraphicsContextState& state)
: globalAlpha(state.alpha())
{
if (auto strokePattern = state.strokeBrush().pattern())
pattern = adoptRef(strokePattern->createPlatformPattern(AffineTransform()));
else if (auto strokeGradient = state.strokeBrush().gradient()) {
gradient.base = strokeGradient->createPattern(1, state.strokeBrush().gradientSpaceTransform());
if (state.alpha() != 1)
gradient.alphaAdjusted = strokeGradient->createPattern(state.alpha(), state.strokeBrush().gradientSpaceTransform());
} else
color = state.strokeBrush().color();
}
ShadowState::ShadowState(const GraphicsContextState& state)
: ignoreTransforms(state.shadowsIgnoreTransforms())
, globalAlpha(state.alpha())
, globalCompositeOperator(state.compositeMode().operation)
{
if (state.dropShadow()) {
offset = state.dropShadow()->offset;
blur = state.dropShadow()->radius;
color = state.dropShadow()->color;
}
}
bool ShadowState::isVisible() const
{
return color.isVisible() && (offset.width() || offset.height() || blur);
}
bool ShadowState::isRequired(GraphicsContextCairo& platformContext) const
{
// We can't avoid ShadowBlur if the shadow has blur.
if (color.isVisible() && blur)
return true;
// We can avoid ShadowBlur and optimize, since we're not drawing on a
// canvas and box shadows are affected by the transformation matrix.
if (!ignoreTransforms)
return false;
// We can avoid ShadowBlur, since there are no transformations to apply to the canvas.
if (State::getCTM(platformContext).isIdentity())
return false;
// Otherwise, no chance avoiding ShadowBlur.
return true;
}
void setLineCap(GraphicsContextCairo& platformContext, LineCap lineCap)
{
cairo_line_cap_t cairoCap { };
switch (lineCap) {
case LineCap::Butt:
cairoCap = CAIRO_LINE_CAP_BUTT;
break;
case LineCap::Round:
cairoCap = CAIRO_LINE_CAP_ROUND;
break;
case LineCap::Square:
cairoCap = CAIRO_LINE_CAP_SQUARE;
break;
}
cairo_set_line_cap(platformContext.cr(), cairoCap);
}
void setLineDash(GraphicsContextCairo& platformContext, const DashArray& dashes, float dashOffset)
{
if (std::all_of(dashes.begin(), dashes.end(), [](auto& dash) { return !dash; }))
cairo_set_dash(platformContext.cr(), 0, 0, 0);
else
cairo_set_dash(platformContext.cr(), dashes.data(), dashes.size(), dashOffset);
}
void setLineJoin(GraphicsContextCairo& platformContext, LineJoin lineJoin)
{
cairo_line_join_t cairoJoin { };
switch (lineJoin) {
case LineJoin::Miter:
cairoJoin = CAIRO_LINE_JOIN_MITER;
break;
case LineJoin::Round:
cairoJoin = CAIRO_LINE_JOIN_ROUND;
break;
case LineJoin::Bevel:
cairoJoin = CAIRO_LINE_JOIN_BEVEL;
break;
}
cairo_set_line_join(platformContext.cr(), cairoJoin);
}
void setMiterLimit(GraphicsContextCairo& platformContext, float miterLimit)
{
cairo_set_miter_limit(platformContext.cr(), miterLimit);
}
void fillRect(GraphicsContextCairo& platformContext, const FloatRect& rect, const FillSource& fillSource, const ShadowState& shadowState)
{
cairo_t* cr = platformContext.cr();
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
drawPathShadow(platformContext, fillSource, { }, shadowState, Fill);
fillCurrentCairoPath(platformContext, fillSource);
}
void fillRect(GraphicsContextCairo& platformContext, const FloatRect& rect, const Color& color, const ShadowState& shadowState)
{
if (shadowState.isVisible()) {
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
shadow.drawRectShadow(State::getCTM(platformContext), State::getClipBounds(platformContext), FloatRoundedRect(rect),
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
fillShadowBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
},
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatRect& destRect, const FloatRect& srcRect)
{
drawShadowImage(platformContext, layerImage, destRect, srcRect, shadowState);
},
[&platformContext](const FloatRect& rect, const Color& color)
{
fillRectWithColor(platformContext.cr(), rect, color);
});
}
fillRectWithColor(platformContext.cr(), rect, color);
}
void fillRect(GraphicsContextCairo& platformContext, const FloatRect& rect, cairo_pattern_t* platformPattern)
{
cairo_t* cr = platformContext.cr();
cairo_set_source(cr, platformPattern);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill(cr);
}
void fillRoundedRect(GraphicsContextCairo& platformContext, const FloatRoundedRect& rect, const Color& color, const ShadowState& shadowState)
{
if (shadowState.isVisible()) {
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
shadow.drawRectShadow(State::getCTM(platformContext), State::getClipBounds(platformContext), rect,
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
fillShadowBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
},
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatRect& destRect, const FloatRect& srcRect)
{
drawShadowImage(platformContext, layerImage, destRect, srcRect, shadowState);
},
[&platformContext](const FloatRect& rect, const Color& color)
{
fillRectWithColor(platformContext.cr(), rect, color);
});
}
cairo_t* cr = platformContext.cr();
cairo_save(cr);
Path path;
path.addRoundedRect(rect);
appendWebCorePathToCairoContext(cr, path);
setSourceRGBAFromColor(cr, color);
cairo_fill(cr);
cairo_restore(cr);
}
void fillRectWithRoundedHole(GraphicsContextCairo& platformContext, const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const FillSource& fillSource, const ShadowState& shadowState)
{
// FIXME: this should leverage the specified color.
if (shadowState.isVisible()) {
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
shadow.drawInsetShadow(State::getCTM(platformContext), State::getClipBounds(platformContext), rect, roundedHoleRect,
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
fillShadowBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
},
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatRect& destRect, const FloatRect& srcRect)
{
drawShadowImage(platformContext, layerImage, destRect, srcRect, shadowState);
},
[&platformContext](const FloatRect& rect, const FloatRect& holeRect, const Color& color)
{
// FIXME: We should use fillRectWithRoundedHole.
cairo_t* cr = platformContext.cr();
cairo_save(cr);
setSourceRGBAFromColor(cr, color);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_rectangle(cr, holeRect.x(), holeRect.y(), holeRect.width(), holeRect.height());
cairo_fill(cr);
cairo_restore(cr);
});
}
Path path;
path.addRect(rect);
if (!roundedHoleRect.radii().isZero())
path.addRoundedRect(roundedHoleRect);
else
path.addRect(roundedHoleRect.rect());
cairo_t* cr = platformContext.cr();
cairo_save(cr);
setPathOnCairoContext(platformContext.cr(), path.platformPath());
fillCurrentCairoPath(platformContext, fillSource);
cairo_restore(cr);
}
void fillPath(GraphicsContextCairo& platformContext, const Path& path, const FillSource& fillSource, const ShadowState& shadowState)
{
cairo_t* cr = platformContext.cr();
setPathOnCairoContext(cr, path.platformPath());
drawPathShadow(platformContext, fillSource, { }, shadowState, Fill);
fillCurrentCairoPath(platformContext, fillSource);
}
void strokeRect(GraphicsContextCairo& platformContext, const FloatRect& rect, float lineWidth, const StrokeSource& strokeSource, const ShadowState& shadowState)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_set_line_width(cr, lineWidth);
drawPathShadow(platformContext, { }, strokeSource, shadowState, Stroke);
prepareForStroking(cr, strokeSource, PreserveAlpha);
cairo_stroke(cr);
cairo_restore(cr);
}
void strokePath(GraphicsContextCairo& platformContext, const Path& path, const StrokeSource& strokeSource, const ShadowState& shadowState)
{
cairo_t* cr = platformContext.cr();
setPathOnCairoContext(cr, path.platformPath());
drawPathShadow(platformContext, { }, strokeSource, shadowState, Stroke);
prepareForStroking(cr, strokeSource, PreserveAlpha);
cairo_stroke(cr);
}
void clearRect(GraphicsContextCairo& platformContext, const FloatRect& rect)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_fill(cr);
cairo_restore(cr);
}
void drawGlyphs(GraphicsContextCairo& platformContext, const FillSource& fillSource, const StrokeSource& strokeSource, const ShadowState& shadowState, const FloatPoint& point, cairo_scaled_font_t* scaledFont, double syntheticBoldOffset, const Vector<cairo_glyph_t>& glyphs, float xOffset, TextDrawingModeFlags textDrawingMode, float strokeThickness, std::optional<GraphicsDropShadow> dropShadow, FontSmoothingMode fontSmoothingMode)
{
#if USE(FREETYPE)
Locker cairoFontLocker(cairoFontLock());
#endif
if (dropShadow)
drawGlyphsShadow(platformContext, shadowState, textDrawingMode, *dropShadow, point, scaledFont, syntheticBoldOffset, glyphs, fontSmoothingMode);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
if (textDrawingMode.contains(TextDrawingMode::Fill)) {
prepareForFilling(cr, fillSource, AdjustPatternForGlobalAlpha);
drawGlyphsToContext(cr, scaledFont, syntheticBoldOffset, glyphs, fontSmoothingMode);
}
// Prevent running into a long computation within cairo. If the stroke width is
// twice the size of the width of the text we will not ask cairo to stroke
// the text as even one single stroke would cover the full wdth of the text.
// See https://bugs.webkit.org/show_bug.cgi?id=33759.
if (textDrawingMode.contains(TextDrawingMode::Stroke) && strokeThickness < 2 * xOffset) {
prepareForStroking(cr, strokeSource, PreserveAlpha);
cairo_set_line_width(cr, strokeThickness);
// This may disturb the CTM, but we are going to call cairo_restore soon after.
cairo_set_scaled_font(cr, scaledFont);
cairo_glyph_path(cr, glyphs.data(), glyphs.size());
cairo_stroke(cr);
}
cairo_restore(cr);
}
void drawPlatformImage(GraphicsContextCairo& platformContext, cairo_surface_t* surface, const FloatRect& destRect, const FloatRect& srcRect, ImagePaintingOptions options, float globalAlpha, const ShadowState& shadowState)
{
platformContext.save();
// Set the compositing operation.
if (options.compositeOperator() == CompositeOperator::SourceOver && options.blendMode() == BlendMode::Normal && !cairoSurfaceHasAlpha(surface))
Cairo::State::setCompositeOperation(platformContext, CompositeOperator::Copy, BlendMode::Normal);
else
Cairo::State::setCompositeOperation(platformContext, options.compositeOperator(), options.blendMode());
FloatRect dst = destRect;
if (options.orientation() != ImageOrientation::Orientation::None) {
// ImageOrientation expects the origin to be at (0, 0).
Cairo::translate(platformContext, dst.x(), dst.y());
dst.setLocation(FloatPoint());
Cairo::concatCTM(platformContext, options.orientation().transformFromDefault(dst.size()));
if (options.orientation().usesWidthAsHeight()) {
// The destination rectangle will have its width and height already reversed for the orientation of
// the image, as it was needed for page layout, so we need to reverse it back here.
dst = FloatRect(dst.x(), dst.y(), dst.height(), dst.width());
}
}
auto orientationSizing = options.orientation().usesWidthAsHeight() ? OrientationSizing::WidthAsHeight : OrientationSizing::Normal;
drawSurface(platformContext, surface, dst, srcRect, options.interpolationQuality(), globalAlpha, shadowState, orientationSizing);
platformContext.restore();
}
void drawPattern(GraphicsContextCairo& platformContext, cairo_surface_t* surface, const IntSize& size, const FloatRect& destRect, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize& spacing, ImagePaintingOptions options)
{
// FIXME: Investigate why the size has to be passed in as an IntRect.
drawPatternToCairoContext(platformContext.cr(), surface, size, tileRect, patternTransform, phase, spacing, toCairoOperator(options.compositeOperator(), options.blendMode()), options.interpolationQuality(), destRect);
}
static IntRect calculateSubsurfaceRect(FloatRect& dest, FloatRect& src, const IntSize& surface, FloatSize& padding)
{
// When the source rectangle is outside the source image, the source rectangle must be clipped
// to the source image and the destination rectangle must be clipped in the same proportion.
auto calc1d = [](float& dest1, float& destSize, float& src1, float& srcSize, float surfaceWidth, float& padding) -> std::tuple<int, int> {
ASSERT(destSize);
ASSERT(srcSize);
ASSERT(surfaceWidth > 0);
// Cairo subsurfaces don't support floating point boundaries well, so we expand the rectangle.
int expanded1, expanded2;
float dest2 = dest1 + destSize;
if (destSize < 0) {
destSize = -destSize;
std::swap(dest1, dest2);
}
float src2 = src1 + srcSize;
if (srcSize < 0) {
srcSize = -srcSize;
std::swap(src1, src2);
}
if (src2 <= 0 || src1 >= surfaceWidth)
return { };
if (src1 < 0) {
dest1 += -src1 * destSize / srcSize;
src1 = 0;
expanded1 = 0;
} else {
expanded1 = floor(src1);
padding = src1 - expanded1;
}
if (src2 < surfaceWidth)
expanded2 = ceil(src2);
else {
dest2 -= (src2 - surfaceWidth) * destSize / srcSize;
src2 = surfaceWidth;
expanded2 = surfaceWidth;
}
destSize = dest2 - dest1;
srcSize = src2 - src1;
ASSERT(destSize > 0);
ASSERT(srcSize > 0);
return { expanded1, expanded2 - expanded1 };
};
float xDestLocation = dest.x();
float xDestSize = dest.width();
float xSrcLocation = src.x();
float xSrcSize = src.width();
float xPadding = padding.width();
auto [xExpandedLocation, xExpandedSize] = calc1d(xDestLocation, xDestSize, xSrcLocation, xSrcSize, surface.width(), xPadding);
float yDestLocation = dest.y();
float yDestSize = dest.height();
float ySrcLocation = src.y();
float ySrcSize = src.height();
float yPadding = padding.height();
auto [yExpandedLocation, yExpandedSize] = calc1d(yDestLocation, yDestSize, ySrcLocation, ySrcSize, surface.height(), yPadding);
dest.setLocation({ xDestLocation, yDestLocation });
dest.setSize({ xDestSize, yDestSize });
src.setLocation({ xSrcLocation, ySrcLocation });
src.setSize({ xSrcSize, ySrcSize });
padding.setWidth(xPadding);
padding.setHeight(yPadding);
return { xExpandedLocation, yExpandedLocation, xExpandedSize, yExpandedSize };
}
void drawSurface(GraphicsContextCairo& platformContext, cairo_surface_t* surface, const FloatRect& originalDestRect, const FloatRect& originalSrcRect, InterpolationQuality imageInterpolationQuality, float globalAlpha, const ShadowState& shadowState, OrientationSizing orientationSizing)
{
// Avoid invalid cairo matrix with small values.
if (std::abs(originalDestRect.width()) < 0.5f || std::abs(originalDestRect.height()) < 0.5f)
return;
FloatRect destRect = originalDestRect;
FloatRect srcRect = originalSrcRect;
// We need to account for negative source dimensions by flipping the rectangle.
if (originalSrcRect.width() < 0) {
srcRect.setX(originalSrcRect.x() + originalSrcRect.width());
srcRect.setWidth(std::abs(originalSrcRect.width()));
}
if (originalSrcRect.height() < 0) {
srcRect.setY(originalSrcRect.y() + originalSrcRect.height());
srcRect.setHeight(std::abs(originalSrcRect.height()));
}
RefPtr<cairo_surface_t> patternSurface = surface;
FloatSize padding;
auto surfaceSize = cairoSurfaceSize(surface);
if (surfaceSize.isEmpty())
return;
bool didUseWidthAsHeight = orientationSizing == OrientationSizing::WidthAsHeight;
if (didUseWidthAsHeight)
surfaceSize = surfaceSize.transposedSize();
bool differentSize = srcRect.size() != surfaceSize;
if (srcRect.x() || srcRect.y() || differentSize) {
IntRect subsurfaceRect = calculateSubsurfaceRect(destRect, srcRect, surfaceSize, padding);
// We use a subsurface here so that we don't end up sampling outside the originalSrcRect rectangle.
// See https://bugs.webkit.org/show_bug.cgi?id=58309
patternSurface = adoptRef(cairo_surface_create_for_rectangle(surface, subsurfaceRect.x(),
subsurfaceRect.y(), subsurfaceRect.width(), subsurfaceRect.height()));
}
RefPtr<cairo_pattern_t> pattern = adoptRef(cairo_pattern_create_for_surface(patternSurface.get()));
switch (imageInterpolationQuality) {
case InterpolationQuality::DoNotInterpolate:
cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_FAST);
break;
case InterpolationQuality::Low:
cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_BILINEAR);
break;
case InterpolationQuality::Medium:
case InterpolationQuality::Default:
cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_GOOD);
break;
case InterpolationQuality::High:
cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_BEST);
break;
}
cairo_pattern_set_extend(pattern.get(), CAIRO_EXTEND_PAD);
// The pattern transformation properly scales the pattern for when the source rectangle is a
// different size than the destination rectangle. We also account for any offset we introduced
// by expanding floating point source rectangle sizes. It's important to take the absolute value
// of the scale since the original width and height might be negative.
float scaleX = 1;
float scaleY = 1;
if (didUseWidthAsHeight) {
scaleX = std::abs(srcRect.width() / destRect.height());
scaleY = std::abs(srcRect.height() / destRect.width());
} else {
scaleX = std::abs(srcRect.width() / destRect.width());
scaleY = std::abs(srcRect.height() / destRect.height());
}
cairo_matrix_t matrix = { scaleX, 0, 0, scaleY, padding.width(), padding.height() };
cairo_pattern_set_matrix(pattern.get(), &matrix);
ShadowBlur shadow({ shadowState.blur, shadowState.blur }, shadowState.offset, shadowState.color, shadowState.ignoreTransforms);
if (shadow.type() != ShadowBlur::NoShadow) {
shadow.drawShadowLayer(State::getCTM(platformContext), State::getClipBounds(platformContext), destRect,
[&pattern, &destRect](GraphicsContext& shadowContext)
{
drawPatternToCairoContext(shadowContext.platformContext()->cr(), pattern.get(), destRect, 1);
},
[&platformContext, &shadowState](ImageBuffer& layerImage, const FloatPoint& layerOrigin, const FloatSize& layerSize)
{
drawShadowLayerBuffer(platformContext, layerImage, layerOrigin, layerSize, shadowState);
});
}
auto* cr = platformContext.cr();
cairo_save(cr);
drawPatternToCairoContext(cr, pattern.get(), destRect, globalAlpha);
cairo_restore(cr);
}
void drawRect(GraphicsContextCairo& platformContext, const FloatRect& rect, float borderThickness, const Color& fillColor, StrokeStyle strokeStyle, const Color& strokeColor)
{
// FIXME: how should borderThickness be used?
UNUSED_PARAM(borderThickness);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
fillRectWithColor(cr, rect, fillColor);
if (strokeStyle != StrokeStyle::NoStroke) {
setSourceRGBAFromColor(cr, strokeColor);
FloatRect r(rect);
r.inflate(-.5f);
cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
cairo_set_line_width(cr, 1.0); // borderThickness?
cairo_stroke(cr);
}
cairo_restore(cr);
}
void drawLine(GraphicsContextCairo& platformContext, const FloatPoint& point1, const FloatPoint& point2, StrokeStyle strokeStyle, const Color& strokeColor, float strokeThickness, bool shouldAntialias)
{
bool isVerticalLine = (point1.x() + strokeThickness == point2.x());
float strokeWidth = isVerticalLine ? point2.y() - point1.y() : point2.x() - point1.x();
if (!strokeThickness || !strokeWidth)
return;
cairo_t* cairoContext = platformContext.cr();
float cornerWidth = 0;
bool drawsDashedLine = strokeStyle == StrokeStyle::DottedStroke || strokeStyle == StrokeStyle::DashedStroke;
if (drawsDashedLine) {
cairo_save(cairoContext);
// Figure out end points to ensure we always paint corners.
cornerWidth = dashedLineCornerWidthForStrokeWidth(strokeWidth, strokeStyle, strokeThickness);
if (isVerticalLine) {
fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), strokeThickness, cornerWidth), strokeColor);
fillRectWithColor(cairoContext, FloatRect(point1.x(), point2.y() - cornerWidth, strokeThickness, cornerWidth), strokeColor);
} else {
fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), cornerWidth, strokeThickness), strokeColor);
fillRectWithColor(cairoContext, FloatRect(point2.x() - cornerWidth, point1.y(), cornerWidth, strokeThickness), strokeColor);
}
strokeWidth -= 2 * cornerWidth;
float patternWidth = dashedLinePatternWidthForStrokeWidth(strokeWidth, strokeStyle, strokeThickness);
// Check if corner drawing sufficiently covers the line.
if (strokeWidth <= patternWidth + 1) {
cairo_restore(cairoContext);
return;
}
float patternOffset = dashedLinePatternOffsetForPatternAndStrokeWidth(patternWidth, strokeWidth);
const double dashedLine[2] = { static_cast<double>(patternWidth), static_cast<double>(patternWidth) };
cairo_set_dash(cairoContext, dashedLine, 2, patternOffset);
} else {
setSourceRGBAFromColor(cairoContext, strokeColor);
if (strokeThickness < 1)
cairo_set_line_width(cairoContext, 1);
}
auto centeredPoints = centerLineAndCutOffCorners(isVerticalLine, cornerWidth, point1, point2);
auto p1 = centeredPoints[0];
auto p2 = centeredPoints[1];
if (shouldAntialias)
cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_NONE);
cairo_new_path(cairoContext);
cairo_move_to(cairoContext, p1.x(), p1.y());
cairo_line_to(cairoContext, p2.x(), p2.y());
cairo_stroke(cairoContext);
if (drawsDashedLine)
cairo_restore(cairoContext);
if (shouldAntialias)
cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_DEFAULT);
}
void drawLinesForText(GraphicsContextCairo& platformContext, const FloatPoint& point, float strokeThickness, std::span<const FloatSegment> lineSegments, bool printing, bool doubleUnderlines, const Color& color)
{
Color modifiedColor = color;
FloatRect bounds = computeLineBoundsAndAntialiasingModeForText(platformContext, point, lineSegments.back().end, printing, modifiedColor, strokeThickness);
Vector<FloatRect, 4> dashBounds;
dashBounds.reserveInitialCapacity(lineSegments.size());
for (const auto& lineSegment : lineSegments)
dashBounds.append(FloatRect(FloatPoint(bounds.x() + lineSegment.begin, bounds.y()), FloatSize(lineSegment.length(), bounds.height())));
if (doubleUnderlines) {
// The space between double underlines is equal to the height of the underline
for (auto& lineSegment : lineSegments)
dashBounds.append(FloatRect(FloatPoint(bounds.x() + lineSegment.begin, bounds.y() + 2 * bounds.height()), FloatSize(lineSegment.length(), bounds.height())));
}
cairo_t* cr = platformContext.cr();
cairo_save(cr);
for (auto& dash : dashBounds)
fillRectWithColor(cr, dash, modifiedColor);
cairo_restore(cr);
}
void drawDotsForDocumentMarker(GraphicsContextCairo& platformContext, const FloatRect& rect, DocumentMarkerLineStyle style)
{
if (style.mode != DocumentMarkerLineStyleMode::Spelling
&& style.mode != DocumentMarkerLineStyleMode::Grammar)
return;
cairo_t* cr = platformContext.cr();
cairo_save(cr);
auto [r, g, b, a] = style.color.toColorTypeLossy<SRGBA<uint8_t>>().resolved();
cairo_set_source_rgba(cr, r, g, b, a);
drawErrorUnderline(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_restore(cr);
}
void drawEllipse(GraphicsContextCairo& platformContext, const FloatRect& rect, const Color& fillColor, StrokeStyle strokeStyle, const Color& strokeColor, float strokeThickness)
{
cairo_t* cr = platformContext.cr();
cairo_save(cr);
float yRadius = .5 * rect.height();
float xRadius = .5 * rect.width();
cairo_translate(cr, rect.x() + xRadius, rect.y() + yRadius);
cairo_scale(cr, xRadius, yRadius);
cairo_arc(cr, 0., 0., 1., 0., 2 * piFloat);
cairo_restore(cr);
if (fillColor.isVisible()) {
setSourceRGBAFromColor(cr, fillColor);
cairo_fill_preserve(cr);
}
if (strokeStyle != StrokeStyle::NoStroke) {
setSourceRGBAFromColor(cr, strokeColor);
cairo_set_line_width(cr, strokeThickness);
cairo_stroke(cr);
} else
cairo_new_path(cr);
}
void drawFocusRing(GraphicsContextCairo& platformContext, const Path& path, float width, const Color& color)
{
// FIXME: We should draw paths that describe a rectangle with rounded corners
// so as to be consistent with how we draw rectangular focus rings.
// Force the alpha to 50%. This matches what the Mac does with outline rings.
Color ringColor = color.colorWithAlpha(.5);
cairo_t* cr = platformContext.cr();
cairo_save(cr);
cairo_push_group(cr);
appendWebCorePathToCairoContext(cr, path);
setSourceRGBAFromColor(cr, ringColor);
cairo_set_line_width(cr, width);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_stroke_preserve(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
cairo_fill(cr);
cairo_pop_group_to_source(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_paint(cr);
cairo_restore(cr);
}
void drawFocusRing(GraphicsContextCairo& platformContext, const Vector<FloatRect>& rects, float width, const Color& color)
{
Path path;
unsigned rectCount = rects.size();
int radius = (width - 1) / 2;
Path subPath;
for (unsigned i = 0; i < rectCount; ++i) {
if (i > 0)
subPath.clear();
subPath.addRoundedRect(rects[i], FloatSize(radius, radius));
path.addPath(subPath, AffineTransform());
}
drawFocusRing(platformContext, path, width, color);
}
void translate(GraphicsContextCairo& platformContext, float x, float y)
{
cairo_translate(platformContext.cr(), x, y);
}
void rotate(GraphicsContextCairo& platformContext, float angleInRadians)
{
cairo_rotate(platformContext.cr(), angleInRadians);
}
void scale(GraphicsContextCairo& platformContext, const FloatSize& size)
{
cairo_scale(platformContext.cr(), size.width(), size.height());
}
void concatCTM(GraphicsContextCairo& platformContext, const AffineTransform& transform)
{
const cairo_matrix_t matrix = toCairoMatrix(transform);
cairo_transform(platformContext.cr(), &matrix);
}
void beginTransparencyLayer(GraphicsContextCairo& platformContext, float opacity)
{
cairo_push_group(platformContext.cr());
platformContext.layers().append(opacity);
}
void endTransparencyLayer(GraphicsContextCairo& platformContext)
{
cairo_t* cr = platformContext.cr();
cairo_pop_group_to_source(cr);
cairo_paint_with_alpha(cr, platformContext.layers().takeLast());
}
static void doClipWithAntialias(cairo_t* cr, cairo_antialias_t antialias)
{
auto savedAntialiasRule = cairo_get_antialias(cr);
cairo_set_antialias(cr, antialias);
cairo_clip(cr);
cairo_set_antialias(cr, savedAntialiasRule);
}
static FloatRect clampClipRect(const FloatRect& rect)
{
// Cairo is internally using 24.8 fixed point numbers.
float maxValue = 1 << 22;
auto x = std::max(rect.x(), -maxValue / 2);
auto y = std::max(rect.y(), -maxValue / 2);
auto width = std::min(rect.width(), maxValue);
auto height = std::min(rect.height(), maxValue);
return { x, y, width, height };
}
void clip(GraphicsContextCairo& platformContext, const FloatRect& clipRect)
{
cairo_t* cr = platformContext.cr();
auto rect = clampClipRect(clipRect);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
// The rectangular clip function is traditionally not expected to
// antialias. If we don't force antialiased clipping here,
// edge fringe artifacts may occur at the layer edges
// when a transformation is applied to the GraphicsContext
// while drawing the transformed layer.
doClipWithAntialias(cr, CAIRO_ANTIALIAS_NONE);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipOut(GraphicsContextCairo& platformContext, const FloatRect& rect)
{
cairo_t* cr = platformContext.cr();
double x1, y1, x2, y2;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
doClipWithAntialias(cr, CAIRO_ANTIALIAS_NONE);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipOut(GraphicsContextCairo& platformContext, const Path& path)
{
cairo_t* cr = platformContext.cr();
double x1, y1, x2, y2;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
appendWebCorePathToCairoContext(cr, path);
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
// Enforce default antialias when clipping paths, since they can contain curves.
doClipWithAntialias(cr, CAIRO_ANTIALIAS_DEFAULT);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipPath(GraphicsContextCairo& platformContext, const Path& path, WindRule clipRule)
{
cairo_t* cr = platformContext.cr();
if (!path.isEmpty())
setPathOnCairoContext(cr, path.platformPath());
cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
cairo_set_fill_rule(cr, clipRule == WindRule::EvenOdd ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
// Enforce default antialias when clipping paths, since they can contain curves.
doClipWithAntialias(cr, CAIRO_ANTIALIAS_DEFAULT);
cairo_set_fill_rule(cr, savedFillRule);
}
void clipToImageBuffer(GraphicsContextCairo& platformContext, cairo_surface_t* image, const FloatRect& destRect)
{
platformContext.pushImageMask(image, destRect);
}
} // namespace Cairo
} // namespace WebCore
#endif // USE(CAIRO)
|