DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (fddffdeab170)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <dlfcn.h>
#include "BorrowedContext.h"
#include "DataSurfaceHelpers.h"
#include "DrawTargetCG.h"
#include "Logging.h"
#include "SourceSurfaceCG.h"
#include "Rect.h"
#include "ScaledFontMac.h"
#include "Tools.h"
#include "PathHelpers.h"
#include <vector>
#include <algorithm>
#include "MacIOSurface.h"
#include "FilterNodeSoftware.h"
#include "mozilla/Assertions.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Types.h" // for decltype
#include "mozilla/Vector.h"

using namespace std;

//CG_EXTERN void CGContextSetCompositeOperation (CGContextRef, PrivateCGCompositeMode);

// A private API that Cairo has been using for a long time
CG_EXTERN void CGContextSetCTM(CGContextRef, CGAffineTransform);

namespace mozilla {
namespace gfx {

template <typename T>
static CGRect RectToCGRect(const T& r)
{
  return CGRectMake(r.x, r.y, r.width, r.height);
}

CGBlendMode ToBlendMode(CompositionOp op)
{
  CGBlendMode mode;
  switch (op) {
    case CompositionOp::OP_OVER:
      mode = kCGBlendModeNormal;
      break;
    case CompositionOp::OP_ADD:
      mode = kCGBlendModePlusLighter;
      break;
    case CompositionOp::OP_ATOP:
      mode = kCGBlendModeSourceAtop;
      break;
    case CompositionOp::OP_OUT:
      mode = kCGBlendModeSourceOut;
      break;
    case CompositionOp::OP_IN:
      mode = kCGBlendModeSourceIn;
      break;
    case CompositionOp::OP_SOURCE:
      mode = kCGBlendModeCopy;
      break;
    case CompositionOp::OP_DEST_IN:
      mode = kCGBlendModeDestinationIn;
      break;
    case CompositionOp::OP_DEST_OUT:
      mode = kCGBlendModeDestinationOut;
      break;
    case CompositionOp::OP_DEST_OVER:
      mode = kCGBlendModeDestinationOver;
      break;
    case CompositionOp::OP_DEST_ATOP:
      mode = kCGBlendModeDestinationAtop;
      break;
    case CompositionOp::OP_XOR:
      mode = kCGBlendModeXOR;
      break;
    case CompositionOp::OP_MULTIPLY:
      mode = kCGBlendModeMultiply;
      break;
    case CompositionOp::OP_SCREEN:
      mode = kCGBlendModeScreen;
      break;
    case CompositionOp::OP_OVERLAY:
      mode = kCGBlendModeOverlay;
      break;
    case CompositionOp::OP_DARKEN:
      mode = kCGBlendModeDarken;
      break;
    case CompositionOp::OP_LIGHTEN:
      mode = kCGBlendModeLighten;
      break;
    case CompositionOp::OP_COLOR_DODGE:
      mode = kCGBlendModeColorDodge;
      break;
    case CompositionOp::OP_COLOR_BURN:
      mode = kCGBlendModeColorBurn;
      break;
    case CompositionOp::OP_HARD_LIGHT:
      mode = kCGBlendModeHardLight;
      break;
    case CompositionOp::OP_SOFT_LIGHT:
      mode = kCGBlendModeSoftLight;
      break;
    case CompositionOp::OP_DIFFERENCE:
      mode = kCGBlendModeDifference;
      break;
    case CompositionOp::OP_EXCLUSION:
      mode = kCGBlendModeExclusion;
      break;
    case CompositionOp::OP_HUE:
      mode = kCGBlendModeHue;
      break;
    case CompositionOp::OP_SATURATION:
      mode = kCGBlendModeSaturation;
      break;
    case CompositionOp::OP_COLOR:
      mode = kCGBlendModeColor;
      break;
    case CompositionOp::OP_LUMINOSITY:
      mode = kCGBlendModeLuminosity;
      break;
      /*
    case OP_CLEAR:
      mode = kCGBlendModeClear;
      break;*/
    default:
      mode = kCGBlendModeNormal;
  }
  return mode;
}

static CGInterpolationQuality
InterpolationQualityFromFilter(Filter aFilter)
{
  switch (aFilter) {
    default:
    case Filter::LINEAR:
      return kCGInterpolationLow;
    case Filter::POINT:
      return kCGInterpolationNone;
    case Filter::GOOD:
      return kCGInterpolationLow;
  }
}


DrawTargetCG::DrawTargetCG()
  : mColorSpace(nullptr)
  , mCg(nullptr)
  , mMayContainInvalidPremultipliedData(false)
{
}

DrawTargetCG::~DrawTargetCG()
{
  if (mSnapshot) {
    if (mSnapshot->refCount() > 1) {
      // We only need to worry about snapshots that someone else knows about
      mSnapshot->DrawTargetWillGoAway();
    }
    mSnapshot = nullptr;
  }

  // Both of these are OK with nullptr arguments, so we do not
  // need to check (these could be nullptr if Init fails)
  CGColorSpaceRelease(mColorSpace);
  CGContextRelease(mCg);
}

DrawTargetType
DrawTargetCG::GetType() const
{
  return GetBackendType() == BackendType::COREGRAPHICS_ACCELERATED ?
           DrawTargetType::HARDWARE_RASTER : DrawTargetType::SOFTWARE_RASTER;
}

BackendType
DrawTargetCG::GetBackendType() const
{
#ifdef MOZ_WIDGET_COCOA
  // It may be worth spliting Bitmap and IOSurface DrawTarget
  // into seperate classes.
  if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
    return BackendType::COREGRAPHICS_ACCELERATED;
  } else {
    return BackendType::COREGRAPHICS;
  }
#else
  return BackendType::COREGRAPHICS;
#endif
}

already_AddRefed<SourceSurface>
DrawTargetCG::Snapshot()
{
  if (!mSnapshot) {
#ifdef MOZ_WIDGET_COCOA
    if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
      return MakeAndAddRef<SourceSurfaceCGIOSurfaceContext>(this);
    }
#endif
    Flush();
    mSnapshot = new SourceSurfaceCGBitmapContext(this);
  }

  RefPtr<SourceSurface> snapshot(mSnapshot);
  return snapshot.forget();
}

already_AddRefed<DrawTarget>
DrawTargetCG::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
{
  // XXX: in thebes we use CGLayers to do this kind of thing. It probably makes sense
  // to add that in somehow, but at a higher level
  RefPtr<DrawTargetCG> newTarget = new DrawTargetCG();
  if (newTarget->Init(GetBackendType(), aSize, aFormat)) {
    return newTarget.forget();
  }
  return nullptr;
}

already_AddRefed<SourceSurface>
DrawTargetCG::CreateSourceSurfaceFromData(unsigned char *aData,
                                           const IntSize &aSize,
                                           int32_t aStride,
                                           SurfaceFormat aFormat) const
{
  RefPtr<SourceSurfaceCG> newSurf = new SourceSurfaceCG();

  if (!newSurf->InitFromData(aData, aSize, aStride, aFormat)) {
    return nullptr;
  }

  return newSurf.forget();
}

static void releaseDataSurface(void* info, const void *data, size_t size)
{
  static_cast<DataSourceSurface*>(info)->Release();
}

// This function returns a retained CGImage that needs to be released after
// use. The reason for this is that we want to either reuse an existing CGImage
// or create a new one.
static CGImageRef
GetRetainedImageFromSourceSurface(SourceSurface *aSurface)
{
  switch(aSurface->GetType()) {
    case SurfaceType::COREGRAPHICS_IMAGE:
      return CGImageRetain(static_cast<SourceSurfaceCG*>(aSurface)->GetImage());

    case SurfaceType::COREGRAPHICS_CGCONTEXT:
      return CGImageRetain(static_cast<SourceSurfaceCGContext*>(aSurface)->GetImage());

    default:
    {
      RefPtr<DataSourceSurface> data = aSurface->GetDataSurface();
      if (!data) {
        MOZ_CRASH("unsupported source surface");
      }
      data.get()->AddRef();
      return CreateCGImage(releaseDataSurface, data.get(),
                           data->GetData(), data->GetSize(),
                           data->Stride(), data->GetFormat());
    }
  }
}

already_AddRefed<SourceSurface>
DrawTargetCG::OptimizeSourceSurface(SourceSurface *aSurface) const
{
  RefPtr<SourceSurface> surface(aSurface);
  return surface.forget();
}

class UnboundnessFixer
{
    CGRect mClipBounds;
    CGLayerRef mLayer;
    CGContextRef mLayerCg;
  public:
    UnboundnessFixer() : mLayerCg(nullptr) {}

    CGContextRef Check(DrawTargetCG* dt, CompositionOp blend, const Rect* maskBounds = nullptr)
    {
      MOZ_ASSERT(dt->mCg);
      if (!IsOperatorBoundByMask(blend)) {
        // The clip bounding box will be in user space so we need to clear our transform first
        CGContextSetCTM(dt->mCg, dt->mOriginalTransform);
        mClipBounds = CGContextGetClipBoundingBox(dt->mCg);

        // If we're entirely clipped out or if the drawing operation covers the entire clip then
        // we don't need to create a temporary surface.
        if (CGRectIsEmpty(mClipBounds) ||
            (maskBounds && maskBounds->Contains(CGRectToRect(mClipBounds)))) {
          CGContextConcatCTM(dt->mCg, GfxMatrixToCGAffineTransform(dt->mTransform));
          return dt->mCg;
        }

        // TransparencyLayers aren't blended using the blend mode so
        // we are forced to use CGLayers

        //XXX: The size here is in default user space units, of the layer relative to the graphics context.
        // is the clip bounds still correct if, for example, we have a scale applied to the context?
        mLayer = CGLayerCreateWithContext(dt->mCg, mClipBounds.size, nullptr);
        mLayerCg = CGLayerGetContext(mLayer);
        // CGContext's default to have the origin at the bottom left
        // so flip it to the top left and adjust for the origin
        // of the layer
        if (MOZ2D_ERROR_IF(!mLayerCg)) {
          return nullptr;
        }
        CGContextTranslateCTM(mLayerCg, -mClipBounds.origin.x, mClipBounds.origin.y + mClipBounds.size.height);
        CGContextScaleCTM(mLayerCg, 1, -1);
        CGContextConcatCTM(mLayerCg, GfxMatrixToCGAffineTransform(dt->mTransform));

        return mLayerCg;
      } else {
        return dt->mCg;
      }
    }

    void Fix(DrawTargetCG *dt)
    {
        if (mLayerCg) {
            // we pushed a layer so draw it to dt->mCg
            MOZ_ASSERT(dt->mCg);
            CGContextTranslateCTM(dt->mCg, 0, mClipBounds.size.height);
            CGContextScaleCTM(dt->mCg, 1, -1);
            mClipBounds.origin.y *= -1;
            CGContextDrawLayerAtPoint(dt->mCg, mClipBounds.origin, mLayer);
            CGContextRelease(mLayerCg);

            // Reset the transform
            CGContextConcatCTM(dt->mCg, GfxMatrixToCGAffineTransform(dt->mTransform));
        }
    }
};

void
DrawTargetCG::DrawSurface(SourceSurface *aSurface,
                           const Rect &aDest,
                           const Rect &aSource,
                           const DrawSurfaceOptions &aSurfOptions,
                           const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }
  MarkChanged();

  CGContextSaveGState(mCg);

  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp, &aDest);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }
  CGContextSetAlpha(cg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);

  CGContextSetInterpolationQuality(cg, InterpolationQualityFromFilter(aSurfOptions.mFilter));

  CGImageRef image = GetRetainedImageFromSourceSurface(aSurface);

  if (aSurfOptions.mFilter == Filter::POINT) {
    CGImageRef subimage = CGImageCreateWithImageInRect(image, RectToCGRect(aSource));
    CGImageRelease(image);

    CGContextScaleCTM(cg, 1, -1);

    CGRect flippedRect = CGRectMake(aDest.x, -(aDest.y + aDest.height),
                                    aDest.width, aDest.height);

    CGContextDrawImage(cg, flippedRect, subimage);
    CGImageRelease(subimage);
  } else {
    CGRect destRect = CGRectMake(aDest.x, aDest.y, aDest.width, aDest.height);
    CGContextClipToRect(cg, destRect);

    float xScale = aSource.width / aDest.width;
    float yScale = aSource.height / aDest.height;
    CGContextTranslateCTM(cg, aDest.x - aSource.x / xScale, aDest.y - aSource.y / yScale);

    CGRect adjustedDestRect = CGRectMake(0, 0, CGImageGetWidth(image) / xScale,
                                         CGImageGetHeight(image) / yScale);

    CGContextTranslateCTM(cg, 0, CGRectGetHeight(adjustedDestRect));
    CGContextScaleCTM(cg, 1, -1);

    CGContextDrawImage(cg, adjustedDestRect, image);
    CGImageRelease(image);
  }

  fixer.Fix(this);

  CGContextRestoreGState(mCg);
}

already_AddRefed<FilterNode>
DrawTargetCG::CreateFilter(FilterType aType)
{
  return FilterNodeSoftware::Create(aType);
}

void
DrawTargetCG::DrawFilter(FilterNode *aNode,
                         const Rect &aSourceRect,
                         const Point &aDestPoint,
                         const DrawOptions &aOptions)
{
  FilterNodeSoftware* filter = static_cast<FilterNodeSoftware*>(aNode);
  filter->Draw(this, aSourceRect, aDestPoint, aOptions);
}

static CGColorRef ColorToCGColor(CGColorSpaceRef aColorSpace, const Color& aColor)
{
  CGFloat components[4] = {aColor.r, aColor.g, aColor.b, aColor.a};
  return CGColorCreate(aColorSpace, components);
}

class GradientStopsCG : public GradientStops
{
  public:
  MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(GradientStopsCG)

  GradientStopsCG(CGColorSpaceRef aColorSpace,
                  const std::vector<GradientStop>& aStops,
                  ExtendMode aExtendMode)
    : mGradient(nullptr)
  {
    // This all works fine with empty aStops vector

    mExtend = aExtendMode;
    if (aExtendMode == ExtendMode::CLAMP) {
      size_t numStops = aStops.size();

      std::vector<CGFloat> colors;
      std::vector<CGFloat> offsets;
      colors.reserve(numStops*4);
      offsets.reserve(numStops);

      for (size_t i = 0; i < numStops; i++) {
        colors.push_back(aStops[i].color.r);
        colors.push_back(aStops[i].color.g);
        colors.push_back(aStops[i].color.b);
        colors.push_back(aStops[i].color.a);

        offsets.push_back(aStops[i].offset);
      }

      mGradient = CGGradientCreateWithColorComponents(aColorSpace,
                                                      &colors.front(),
                                                      &offsets.front(),
                                                      offsets.size());
    } else {
      mStops = aStops;
    }

  }

  virtual ~GradientStopsCG() {
    // CGGradientRelease is OK with nullptr argument
    CGGradientRelease(mGradient);
  }

  // Will always report BackendType::COREGRAPHICS, but it is compatible
  // with BackendType::COREGRAPHICS_ACCELERATED
  BackendType GetBackendType() const { return BackendType::COREGRAPHICS; }
  // XXX this should be a union
  CGGradientRef mGradient;
  std::vector<GradientStop> mStops;
  ExtendMode mExtend;
};

already_AddRefed<GradientStops>
DrawTargetCG::CreateGradientStops(GradientStop *aStops, uint32_t aNumStops,
                                  ExtendMode aExtendMode) const
{
  std::vector<GradientStop> stops(aStops, aStops+aNumStops);
  return MakeAndAddRef<GradientStopsCG>(mColorSpace, stops, aExtendMode);
}

static void
UpdateLinearParametersToIncludePoint(double *min_t, double *max_t,
                                     CGPoint *start,
                                     double dx, double dy,
                                     double x, double y)
{
  MOZ_ASSERT(IsFinite(x) && IsFinite(y));

  /**
   * Compute a parameter t such that a line perpendicular to the (dx,dy)
   * vector, passing through (start->x + dx*t, start->y + dy*t), also
   * passes through (x,y).
   *
   * Let px = x - start->x, py = y - start->y.
   * t is given by
   *   (px - dx*t)*dx + (py - dy*t)*dy = 0
   *
   * Solving for t we get
   *   numerator = dx*px + dy*py
   *   denominator = dx^2 + dy^2
   *   t = numerator/denominator
   *
   * In CalculateRepeatingGradientParams we know the length of (dx,dy)
   * is not zero. (This is checked in DrawLinearRepeatingGradient.)
   */
  double px = x - start->x;
  double py = y - start->y;
  double numerator = dx * px + dy * py;
  double denominator = dx * dx + dy * dy;
  double t = numerator / denominator;

  if (*min_t > t) {
    *min_t = t;
  }
  if (*max_t < t) {
    *max_t = t;
  }
}

/**
 * Repeat the gradient line such that lines extended perpendicular to the
 * gradient line at both start and end would completely enclose the drawing
 * extents.
 */
static void
CalculateRepeatingGradientParams(CGPoint *aStart, CGPoint *aEnd,
                                 CGRect aExtents, int *aRepeatStartFactor,
                                 int *aRepeatEndFactor)
{
  double t_min = INFINITY;
  double t_max = -INFINITY;
  double dx = aEnd->x - aStart->x;
  double dy = aEnd->y - aStart->y;

  double bounds_x1 = aExtents.origin.x;
  double bounds_y1 = aExtents.origin.y;
  double bounds_x2 = aExtents.origin.x + aExtents.size.width;
  double bounds_y2 = aExtents.origin.y + aExtents.size.height;

  UpdateLinearParametersToIncludePoint(&t_min, &t_max, aStart, dx, dy,
                                       bounds_x1, bounds_y1);
  UpdateLinearParametersToIncludePoint(&t_min, &t_max, aStart, dx, dy,
                                       bounds_x2, bounds_y1);
  UpdateLinearParametersToIncludePoint(&t_min, &t_max, aStart, dx, dy,
                                       bounds_x2, bounds_y2);
  UpdateLinearParametersToIncludePoint(&t_min, &t_max, aStart, dx, dy,
                                       bounds_x1, bounds_y2);

  MOZ_ASSERT(!isinf(t_min) && !isinf(t_max),
             "The first call to UpdateLinearParametersToIncludePoint should have made t_min and t_max non-infinite.");

  // Move t_min and t_max to the nearest usable integer to try to avoid
  // subtle variations due to numerical instability, especially accidentally
  // cutting off a pixel. Extending the gradient repetitions is always safe.
  t_min = floor (t_min);
  t_max = ceil (t_max);
  aEnd->x = aStart->x + dx * t_max;
  aEnd->y = aStart->y + dy * t_max;
  aStart->x = aStart->x + dx * t_min;
  aStart->y = aStart->y + dy * t_min;

  *aRepeatStartFactor = t_min;
  *aRepeatEndFactor = t_max;
}

static CGGradientRef
CreateRepeatingGradient(CGColorSpaceRef aColorSpace,
                        CGContextRef cg, GradientStopsCG* aStops,
                        int aRepeatStartFactor, int aRepeatEndFactor,
                        bool aReflect)
{
  int repeatCount = aRepeatEndFactor - aRepeatStartFactor;
  uint32_t stopCount = aStops->mStops.size();
  double scale = 1./repeatCount;

  std::vector<CGFloat> colors;
  std::vector<CGFloat> offsets;
  colors.reserve(stopCount*repeatCount*4);
  offsets.reserve(stopCount*repeatCount);

  for (int j = aRepeatStartFactor; j < aRepeatEndFactor; j++) {
    bool isReflected = aReflect && (j % 2) != 0;
    for (uint32_t i = 0; i < stopCount; i++) {
      uint32_t stopIndex = isReflected ? stopCount - i - 1 : i;
      colors.push_back(aStops->mStops[stopIndex].color.r);
      colors.push_back(aStops->mStops[stopIndex].color.g);
      colors.push_back(aStops->mStops[stopIndex].color.b);
      colors.push_back(aStops->mStops[stopIndex].color.a);

      CGFloat offset = aStops->mStops[stopIndex].offset;
      if (isReflected) {
        offset = 1 - offset;
      }
      offsets.push_back((offset + (j - aRepeatStartFactor)) * scale);
    }
  }

  CGGradientRef gradient = CGGradientCreateWithColorComponents(aColorSpace,
                                                               &colors.front(),
                                                               &offsets.front(),
                                                               repeatCount*stopCount);
  return gradient;
}

static void
DrawLinearRepeatingGradient(CGColorSpaceRef aColorSpace, CGContextRef cg,
                            const LinearGradientPattern &aPattern,
                            const CGRect &aExtents, bool aReflect)
{
  GradientStopsCG *stops = static_cast<GradientStopsCG*>(aPattern.mStops.get());
  CGPoint startPoint = { aPattern.mBegin.x, aPattern.mBegin.y };
  CGPoint endPoint = { aPattern.mEnd.x, aPattern.mEnd.y };

  int repeatStartFactor = 0, repeatEndFactor = 1;
  // if we don't have a line then we can't extend it
  if (aPattern.mEnd.x != aPattern.mBegin.x ||
      aPattern.mEnd.y != aPattern.mBegin.y) {
    CalculateRepeatingGradientParams(&startPoint, &endPoint, aExtents,
                                     &repeatStartFactor, &repeatEndFactor);
  }

  CGGradientRef gradient = CreateRepeatingGradient(aColorSpace, cg, stops, repeatStartFactor, repeatEndFactor, aReflect);

  CGContextDrawLinearGradient(cg, gradient, startPoint, endPoint,
                              kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
  CGGradientRelease(gradient);
}

static CGPoint CGRectTopLeft(CGRect a)
{ return a.origin; }
static CGPoint CGRectBottomLeft(CGRect a)
{ return CGPointMake(a.origin.x, a.origin.y + a.size.height); }
static CGPoint CGRectTopRight(CGRect a)
{ return CGPointMake(a.origin.x + a.size.width, a.origin.y); }
static CGPoint CGRectBottomRight(CGRect a)
{ return CGPointMake(a.origin.x + a.size.width, a.origin.y + a.size.height); }

static CGFloat
CGPointDistance(CGPoint a, CGPoint b)
{
  return hypot(a.x-b.x, a.y-b.y);
}

static void
DrawRadialRepeatingGradient(CGColorSpaceRef aColorSpace, CGContextRef cg,
                            const RadialGradientPattern &aPattern,
                            const CGRect &aExtents, bool aReflect)
{
  GradientStopsCG *stops = static_cast<GradientStopsCG*>(aPattern.mStops.get());
  CGPoint startCenter = { aPattern.mCenter1.x, aPattern.mCenter1.y };
  CGFloat startRadius = aPattern.mRadius1;
  CGPoint endCenter   = { aPattern.mCenter2.x, aPattern.mCenter2.y };
  CGFloat endRadius   = aPattern.mRadius2;

  // find the maximum distance from endCenter to a corner of aExtents
  CGFloat minimumEndRadius = endRadius;
  minimumEndRadius = max(minimumEndRadius, CGPointDistance(endCenter, CGRectTopLeft(aExtents)));
  minimumEndRadius = max(minimumEndRadius, CGPointDistance(endCenter, CGRectBottomLeft(aExtents)));
  minimumEndRadius = max(minimumEndRadius, CGPointDistance(endCenter, CGRectTopRight(aExtents)));
  minimumEndRadius = max(minimumEndRadius, CGPointDistance(endCenter, CGRectBottomRight(aExtents)));

  CGFloat length = endRadius - startRadius;
  int repeatStartFactor = 0, repeatEndFactor = 1;
  while (endRadius < minimumEndRadius) {
    endRadius += length;
    repeatEndFactor++;
  }

  while (startRadius-length >= 0) {
    startRadius -= length;
    repeatStartFactor--;
  }

  CGGradientRef gradient = CreateRepeatingGradient(aColorSpace, cg, stops, repeatStartFactor, repeatEndFactor, aReflect);

  //XXX: are there degenerate radial gradients that we should avoid drawing?
  CGContextDrawRadialGradient(cg, gradient, startCenter, startRadius, endCenter, endRadius,
                              kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
  CGGradientRelease(gradient);
}

static void
DrawGradient(CGColorSpaceRef aColorSpace,
             CGContextRef cg, const Pattern &aPattern, const CGRect &aExtents)
{
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  if (CGRectIsEmpty(aExtents)) {
    return;
  }

  if (aPattern.GetType() == PatternType::LINEAR_GRADIENT) {
    const LinearGradientPattern& pat = static_cast<const LinearGradientPattern&>(aPattern);
    GradientStopsCG *stops = static_cast<GradientStopsCG*>(pat.mStops.get());
    CGAffineTransform patternMatrix = GfxMatrixToCGAffineTransform(pat.mMatrix);
    CGContextConcatCTM(cg, patternMatrix);
    CGRect extents = CGRectApplyAffineTransform(aExtents, CGAffineTransformInvert(patternMatrix));
    if (stops->mExtend == ExtendMode::CLAMP) {

      // XXX: we should take the m out of the properties of LinearGradientPatterns
      CGPoint startPoint = { pat.mBegin.x, pat.mBegin.y };
      CGPoint endPoint   = { pat.mEnd.x,   pat.mEnd.y };

      // Canvas spec states that we should avoid drawing degenerate gradients (XXX: should this be in common code?)
      //if (startPoint.x == endPoint.x && startPoint.y == endPoint.y)
      //  return;

      CGContextDrawLinearGradient(cg, stops->mGradient, startPoint, endPoint,
                                  kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    } else if (stops->mExtend == ExtendMode::REPEAT || stops->mExtend == ExtendMode::REFLECT) {
      DrawLinearRepeatingGradient(aColorSpace, cg, pat, extents, stops->mExtend == ExtendMode::REFLECT);
    }
  } else if (aPattern.GetType() == PatternType::RADIAL_GRADIENT) {
    const RadialGradientPattern& pat = static_cast<const RadialGradientPattern&>(aPattern);
    CGAffineTransform patternMatrix = GfxMatrixToCGAffineTransform(pat.mMatrix);
    CGContextConcatCTM(cg, patternMatrix);
    CGRect extents = CGRectApplyAffineTransform(aExtents, CGAffineTransformInvert(patternMatrix));
    GradientStopsCG *stops = static_cast<GradientStopsCG*>(pat.mStops.get());
    if (stops->mExtend == ExtendMode::CLAMP) {

      // XXX: we should take the m out of the properties of RadialGradientPatterns
      CGPoint startCenter = { pat.mCenter1.x, pat.mCenter1.y };
      CGFloat startRadius = pat.mRadius1;
      CGPoint endCenter   = { pat.mCenter2.x, pat.mCenter2.y };
      CGFloat endRadius   = pat.mRadius2;

      //XXX: are there degenerate radial gradients that we should avoid drawing?
      CGContextDrawRadialGradient(cg, stops->mGradient, startCenter, startRadius, endCenter, endRadius,
                                  kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    } else if (stops->mExtend == ExtendMode::REPEAT || stops->mExtend == ExtendMode::REFLECT) {
      DrawRadialRepeatingGradient(aColorSpace, cg, pat, extents, stops->mExtend == ExtendMode::REFLECT);
    }
  } else {
    assert(0);
  }

}

static void
drawPattern(void *info, CGContextRef context)
{
  CGImageRef image = static_cast<CGImageRef>(info);
  CGRect rect = {{0, 0},
    {static_cast<CGFloat>(CGImageGetWidth(image)),
     static_cast<CGFloat>(CGImageGetHeight(image))}};
  CGContextDrawImage(context, rect, image);
}

static void
releaseInfo(void *info)
{
  CGImageRef image = static_cast<CGImageRef>(info);
  CGImageRelease(image);
}

CGPatternCallbacks patternCallbacks = {
  0,
  drawPattern,
  releaseInfo
};

static bool
isGradient(const Pattern &aPattern)
{
  return aPattern.GetType() == PatternType::LINEAR_GRADIENT || aPattern.GetType() == PatternType::RADIAL_GRADIENT;
}

static bool
isNonRepeatingSurface(const Pattern& aPattern)
{
  return aPattern.GetType() == PatternType::SURFACE &&
    static_cast<const SurfacePattern&>(aPattern).mExtendMode != ExtendMode::REPEAT;
}

/* CoreGraphics patterns ignore the userspace transform so
 * we need to multiply it in */
static CGPatternRef
CreateCGPattern(const Pattern &aPattern, CGAffineTransform aUserSpace)
{
  const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
  // XXX: is .get correct here?
  CGImageRef image = GetRetainedImageFromSourceSurface(pat.mSurface.get());
  Matrix patTransform = pat.mMatrix;
  if (!pat.mSamplingRect.IsEmpty()) {
    CGImageRef temp = CGImageCreateWithImageInRect(image, RectToCGRect(pat.mSamplingRect));
    CGImageRelease(image);
    image = temp;
    patTransform.PreTranslate(pat.mSamplingRect.x, pat.mSamplingRect.y);
  }
  CGFloat xStep, yStep;
  switch (pat.mExtendMode) {
    case ExtendMode::CLAMP:
      // The 1 << 22 comes from Webkit see Pattern::createPlatformPattern() in PatternCG.cpp for more info
      xStep = static_cast<CGFloat>(1 << 22);
      yStep = static_cast<CGFloat>(1 << 22);
      break;
    case ExtendMode::REFLECT:
      assert(0);
    case ExtendMode::REPEAT:
      xStep = static_cast<CGFloat>(CGImageGetWidth(image));
      yStep = static_cast<CGFloat>(CGImageGetHeight(image));
      // webkit uses wkCGPatternCreateWithImageAndTransform a wrapper around CGPatternCreateWithImage2
      // this is done to avoid pixel-cracking along pattern boundaries
      // (see https://bugs.webkit.org/show_bug.cgi?id=53055)
      // typedef enum {
      //    wkPatternTilingNoDistortion,
      //    wkPatternTilingConstantSpacingMinimalDistortion,
      //    wkPatternTilingConstantSpacing
      // } wkPatternTiling;
      // extern CGPatternRef (*wkCGPatternCreateWithImageAndTransform)(CGImageRef, CGAffineTransform, int);
  }

  //XXX: We should be using CGContextDrawTiledImage when we can. Even though it
  // creates a pattern, it seems to go down a faster path than using a delegate
  // like we do below
  CGRect bounds = {
    {0, 0,},
    {static_cast<CGFloat>(CGImageGetWidth(image)), static_cast<CGFloat>(CGImageGetHeight(image))}
  };
  CGAffineTransform transform =
      CGAffineTransformConcat(CGAffineTransformConcat(CGAffineTransformMakeScale(1,
                                                                                 -1),
                                                      GfxMatrixToCGAffineTransform(patTransform)),
                              aUserSpace);
  transform = CGAffineTransformTranslate(transform, 0, -static_cast<float>(CGImageGetHeight(image)));
  return CGPatternCreate(image, bounds, transform, xStep, yStep, kCGPatternTilingConstantSpacing,
                         true, &patternCallbacks);
}

static void
SetFillFromPattern(CGContextRef cg, CGColorSpaceRef aColorSpace, const Pattern &aPattern)
{
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  assert(!isGradient(aPattern));
  if (aPattern.GetType() == PatternType::COLOR) {

    const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
    //XXX: we should cache colors
    CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
    CGContextSetFillColorWithColor(cg, cgcolor);
    CGColorRelease(cgcolor);
  } else if (aPattern.GetType() == PatternType::SURFACE) {

    CGColorSpaceRef patternSpace;
    patternSpace = CGColorSpaceCreatePattern (nullptr);
    CGContextSetFillColorSpace(cg, patternSpace);
    CGColorSpaceRelease(patternSpace);

    CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
    const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
    CGContextSetInterpolationQuality(cg, InterpolationQualityFromFilter(pat.mFilter));
    CGFloat alpha = 1.;
    CGContextSetFillPattern(cg, pattern, &alpha);
    CGPatternRelease(pattern);
  }
}

static void
SetStrokeFromPattern(CGContextRef cg, CGColorSpaceRef aColorSpace, const Pattern &aPattern)
{
  assert(!isGradient(aPattern));
  if (aPattern.GetType() == PatternType::COLOR) {
    const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
    //XXX: we should cache colors
    CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
    CGContextSetStrokeColorWithColor(cg, cgcolor);
    CGColorRelease(cgcolor);
  } else if (aPattern.GetType() == PatternType::SURFACE) {
    CGColorSpaceRef patternSpace;
    patternSpace = CGColorSpaceCreatePattern (nullptr);
    CGContextSetStrokeColorSpace(cg, patternSpace);
    CGColorSpaceRelease(patternSpace);

    CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
    const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
    CGContextSetInterpolationQuality(cg, InterpolationQualityFromFilter(pat.mFilter));
    CGFloat alpha = 1.;
    CGContextSetStrokePattern(cg, pattern, &alpha);
    CGPatternRelease(pattern);
  }

}

void
DrawTargetCG::MaskSurface(const Pattern &aSource,
                          SourceSurface *aMask,
                          Point aOffset,
                          const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  CGContextSaveGState(mCg);

  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(cg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);

  CGImageRef image = GetRetainedImageFromSourceSurface(aMask);

  // use a negative-y so that the mask image draws right ways up
  CGContextScaleCTM(cg, 1, -1);

  IntSize size = aMask->GetSize();

  CGContextClipToMask(cg, CGRectMake(aOffset.x, -(aOffset.y + size.height), size.width, size.height), image);

  CGContextScaleCTM(cg, 1, -1);
  if (isGradient(aSource)) {
    // we shouldn't need to clip to an additional rectangle
    // as the cliping to the mask should be sufficient.
    DrawGradient(mColorSpace, cg, aSource, CGRectMake(aOffset.x, aOffset.y, size.width, size.height));
  } else {
    SetFillFromPattern(cg, mColorSpace, aSource);
    CGContextFillRect(cg, CGRectMake(aOffset.x, aOffset.y, size.width, size.height));
  }

  CGImageRelease(image);

  fixer.Fix(this);

  CGContextRestoreGState(mCg);
}

void
DrawTargetCG::SetTransform(const Matrix &aTransform)
{
  mTransform = aTransform;
  CGContextSetCTM(mCg, mOriginalTransform);
  CGContextConcatCTM(mCg, GfxMatrixToCGAffineTransform(aTransform));
}

void
DrawTargetCG::FillRect(const Rect &aRect,
                       const Pattern &aPattern,
                       const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  CGContextSaveGState(mCg);

  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp, &aRect);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);
  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));

  if (isGradient(aPattern)) {
    CGContextClipToRect(cg, RectToCGRect(aRect));
    CGRect clipBounds = CGContextGetClipBoundingBox(cg);
    DrawGradient(mColorSpace, cg, aPattern, clipBounds);
  } else if (isNonRepeatingSurface(aPattern)) {
    // SetFillFromPattern can handle this case but using CGContextDrawImage
    // should give us better performance, better output, smaller PDF and
    // matches what cairo does.
    const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
    CGImageRef image = GetRetainedImageFromSourceSurface(pat.mSurface.get());
    Matrix transform = pat.mMatrix;
    if (!pat.mSamplingRect.IsEmpty()) {
      CGImageRef temp = CGImageCreateWithImageInRect(image, RectToCGRect(pat.mSamplingRect));
      CGImageRelease(image);
      image = temp;
      transform.PreTranslate(pat.mSamplingRect.x, pat.mSamplingRect.y);
    }
    CGContextClipToRect(cg, RectToCGRect(aRect));
    CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(transform));
    CGContextTranslateCTM(cg, 0, CGImageGetHeight(image));
    CGContextScaleCTM(cg, 1, -1);

    CGRect imageRect = CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image));

    CGContextSetInterpolationQuality(cg, InterpolationQualityFromFilter(pat.mFilter));

    CGContextDrawImage(cg, imageRect, image);
    CGImageRelease(image);
  } else {
    SetFillFromPattern(cg, mColorSpace, aPattern);
    CGContextFillRect(cg, RectToCGRect(aRect));
  }

  fixer.Fix(this);
  CGContextRestoreGState(mCg);
}

static Float
DashPeriodLength(const StrokeOptions& aStrokeOptions)
{
  Float length = 0;
  for (size_t i = 0; i < aStrokeOptions.mDashLength; i++) {
    length += aStrokeOptions.mDashPattern[i];
  }
  if (aStrokeOptions.mDashLength & 1) {
    // "If an odd number of values is provided, then the list of values is
    // repeated to yield an even number of values."
    // Double the length.
    length += length;
  }
  return length;
}

inline Float
RoundDownToMultiple(Float aValue, Float aFactor)
{
  return floorf(aValue / aFactor) * aFactor;
}

static Rect
UserSpaceStrokeClip(const Rect &aDeviceClip,
                   const Matrix &aTransform,
                   const StrokeOptions &aStrokeOptions)
{
  Matrix inverse = aTransform;
  if (!inverse.Invert()) {
    return Rect();
  }
  Rect deviceClip = aDeviceClip;
  deviceClip.Inflate(MaxStrokeExtents(aStrokeOptions, aTransform));
  return inverse.TransformBounds(deviceClip);
}

static Rect
ShrinkClippedStrokedRect(const Rect &aStrokedRect, const Rect &aDeviceClip,
                         const Matrix &aTransform,
                         const StrokeOptions &aStrokeOptions)
{
  Rect userSpaceStrokeClip =
    UserSpaceStrokeClip(aDeviceClip, aTransform, aStrokeOptions);

  Rect intersection = aStrokedRect.Intersect(userSpaceStrokeClip);
  Float dashPeriodLength = DashPeriodLength(aStrokeOptions);
  if (intersection.IsEmpty() || dashPeriodLength == 0.0f) {
    return intersection;
  }

  // Reduce the rectangle side lengths in multiples of the dash period length
  // so that the visible dashes stay in the same place.
  Margin insetBy = aStrokedRect - intersection;
  insetBy.top = RoundDownToMultiple(insetBy.top, dashPeriodLength);
  insetBy.right = RoundDownToMultiple(insetBy.right, dashPeriodLength);
  insetBy.bottom = RoundDownToMultiple(insetBy.bottom, dashPeriodLength);
  insetBy.left = RoundDownToMultiple(insetBy.left, dashPeriodLength);

  Rect shrunkRect = aStrokedRect;
  shrunkRect.Deflate(insetBy);
  return shrunkRect;
}

// Liang-Barsky
// This algorithm was chosen for its code brevity, with the hope that its
// performance is good enough.
// Sets aStart and aEnd to floats between 0 and the line length, or returns
// false if the line is completely outside the rect.
static bool
IntersectLineWithRect(const Point& aP1, const Point& aP2, const Rect& aClip,
                      Float* aStart, Float* aEnd)
{
  Float t0 = 0.0f;
  Float t1 = 1.0f;
  Point vector = aP2 - aP1;
  for (uint32_t edge = 0; edge < 4; edge++) {
    Float p, q;
    switch (edge) {
      case 0: p = -vector.x; q = aP1.x - aClip.x; break;
      case 1: p =  vector.x; q = aClip.XMost() - aP1.x; break;
      case 2: p = -vector.y; q = aP1.y - aClip.y; break;
      case 3: p =  vector.y; q = aClip.YMost() - aP1.y; break;
    }

    if (p == 0.0f) {
      // Line is parallel to the edge.
      if (q < 0.0f) {
        return false;
      }
      continue;
    }

    Float r = q / p;
    if (p < 0) {
      t0 = std::max(t0, r);
    } else {
      t1 = std::min(t1, r);
    }

    if (t0 > t1) {
      return false;
    }
  }

  Float length = vector.Length();
  *aStart = t0 * length;
  *aEnd = t1 * length;
  return true;
}

// Adjusts aP1 and aP2 to a shrunk line, or returns false if the line is
// completely outside the clip.
static bool
ShrinkClippedStrokedLine(Point &aP1, Point& aP2, const Rect &aDeviceClip,
                         const Matrix &aTransform,
                         const StrokeOptions &aStrokeOptions)
{
  Rect userSpaceStrokeClip =
    UserSpaceStrokeClip(aDeviceClip, aTransform, aStrokeOptions);

  Point vector = aP2 - aP1;
  Float length = vector.Length();

  if (length == 0.0f) {
    return true;
  }

  Float start = 0;
  Float end = length;
  if (!IntersectLineWithRect(aP1, aP2, userSpaceStrokeClip, &start, &end)) {
    return false;
  }

  Float dashPeriodLength = DashPeriodLength(aStrokeOptions);
  if (dashPeriodLength > 0.0f) {
    // Shift the line points by multiples of dashPeriodLength so that the
    // dashes stay in the same place.
    start = RoundDownToMultiple(start, dashPeriodLength);
    end = length - RoundDownToMultiple(length - end, dashPeriodLength);
  }

  Point startPoint = aP1;
  aP1 = Point(startPoint.x + start * vector.x / length,
              startPoint.y + start * vector.y / length);
  aP2 = Point(startPoint.x + end * vector.x / length,
              startPoint.y + end * vector.y / length);
  return true;
}

void
DrawTargetCG::StrokeLine(const Point &aP1, const Point &aP2, const Pattern &aPattern, const StrokeOptions &aStrokeOptions, const DrawOptions &aDrawOptions)
{
  if (!std::isfinite(aP1.x) ||
      !std::isfinite(aP1.y) ||
      !std::isfinite(aP2.x) ||
      !std::isfinite(aP2.y)) {
    return;
  }

  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  Point p1 = aP1;
  Point p2 = aP2;

  Rect deviceClip(0, 0, mSize.width, mSize.height);
  if (!ShrinkClippedStrokedLine(p1, p2, deviceClip, mTransform, aStrokeOptions)) {
    return;
  }

  MarkChanged();

  CGContextSaveGState(mCg);

  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }
  CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);
  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));

  CGContextBeginPath(cg);
  CGContextMoveToPoint(cg, p1.x, p1.y);
  CGContextAddLineToPoint(cg, p2.x, p2.y);

  SetStrokeOptions(cg, aStrokeOptions);

  if (isGradient(aPattern)) {
    CGContextReplacePathWithStrokedPath(cg);
    CGRect extents = CGContextGetPathBoundingBox(cg);
    //XXX: should we use EO clip here?
    CGContextClip(cg);
    DrawGradient(mColorSpace, cg, aPattern, extents);
  } else {
    SetStrokeFromPattern(cg, mColorSpace, aPattern);
    CGContextStrokePath(cg);
  }

  fixer.Fix(this);
  CGContextRestoreGState(mCg);
}

static bool
IsInteger(Float aValue)
{
  return floorf(aValue) == aValue;
}

static bool
IsPixelAlignedStroke(const Rect& aRect, Float aLineWidth)
{
  Float halfWidth = aLineWidth/2;
  return IsInteger(aLineWidth) &&
         IsInteger(aRect.x - halfWidth) && IsInteger(aRect.y - halfWidth) &&
         IsInteger(aRect.XMost() - halfWidth) && IsInteger(aRect.YMost() - halfWidth);
}

void
DrawTargetCG::StrokeRect(const Rect &aRect,
                         const Pattern &aPattern,
                         const StrokeOptions &aStrokeOptions,
                         const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  if (!aRect.IsFinite()) {
    return;
  }

  // Stroking large rectangles with dashes is expensive with CG (fixed
  // overhead based on the number of dashes, regardless of whether the dashes
  // are visible), so we try to reduce the size of the stroked rectangle as
  // much as possible before passing it on to CG.
  Rect rect = aRect;
  if (!rect.IsEmpty()) {
    Rect deviceClip(0, 0, mSize.width, mSize.height);
    rect = ShrinkClippedStrokedRect(rect, deviceClip, mTransform, aStrokeOptions);
    if (rect.IsEmpty()) {
      return;
    }
  }

  MarkChanged();

  CGContextSaveGState(mCg);

  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));

  // Work around Quartz bug where antialiasing causes corner pixels to be off by
  // 1 channel value (e.g. rgb(1,1,1) values appear at the corner of solid
  // black stroke), by turning off antialiasing when the edges of the stroke
  // are pixel-aligned. Note that when a transform's components are all
  // integers, it maps integers coordinates to integer coordinates.
  bool pixelAlignedStroke = mTransform.IsAllIntegers() &&
    mTransform.PreservesAxisAlignedRectangles() &&
    aPattern.GetType() == PatternType::COLOR &&
    IsPixelAlignedStroke(rect, aStrokeOptions.mLineWidth);
  CGContextSetShouldAntialias(cg,
    aDrawOptions.mAntialiasMode != AntialiasMode::NONE && !pixelAlignedStroke);

  SetStrokeOptions(cg, aStrokeOptions);

  if (isGradient(aPattern)) {
    // There's no CGContextClipStrokeRect so we do it by hand
    CGContextBeginPath(cg);
    CGContextAddRect(cg, RectToCGRect(rect));
    CGContextReplacePathWithStrokedPath(cg);
    CGRect extents = CGContextGetPathBoundingBox(cg);
    //XXX: should we use EO clip here?
    CGContextClip(cg);
    DrawGradient(mColorSpace, cg, aPattern, extents);
  } else {
    SetStrokeFromPattern(cg, mColorSpace, aPattern);
    // We'd like to use CGContextStrokeRect(cg, RectToCGRect(rect));
    // Unfortunately, newer versions of OS X no longer start at the top-left
    // corner and stroke clockwise as older OS X versions and all the other
    // Moz2D backends do. (Newer versions start at the top right-hand corner
    // and stroke counter-clockwise.) For consistency we draw the rect by hand.
    CGContextBeginPath(cg);
    CGContextMoveToPoint(cg, rect.x, rect.y);
    CGContextAddLineToPoint(cg, rect.XMost(), rect.y);
    CGContextAddLineToPoint(cg, rect.XMost(), rect.YMost());
    CGContextAddLineToPoint(cg, rect.x, rect.YMost());
    CGContextClosePath(cg);
    CGContextStrokePath(cg);
  }

  fixer.Fix(this);
  CGContextRestoreGState(mCg);
}


void
DrawTargetCG::ClearRect(const Rect &aRect)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  CGContextClearRect(mCg, RectToCGRect(aRect));
}

void
DrawTargetCG::Stroke(const Path *aPath, const Pattern &aPattern, const StrokeOptions &aStrokeOptions, const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  if (!aPath->GetBounds().IsFinite()) {
    return;
  }

  MarkChanged();

  CGContextSaveGState(mCg);

  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(mCg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);
  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));


  CGContextBeginPath(cg);

  assert(aPath->GetBackendType() == BackendType::COREGRAPHICS);
  const PathCG *cgPath = static_cast<const PathCG*>(aPath);
  CGContextAddPath(cg, cgPath->GetPath());

  SetStrokeOptions(cg, aStrokeOptions);

  if (isGradient(aPattern)) {
    CGContextReplacePathWithStrokedPath(cg);
    CGRect extents = CGContextGetPathBoundingBox(cg);
    //XXX: should we use EO clip here?
    CGContextClip(cg);
    DrawGradient(mColorSpace, cg, aPattern, extents);
  } else {
    // XXX: we could put fill mode into the path fill rule if we wanted

    SetStrokeFromPattern(cg, mColorSpace, aPattern);
    CGContextStrokePath(cg);
  }

  fixer.Fix(this);
  CGContextRestoreGState(mCg);
}

void
DrawTargetCG::Fill(const Path *aPath, const Pattern &aPattern, const DrawOptions &aDrawOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  assert(aPath->GetBackendType() == BackendType::COREGRAPHICS);

  CGContextSaveGState(mCg);

  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(cg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);

  CGContextBeginPath(cg);
  // XXX: we could put fill mode into the path fill rule if we wanted
  const PathCG *cgPath = static_cast<const PathCG*>(aPath);

  if (isGradient(aPattern)) {
    // setup a clip to draw the gradient through
    CGRect extents;
    if (CGPathIsEmpty(cgPath->GetPath())) {
      // Adding an empty path will cause us not to clip
      // so clip everything explicitly
      CGContextClipToRect(mCg, CGRectZero);
      extents = CGRectZero;
    } else {
      CGContextAddPath(cg, cgPath->GetPath());
      extents = CGContextGetPathBoundingBox(cg);
      if (cgPath->GetFillRule() == FillRule::FILL_EVEN_ODD)
        CGContextEOClip(mCg);
      else
        CGContextClip(mCg);
    }

    DrawGradient(mColorSpace, cg, aPattern, extents);
  } else {
    CGContextAddPath(cg, cgPath->GetPath());

    SetFillFromPattern(cg, mColorSpace, aPattern);

    if (cgPath->GetFillRule() == FillRule::FILL_EVEN_ODD)
      CGContextEOFillPath(cg);
    else
      CGContextFillPath(cg);
  }

  fixer.Fix(this);
  CGContextRestoreGState(mCg);
}

CGRect ComputeGlyphsExtents(CGRect *bboxes, CGPoint *positions, CFIndex count, float scale)
{
  CGFloat x1, x2, y1, y2;
  if (count < 1)
    return CGRectZero;

  x1 = bboxes[0].origin.x + positions[0].x;
  x2 = bboxes[0].origin.x + positions[0].x + scale*bboxes[0].size.width;
  y1 = bboxes[0].origin.y + positions[0].y;
  y2 = bboxes[0].origin.y + positions[0].y + scale*bboxes[0].size.height;

  // accumulate max and minimum coordinates
  for (int i = 1; i < count; i++) {
    x1 = min(x1, bboxes[i].origin.x + positions[i].x);
    y1 = min(y1, bboxes[i].origin.y + positions[i].y);
    x2 = max(x2, bboxes[i].origin.x + positions[i].x + scale*bboxes[i].size.width);
    y2 = max(y2, bboxes[i].origin.y + positions[i].y + scale*bboxes[i].size.height);
  }

  CGRect extents = {{x1, y1}, {x2-x1, y2-y1}};
  return extents;
}

typedef void (*CGContextSetFontSmoothingBackgroundColorFunc) (CGContextRef cgContext, CGColorRef color);

static CGContextSetFontSmoothingBackgroundColorFunc
GetCGContextSetFontSmoothingBackgroundColorFunc()
{
  static CGContextSetFontSmoothingBackgroundColorFunc func = nullptr;
  static bool lookedUpFunc = false;
  if (!lookedUpFunc) {
    func = (CGContextSetFontSmoothingBackgroundColorFunc)dlsym(
      RTLD_DEFAULT, "CGContextSetFontSmoothingBackgroundColor");
    lookedUpFunc = true;
  }
  return func;
}

void
DrawTargetCG::FillGlyphs(ScaledFont *aFont, const GlyphBuffer &aBuffer, const Pattern &aPattern, const DrawOptions &aDrawOptions,
                         const GlyphRenderingOptions *aGlyphRenderingOptions)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  assert(aBuffer.mNumGlyphs);
  CGContextSaveGState(mCg);

  if (aGlyphRenderingOptions && aGlyphRenderingOptions->GetType() == FontType::MAC) {
    Color fontSmoothingBackgroundColor =
      static_cast<const GlyphRenderingOptionsCG*>(aGlyphRenderingOptions)->FontSmoothingBackgroundColor();
    if (fontSmoothingBackgroundColor.a > 0) {
      CGContextSetFontSmoothingBackgroundColorFunc setFontSmoothingBGColorFunc =
        GetCGContextSetFontSmoothingBackgroundColorFunc();
      if (setFontSmoothingBGColorFunc) {
        CGColorRef color = ColorToCGColor(mColorSpace, fontSmoothingBackgroundColor);
        setFontSmoothingBGColorFunc(mCg, color);
        CGColorRelease(color);

        // Font rendering with a non-transparent font smoothing background color
        // can leave pixels in our buffer where the rgb components exceed the alpha
        // component. When this happens we need to clean up the data afterwards.
        // The purpose of this is probably the following: Correct compositing of
        // subpixel anti-aliased fonts on transparent backgrounds requires
        // different alpha values per RGB component. Usually, premultiplied color
        // values are derived by multiplying all components with the same per-pixel
        // alpha value. However, if you multiply each component with a *different*
        // alpha, and set the alpha component of the pixel to, say, the average
        // of the alpha values that you used during the premultiplication of the
        // RGB components, you can trick OVER compositing into doing a simplified
        // form of component alpha compositing. (You just need to make sure to
        // clamp the components of the result pixel to [0,255] afterwards.)
        mMayContainInvalidPremultipliedData = true;
      }
    }
  }

  CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
  UnboundnessFixer fixer;
  CGContextRef cg = fixer.Check(this, aDrawOptions.mCompositionOp);
  if (MOZ2D_ERROR_IF(!cg)) {
    return;
  }

  CGContextSetAlpha(cg, aDrawOptions.mAlpha);
  CGContextSetShouldAntialias(cg, aDrawOptions.mAntialiasMode != AntialiasMode::NONE);
  if (aDrawOptions.mAntialiasMode != AntialiasMode::DEFAULT) {
    CGContextSetShouldSmoothFonts(cg, aDrawOptions.mAntialiasMode == AntialiasMode::SUBPIXEL);
  }

  ScaledFontMac* macFont = static_cast<ScaledFontMac*>(aFont);

  // This code can execute millions of times in short periods, so we want to
  // avoid heap allocation whenever possible. So we use an inline vector
  // capacity of 64 elements, which is enough to typically avoid heap
  // allocation in ~99% of cases.
  Vector<CGGlyph, 64> glyphs;
  Vector<CGPoint, 64> positions;
  if (!glyphs.resizeUninitialized(aBuffer.mNumGlyphs) ||
      !positions.resizeUninitialized(aBuffer.mNumGlyphs)) {
    MOZ_CRASH("glyphs/positions allocation failed");
  }

  // Handle the flip
  CGContextScaleCTM(cg, 1, -1);
  // CGContextSetTextMatrix works differently with kCGTextClip && kCGTextFill
  // It seems that it transforms the positions with TextFill and not with TextClip
  // Therefore we'll avoid it. See also:
  // http://cgit.freedesktop.org/cairo/commit/?id=9c0d761bfcdd28d52c83d74f46dd3c709ae0fa69

  for (unsigned int i = 0; i < aBuffer.mNumGlyphs; i++) {
    glyphs[i] = aBuffer.mGlyphs[i].mIndex;
    // XXX: CGPointMake might not be inlined
    positions[i] = CGPointMake(aBuffer.mGlyphs[i].mPosition.x,
                              -aBuffer.mGlyphs[i].mPosition.y);
  }

  //XXX: CGContextShowGlyphsAtPositions is 10.5+ for older versions use CGContextShowGlyphsWithAdvances
  if (isGradient(aPattern)) {
    CGContextSetTextDrawingMode(cg, kCGTextClip);
    CGRect extents;
    if (ScaledFontMac::CTFontDrawGlyphsPtr != nullptr) {
      CGRect *bboxes = new CGRect[aBuffer.mNumGlyphs];
      CTFontGetBoundingRectsForGlyphs(macFont->mCTFont, kCTFontDefaultOrientation,
                                      glyphs.begin(), bboxes, aBuffer.mNumGlyphs);
      extents = ComputeGlyphsExtents(bboxes, positions.begin(), aBuffer.mNumGlyphs, 1.0f);
      ScaledFontMac::CTFontDrawGlyphsPtr(macFont->mCTFont, glyphs.begin(),
                                         positions.begin(), aBuffer.mNumGlyphs, cg);
      delete[] bboxes;
    } else {
      CGRect *bboxes = new CGRect[aBuffer.mNumGlyphs];
      CGFontGetGlyphBBoxes(macFont->mFont, glyphs.begin(), aBuffer.mNumGlyphs, bboxes);
      extents = ComputeGlyphsExtents(bboxes, positions.begin(), aBuffer.mNumGlyphs, macFont->mSize);

      CGContextSetFont(cg, macFont->mFont);
      CGContextSetFontSize(cg, macFont->mSize);
      CGContextShowGlyphsAtPositions(cg, glyphs.begin(), positions.begin(),
                                     aBuffer.mNumGlyphs);
      delete[] bboxes;
    }
    CGContextScaleCTM(cg, 1, -1);
    DrawGradient(mColorSpace, cg, aPattern, extents);
  } else {
    //XXX: with CoreGraphics we can stroke text directly instead of going
    // through GetPath. It would be nice to add support for using that
    CGContextSetTextDrawingMode(cg, kCGTextFill);
    SetFillFromPattern(cg, mColorSpace, aPattern);
    if (ScaledFontMac::CTFontDrawGlyphsPtr != nullptr) {
      ScaledFontMac::CTFontDrawGlyphsPtr(macFont->mCTFont, glyphs.begin(),
                                         positions.begin(),
                                         aBuffer.mNumGlyphs, cg);
    } else {
      CGContextSetFont(cg, macFont->mFont);
      CGContextSetFontSize(cg, macFont->mSize);
      CGContextShowGlyphsAtPositions(cg, glyphs.begin(), positions.begin(),
                                     aBuffer.mNumGlyphs);
    }
  }

  fixer.Fix(this);
  CGContextRestoreGState(cg);
}

extern "C" {
void
CGContextResetClip(CGContextRef);
};

void
DrawTargetCG::CopySurface(SourceSurface *aSurface,
                          const IntRect& aSourceRect,
                          const IntPoint &aDestination)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  CGImageRef image = GetRetainedImageFromSourceSurface(aSurface);

  // XXX: it might be more efficient for us to do the copy directly if we have access to the bits

  CGContextSaveGState(mCg);
  CGContextSetCTM(mCg, mOriginalTransform);

  // CopySurface ignores the clip, so we need to use private API to temporarily reset it
  CGContextResetClip(mCg);
  CGRect destRect = CGRectMake(aDestination.x, aDestination.y,
                               aSourceRect.width, aSourceRect.height);
  CGContextClipToRect(mCg, destRect);

  CGContextSetBlendMode(mCg, kCGBlendModeCopy);

  CGContextScaleCTM(mCg, 1, -1);

  CGRect flippedRect = CGRectMake(aDestination.x - aSourceRect.x, -(aDestination.y - aSourceRect.y + double(CGImageGetHeight(image))),
                                  CGImageGetWidth(image), CGImageGetHeight(image));

  // Quartz seems to copy A8 surfaces incorrectly if we don't initialize them
  // to transparent first.
  if (mFormat == SurfaceFormat::A8) {
    CGContextClearRect(mCg, flippedRect);
  }
  CGContextDrawImage(mCg, flippedRect, image);

  CGContextRestoreGState(mCg);
  CGImageRelease(image);
}

void
DrawTargetCG::DrawSurfaceWithShadow(SourceSurface *aSurface, const Point &aDest, const Color &aColor, const Point &aOffset, Float aSigma, CompositionOp aOperator)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  MarkChanged();

  CGImageRef image = GetRetainedImageFromSourceSurface(aSurface);

  IntSize size = aSurface->GetSize();
  CGContextSaveGState(mCg);
  CGContextSetCTM(mCg, mOriginalTransform);
  //XXX do we need to do the fixup here?
  CGContextSetBlendMode(mCg, ToBlendMode(aOperator));

  CGContextScaleCTM(mCg, 1, -1);

  CGRect flippedRect = CGRectMake(aDest.x, -(aDest.y + size.height),
                                  size.width, size.height);

  CGColorRef color = ColorToCGColor(mColorSpace, aColor);
  CGSize offset = {aOffset.x, -aOffset.y};
  // CoreGraphics needs twice sigma as it's amount of blur
  CGContextSetShadowWithColor(mCg, offset, 2*aSigma, color);
  CGColorRelease(color);

  CGContextDrawImage(mCg, flippedRect, image);

  CGImageRelease(image);
  CGContextRestoreGState(mCg);
}

bool
DrawTargetCG::Init(BackendType aType,
                   unsigned char* aData,
                   const IntSize &aSize,
                   int32_t aStride,
                   SurfaceFormat aFormat)
{
  // XXX: we should come up with some consistent semantics for dealing
  // with zero area drawtargets
  if (aSize.width <= 0 ||
      aSize.height <= 0 ||
      size_t(aSize.width) > GetMaxSurfaceSize() ||
      size_t(aSize.height) > GetMaxSurfaceSize())
  {
    gfxWarning() << "Failed to Init() DrawTargetCG because of bad size.";
    mColorSpace = nullptr;
    mCg = nullptr;
    return false;
  }

  //XXX: handle SurfaceFormat

  //XXX: we'd be better off reusing the Colorspace across draw targets
  mColorSpace = CGColorSpaceCreateDeviceRGB();

  if (aData == nullptr && aType != BackendType::COREGRAPHICS_ACCELERATED) {
    // XXX: Currently, Init implicitly clears, that can often be a waste of time
    size_t bufLen = BufferSizeFromStrideAndHeight(aStride, aSize.height);
    if (bufLen == 0) {
      mColorSpace = nullptr;
      mCg = nullptr;
      return false;
    }
    static_assert(sizeof(decltype(mData[0])) == 1,
                  "mData.Realloc() takes an object count, so its objects must be 1-byte sized if we use bufLen");
    mData.Realloc(/* actually an object count */ bufLen, true);
    aData = static_cast<unsigned char*>(mData);
  }

  mSize = aSize;

#ifdef MOZ_WIDGET_COCOA
  if (aType == BackendType::COREGRAPHICS_ACCELERATED) {
    RefPtr<MacIOSurface> ioSurface = MacIOSurface::CreateIOSurface(aSize.width, aSize.height);
    mCg = ioSurface->CreateIOSurfaceContext();
    // If we don't have the symbol for 'CreateIOSurfaceContext' mCg will be null
    // and we will fallback to software below
  }
#endif

  mFormat = SurfaceFormat::B8G8R8A8;

  if (!mCg || aType == BackendType::COREGRAPHICS) {
    int bitsPerComponent = 8;

    CGBitmapInfo bitinfo;
    if (aFormat == SurfaceFormat::A8) {
      if (mColorSpace)
        CGColorSpaceRelease(mColorSpace);
      mColorSpace = nullptr;
      bitinfo = kCGImageAlphaOnly;
      mFormat = SurfaceFormat::A8;
    } else {
      bitinfo = kCGBitmapByteOrder32Host;
      if (aFormat == SurfaceFormat::B8G8R8X8) {
        bitinfo |= kCGImageAlphaNoneSkipFirst;
        mFormat = aFormat;
      } else {
        bitinfo |= kCGImageAlphaPremultipliedFirst;
      }
    }
    // XXX: what should we do if this fails?
    mCg = CGBitmapContextCreate (aData,
                                 mSize.width,
                                 mSize.height,
                                 bitsPerComponent,
                                 aStride,
                                 mColorSpace,
                                 bitinfo);
  }

  assert(mCg);
  if (!mCg) {
    gfxCriticalError() << "Failed to create CG context" << mSize << ", " << aStride;
    return false;
  }

  // CGContext's default to have the origin at the bottom left
  // so flip it to the top left
  CGContextTranslateCTM(mCg, 0, mSize.height);
  CGContextScaleCTM(mCg, 1, -1);
  mOriginalTransform = CGContextGetCTM(mCg);
  // See Bug 722164 for performance details
  // Medium or higher quality lead to expensive interpolation
  // for canvas we want to use low quality interpolation
  // to have competitive performance with other canvas
  // implementation.
  // XXX: Create input parameter to control interpolation and
  //      use the default for content.
  CGContextSetInterpolationQuality(mCg, kCGInterpolationLow);


  if (aType == BackendType::COREGRAPHICS_ACCELERATED) {
    // The bitmap backend uses callac to clear, we can't do that without
    // reading back the surface. This should trigger something equivilent
    // to glClear.
    ClearRect(Rect(0, 0, mSize.width, mSize.height));
  }

  return true;
}

static void
EnsureValidPremultipliedData(CGContextRef aContext)
{
  if (CGBitmapContextGetBitsPerPixel(aContext) != 32 ||
      CGBitmapContextGetAlphaInfo(aContext) != kCGImageAlphaPremultipliedFirst) {
    return;
  }

  uint8_t* bitmapData = (uint8_t*)CGBitmapContextGetData(aContext);
  int w = CGBitmapContextGetWidth(aContext);
  int h = CGBitmapContextGetHeight(aContext);
  int stride = CGBitmapContextGetBytesPerRow(aContext);
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      int i = y * stride + x * 4;
      uint8_t a = bitmapData[i + 3];

      // Clamp rgb components to the alpha component.
      if (bitmapData[i + 0] > a) {
        bitmapData[i + 0] = a;
      }
      if (bitmapData[i + 1] > a) {
        bitmapData[i + 1] = a;
      }
      if (bitmapData[i + 2] > a) {
        bitmapData[i + 2] = a;
      }
    }
  }
}

void
DrawTargetCG::Flush()
{
#ifdef MOZ_WIDGET_COCOA
  if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
    CGContextFlush(mCg);
  } else if (GetContextType(mCg) == CG_CONTEXT_TYPE_BITMAP &&
             mMayContainInvalidPremultipliedData) {
    // We can't guarantee that all our users can handle pixel data where an RGB
    // component value exceeds the pixel's alpha value. In particular, the
    // color conversion that CG does when we draw a CGImage snapshot of this
    // context into a context that has a different color space throws up on
    // invalid premultiplied data and creates completely wrong colors.
    // Sanitizing the data means that we lose some of the fake component alpha
    // behavior that font rendering tries to give us, but the result still
    // looks good enough to prefer it over grayscale font anti-aliasing.
    EnsureValidPremultipliedData(mCg);
    mMayContainInvalidPremultipliedData = false;
  }
#else
  //TODO
#endif
}

bool
DrawTargetCG::Init(CGContextRef cgContext, const IntSize &aSize)
{
  // XXX: we should come up with some consistent semantics for dealing
  // with zero area drawtargets
  if (aSize.width == 0 || aSize.height == 0) {
    mColorSpace = nullptr;
    mCg = nullptr;
    return false;
  }

  //XXX: handle SurfaceFormat

  //XXX: we'd be better off reusing the Colorspace across draw targets
  mColorSpace = CGColorSpaceCreateDeviceRGB();

  mSize = aSize;

  mCg = cgContext;
  CGContextRetain(mCg);

  assert(mCg);
  if (!mCg) {
    gfxCriticalError() << "Invalid CG context at Init " << aSize;
    return false;
  }

  // CGContext's default to have the origin at the bottom left.
  // However, currently the only use of this function is to construct a
  // DrawTargetCG around a CGContextRef from a cairo quartz surface which
  // already has it's origin adjusted.
  //
  // CGContextTranslateCTM(mCg, 0, mSize.height);
  // CGContextScaleCTM(mCg, 1, -1);
  mOriginalTransform = CGContextGetCTM(mCg);

  mFormat = SurfaceFormat::B8G8R8A8;
#ifdef MOZ_WIDGET_COCOA
  if (GetContextType(mCg) == CG_CONTEXT_TYPE_BITMAP) {
#endif
    CGColorSpaceRef colorspace;
    CGBitmapInfo bitinfo = CGBitmapContextGetBitmapInfo(mCg);
    colorspace = CGBitmapContextGetColorSpace (mCg);
    if (CGColorSpaceGetNumberOfComponents(colorspace) == 1) {
      mFormat = SurfaceFormat::A8;
    } else if ((bitinfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaNoneSkipFirst) {
      mFormat = SurfaceFormat::B8G8R8X8;
    }
#ifdef MOZ_WIDGET_COCOA
  }
#endif

  return true;
}

bool
DrawTargetCG::Init(BackendType aType, const IntSize &aSize, SurfaceFormat &aFormat)
{
  int32_t stride = GetAlignedStride<16>(aSize.width * BytesPerPixel(aFormat));
  
  // Calling Init with aData == nullptr will allocate.
  return Init(aType, nullptr, aSize, stride, aFormat);
}

already_AddRefed<PathBuilder>
DrawTargetCG::CreatePathBuilder(FillRule aFillRule) const
{
  return MakeAndAddRef<PathBuilderCG>(aFillRule);
}

void*
DrawTargetCG::GetNativeSurface(NativeSurfaceType aType)
{
#ifdef MOZ_WIDGET_COCOA
  if ((aType == NativeSurfaceType::CGCONTEXT && GetContextType(mCg) == CG_CONTEXT_TYPE_BITMAP) ||
      (aType == NativeSurfaceType::CGCONTEXT_ACCELERATED && GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE)) {
    return mCg;
  } else {
    return nullptr;
  }
#else
  return mCg;
#endif
}

void
DrawTargetCG::Mask(const Pattern &aSource,
                   const Pattern &aMask,
                   const DrawOptions &aDrawOptions)
{
  MarkChanged();

  CGContextSaveGState(mCg);

  if (isGradient(aMask)) {
    assert(0);
  } else {
    if (aMask.GetType() == PatternType::COLOR) {
      DrawOptions drawOptions(aDrawOptions);
      const Color& color = static_cast<const ColorPattern&>(aMask).mColor;
      drawOptions.mAlpha *= color.a;
      assert(0);
      // XXX: we need to get a rect that when transformed covers the entire surface
      //Rect
      //FillRect(rect, aSource, drawOptions);
    } else if (aMask.GetType() == PatternType::SURFACE) {
      const SurfacePattern& pat = static_cast<const SurfacePattern&>(aMask);
      CGImageRef mask = GetRetainedImageFromSourceSurface(pat.mSurface.get());
      MOZ_ASSERT(pat.mSamplingRect.IsEmpty(), "Sampling rect not supported with masks!");
      Rect rect(0,0, CGImageGetWidth(mask), CGImageGetHeight(mask));
      // XXX: probably we need to do some flipping of the image or something
      CGContextClipToMask(mCg, RectToCGRect(rect), mask);
      FillRect(rect, aSource, aDrawOptions);
      CGImageRelease(mask);
    }
  }

  CGContextRestoreGState(mCg);
}

void
DrawTargetCG::PushClipRect(const Rect &aRect)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  CGContextSaveGState(mCg);

  CGContextClipToRect(mCg, RectToCGRect(aRect));
}


void
DrawTargetCG::PushClip(const Path *aPath)
{
  if (MOZ2D_ERROR_IF(!mCg)) {
    return;
  }

  CGContextSaveGState(mCg);

  CGContextBeginPath(mCg);
  assert(aPath->GetBackendType() == BackendType::COREGRAPHICS);

  const PathCG *cgPath = static_cast<const PathCG*>(aPath);

  // Weirdly, CoreGraphics clips empty paths as all shown
  // but emtpy rects as all clipped.  We detect this situation and
  // workaround it appropriately
  if (CGPathIsEmpty(cgPath->GetPath())) {
    // XXX: should we return here?
    CGContextClipToRect(mCg, CGRectZero);
  }


  /* We go through a bit of trouble to temporarilly set the transform
   * while we add the path. XXX: this could be improved if we keep
   * the CTM as resident state on the DrawTarget. */
  CGContextSaveGState(mCg);
  CGContextAddPath(mCg, cgPath->GetPath());
  CGContextRestoreGState(mCg);

  if (cgPath->GetFillRule() == FillRule::FILL_EVEN_ODD)
    CGContextEOClip(mCg);
  else
    CGContextClip(mCg);
}

void
DrawTargetCG::PopClip()
{
  CGContextRestoreGState(mCg);
}

void
DrawTargetCG::MarkChanged()
{
  if (mSnapshot) {
    if (mSnapshot->refCount() > 1) {
      // We only need to worry about snapshots that someone else knows about
      mSnapshot->DrawTargetWillChange();
    }
    mSnapshot = nullptr;
  }
}

CGContextRef
BorrowedCGContext::BorrowCGContextFromDrawTarget(DrawTarget *aDT)
{
  if ((aDT->GetBackendType() == BackendType::COREGRAPHICS ||
       aDT->GetBackendType() == BackendType::COREGRAPHICS_ACCELERATED) &&
      !aDT->IsTiledDrawTarget() && !aDT->IsDualDrawTarget()) {
    DrawTargetCG* cgDT = static_cast<DrawTargetCG*>(aDT);
    cgDT->Flush();
    cgDT->MarkChanged();

    // swap out the context
    CGContextRef cg = cgDT->mCg;
    if (MOZ2D_ERROR_IF(!cg)) {
      return nullptr;
    }
    cgDT->mCg = nullptr;

    // save the state to make it easier for callers to avoid mucking with things
    CGContextSaveGState(cg);

    return cg;
  }
  return nullptr;
}

void
BorrowedCGContext::ReturnCGContextToDrawTarget(DrawTarget *aDT, CGContextRef cg)
{
  DrawTargetCG* cgDT = static_cast<DrawTargetCG*>(aDT);

  CGContextRestoreGState(cg);
  cgDT->mCg = cg;
}


} // namespace gfx
} // namespace mozilla