Painter.cpp 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  4. * Copyright (c) 2021, Mustafa Quraish <mustafa@serenityos.org>
  5. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  6. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  7. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  8. * Copyright (c) 2022, Jelle Raaijmakers <jelle@gmta.nl>
  9. *
  10. * SPDX-License-Identifier: BSD-2-Clause
  11. */
  12. #include "Painter.h"
  13. #include "Bitmap.h"
  14. #include "Font/Emoji.h"
  15. #include "Font/Font.h"
  16. #include <AK/Assertions.h>
  17. #include <AK/Debug.h>
  18. #include <AK/Function.h>
  19. #include <AK/Math.h>
  20. #include <AK/Memory.h>
  21. #include <AK/Queue.h>
  22. #include <AK/QuickSort.h>
  23. #include <AK/Stack.h>
  24. #include <AK/StdLibExtras.h>
  25. #include <AK/StringBuilder.h>
  26. #include <AK/Utf32View.h>
  27. #include <AK/Utf8View.h>
  28. #include <LibGfx/CharacterBitmap.h>
  29. #include <LibGfx/Palette.h>
  30. #include <LibGfx/Path.h>
  31. #include <LibGfx/Quad.h>
  32. #include <LibGfx/TextDirection.h>
  33. #include <LibGfx/TextLayout.h>
  34. #include <LibUnicode/CharacterTypes.h>
  35. #include <LibUnicode/Emoji.h>
  36. #include <stdio.h>
  37. #if defined(AK_COMPILER_GCC)
  38. # pragma GCC optimize("O3")
  39. #endif
  40. namespace Gfx {
  41. template<BitmapFormat format = BitmapFormat::Invalid>
  42. ALWAYS_INLINE Color get_pixel(Gfx::Bitmap const& bitmap, int x, int y)
  43. {
  44. if constexpr (format == BitmapFormat::BGRx8888)
  45. return Color::from_rgb(bitmap.scanline(y)[x]);
  46. if constexpr (format == BitmapFormat::BGRA8888)
  47. return Color::from_argb(bitmap.scanline(y)[x]);
  48. return bitmap.get_pixel(x, y);
  49. }
  50. Painter::Painter(Gfx::Bitmap& bitmap)
  51. : m_target(bitmap)
  52. {
  53. int scale = bitmap.scale();
  54. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRx8888 || bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  55. VERIFY(bitmap.physical_width() % scale == 0);
  56. VERIFY(bitmap.physical_height() % scale == 0);
  57. m_state_stack.append(State());
  58. state().font = nullptr;
  59. state().clip_rect = { { 0, 0 }, bitmap.size() };
  60. state().scale = scale;
  61. m_clip_origin = state().clip_rect;
  62. }
  63. void Painter::fill_rect_with_draw_op(IntRect const& a_rect, Color color)
  64. {
  65. VERIFY(scale() == 1); // FIXME: Add scaling support.
  66. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  67. if (rect.is_empty())
  68. return;
  69. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  70. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  71. for (int i = rect.height() - 1; i >= 0; --i) {
  72. for (int j = 0; j < rect.width(); ++j)
  73. set_physical_pixel_with_draw_op(dst[j], color);
  74. dst += dst_skip;
  75. }
  76. }
  77. void Painter::clear_rect(IntRect const& a_rect, Color color)
  78. {
  79. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  80. if (rect.is_empty())
  81. return;
  82. VERIFY(m_target->rect().contains(rect));
  83. rect *= scale();
  84. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  85. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  86. for (int i = rect.height() - 1; i >= 0; --i) {
  87. fast_u32_fill(dst, color.value(), rect.width());
  88. dst += dst_skip;
  89. }
  90. }
  91. void Painter::fill_physical_rect(IntRect const& physical_rect, Color color)
  92. {
  93. // Callers must do clipping.
  94. ARGB32* dst = m_target->scanline(physical_rect.top()) + physical_rect.left();
  95. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  96. auto dst_format = target()->format();
  97. for (int i = physical_rect.height() - 1; i >= 0; --i) {
  98. for (int j = 0; j < physical_rect.width(); ++j)
  99. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  100. dst += dst_skip;
  101. }
  102. }
  103. void Painter::fill_rect(IntRect const& a_rect, Color color)
  104. {
  105. if (color.alpha() == 0)
  106. return;
  107. if (draw_op() != DrawOp::Copy) {
  108. fill_rect_with_draw_op(a_rect, color);
  109. return;
  110. }
  111. if (color.alpha() == 0xff) {
  112. clear_rect(a_rect, color);
  113. return;
  114. }
  115. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  116. if (rect.is_empty())
  117. return;
  118. VERIFY(m_target->rect().contains(rect));
  119. fill_physical_rect(rect * scale(), color);
  120. }
  121. void Painter::fill_rect(IntRect const& rect, PaintStyle const& paint_style)
  122. {
  123. auto a_rect = rect.translated(translation());
  124. auto clipped_rect = a_rect.intersected(clip_rect());
  125. if (clipped_rect.is_empty())
  126. return;
  127. a_rect *= scale();
  128. clipped_rect *= scale();
  129. auto start_offset = clipped_rect.location() - a_rect.location();
  130. paint_style.paint(a_rect, [&](PaintStyle::SamplerFunction sample) {
  131. for (int y = 0; y < clipped_rect.height(); ++y) {
  132. for (int x = 0; x < clipped_rect.width(); ++x) {
  133. IntPoint point(x, y);
  134. set_physical_pixel(point + clipped_rect.location(), sample(point + start_offset), true);
  135. }
  136. }
  137. });
  138. }
  139. void Painter::fill_rect_with_dither_pattern(IntRect const& a_rect, Color color_a, Color color_b)
  140. {
  141. VERIFY(scale() == 1); // FIXME: Add scaling support.
  142. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  143. if (rect.is_empty())
  144. return;
  145. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  146. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  147. for (int i = 0; i < rect.height(); ++i) {
  148. for (int j = 0; j < rect.width(); ++j) {
  149. bool checkboard_use_a = ((rect.left() + i) & 1) ^ ((rect.top() + j) & 1);
  150. if (checkboard_use_a && !color_a.alpha())
  151. continue;
  152. if (!checkboard_use_a && !color_b.alpha())
  153. continue;
  154. dst[j] = checkboard_use_a ? color_a.value() : color_b.value();
  155. }
  156. dst += dst_skip;
  157. }
  158. }
  159. void Painter::fill_rect_with_checkerboard(IntRect const& a_rect, IntSize cell_size, Color color_dark, Color color_light)
  160. {
  161. VERIFY(scale() == 1); // FIXME: Add scaling support.
  162. auto translated_rect = a_rect.translated(translation());
  163. auto rect = translated_rect.intersected(clip_rect());
  164. if (rect.is_empty())
  165. return;
  166. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  167. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  168. int first_cell_column = (rect.x() - translated_rect.x()) / cell_size.width();
  169. int prologue_length = min(rect.width(), cell_size.width() - ((rect.x() - translated_rect.x()) % cell_size.width()));
  170. int number_of_aligned_strips = (rect.width() - prologue_length) / cell_size.width();
  171. for (int i = 0; i < rect.height(); ++i) {
  172. int y = rect.y() - translated_rect.y() + i;
  173. int cell_row = y / cell_size.height();
  174. bool odd_row = cell_row & 1;
  175. // Prologue: Paint the unaligned part up to the first intersection.
  176. int j = 0;
  177. int cell_column = first_cell_column;
  178. {
  179. bool odd_cell = cell_column & 1;
  180. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  181. fast_u32_fill(&dst[j], color, prologue_length);
  182. j += prologue_length;
  183. }
  184. // Aligned run: Paint the maximum number of aligned cell strips.
  185. for (int strip = 0; strip < number_of_aligned_strips; ++strip) {
  186. ++cell_column;
  187. bool odd_cell = cell_column & 1;
  188. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  189. fast_u32_fill(&dst[j], color, cell_size.width());
  190. j += cell_size.width();
  191. }
  192. // Epilogue: Paint the unaligned part until the end of the rect.
  193. if (j != rect.width()) {
  194. ++cell_column;
  195. bool odd_cell = cell_column & 1;
  196. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  197. int epilogue_length = rect.width() - j;
  198. fast_u32_fill(&dst[j], color, epilogue_length);
  199. j += epilogue_length;
  200. }
  201. dst += dst_skip;
  202. }
  203. }
  204. void Painter::fill_rect_with_gradient(Orientation orientation, IntRect const& a_rect, Color gradient_start, Color gradient_end)
  205. {
  206. if (gradient_start == gradient_end) {
  207. fill_rect(a_rect, gradient_start);
  208. return;
  209. }
  210. return fill_rect_with_linear_gradient(a_rect, Array { ColorStop { gradient_start, 0 }, ColorStop { gradient_end, 1 } }, orientation == Orientation::Horizontal ? 90.0f : 0.0f);
  211. }
  212. void Painter::fill_rect_with_gradient(IntRect const& a_rect, Color gradient_start, Color gradient_end)
  213. {
  214. return fill_rect_with_gradient(Orientation::Horizontal, a_rect, gradient_start, gradient_end);
  215. }
  216. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  217. {
  218. return fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  219. }
  220. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius)
  221. {
  222. // Fasttrack for rects without any border radii
  223. if (!top_left_radius && !top_right_radius && !bottom_right_radius && !bottom_left_radius)
  224. return fill_rect(a_rect, color);
  225. // Fully transparent, dont care.
  226. if (color.alpha() == 0)
  227. return;
  228. // FIXME: Allow for elliptically rounded corners
  229. IntRect top_left_corner = {
  230. a_rect.x(),
  231. a_rect.y(),
  232. top_left_radius,
  233. top_left_radius
  234. };
  235. IntRect top_right_corner = {
  236. a_rect.x() + a_rect.width() - top_right_radius,
  237. a_rect.y(),
  238. top_right_radius,
  239. top_right_radius
  240. };
  241. IntRect bottom_right_corner = {
  242. a_rect.x() + a_rect.width() - bottom_right_radius,
  243. a_rect.y() + a_rect.height() - bottom_right_radius,
  244. bottom_right_radius,
  245. bottom_right_radius
  246. };
  247. IntRect bottom_left_corner = {
  248. a_rect.x(),
  249. a_rect.y() + a_rect.height() - bottom_left_radius,
  250. bottom_left_radius,
  251. bottom_left_radius
  252. };
  253. IntRect top_rect = {
  254. a_rect.x() + top_left_radius,
  255. a_rect.y(),
  256. a_rect.width() - top_left_radius - top_right_radius, top_left_radius
  257. };
  258. IntRect right_rect = {
  259. a_rect.x() + a_rect.width() - top_right_radius,
  260. a_rect.y() + top_right_radius,
  261. top_right_radius,
  262. a_rect.height() - top_right_radius - bottom_right_radius
  263. };
  264. IntRect bottom_rect = {
  265. a_rect.x() + bottom_left_radius,
  266. a_rect.y() + a_rect.height() - bottom_right_radius,
  267. a_rect.width() - bottom_left_radius - bottom_right_radius,
  268. bottom_right_radius
  269. };
  270. IntRect left_rect = {
  271. a_rect.x(),
  272. a_rect.y() + top_left_radius,
  273. bottom_left_radius,
  274. a_rect.height() - top_left_radius - bottom_left_radius
  275. };
  276. IntRect inner = {
  277. left_rect.x() + left_rect.width(),
  278. left_rect.y(),
  279. a_rect.width() - left_rect.width() - right_rect.width(),
  280. a_rect.height() - top_rect.height() - bottom_rect.height()
  281. };
  282. fill_rect(top_rect, color);
  283. fill_rect(right_rect, color);
  284. fill_rect(bottom_rect, color);
  285. fill_rect(left_rect, color);
  286. fill_rect(inner, color);
  287. if (top_left_radius)
  288. fill_rounded_corner(top_left_corner, top_left_radius, color, CornerOrientation::TopLeft);
  289. if (top_right_radius)
  290. fill_rounded_corner(top_right_corner, top_right_radius, color, CornerOrientation::TopRight);
  291. if (bottom_left_radius)
  292. fill_rounded_corner(bottom_left_corner, bottom_left_radius, color, CornerOrientation::BottomLeft);
  293. if (bottom_right_radius)
  294. fill_rounded_corner(bottom_right_corner, bottom_right_radius, color, CornerOrientation::BottomRight);
  295. }
  296. void Painter::fill_rounded_corner(IntRect const& a_rect, int radius, Color color, CornerOrientation orientation)
  297. {
  298. // Care about clipping
  299. auto translated_a_rect = a_rect.translated(translation());
  300. auto rect = translated_a_rect.intersected(clip_rect());
  301. if (rect.is_empty())
  302. return;
  303. VERIFY(m_target->rect().contains(rect));
  304. // We got cut on the top!
  305. // FIXME: Also account for clipping on the x-axis
  306. int clip_offset = 0;
  307. if (translated_a_rect.y() < rect.y())
  308. clip_offset = rect.y() - translated_a_rect.y();
  309. radius *= scale();
  310. rect *= scale();
  311. clip_offset *= scale();
  312. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  313. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  314. IntPoint circle_center;
  315. switch (orientation) {
  316. case CornerOrientation::TopLeft:
  317. circle_center = { radius, radius + 1 };
  318. break;
  319. case CornerOrientation::TopRight:
  320. circle_center = { -1, radius + 1 };
  321. break;
  322. case CornerOrientation::BottomRight:
  323. circle_center = { -1, 0 };
  324. break;
  325. case CornerOrientation::BottomLeft:
  326. circle_center = { radius, 0 };
  327. break;
  328. default:
  329. VERIFY_NOT_REACHED();
  330. }
  331. int radius2 = radius * radius;
  332. auto is_in_circle = [&](int x, int y) {
  333. int distance2 = (circle_center.x() - x) * (circle_center.x() - x) + (circle_center.y() - y) * (circle_center.y() - y);
  334. // To reflect the grid and be compatible with the draw_circle_arc_intersecting algorithm
  335. // add 1/2 to the radius
  336. return distance2 <= (radius2 + radius + 0.25);
  337. };
  338. auto dst_format = target()->format();
  339. for (int i = rect.height() - 1; i >= 0; --i) {
  340. for (int j = 0; j < rect.width(); ++j)
  341. if (is_in_circle(j, rect.height() - i + clip_offset))
  342. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  343. dst += dst_skip;
  344. }
  345. }
  346. void Painter::draw_circle_arc_intersecting(IntRect const& a_rect, IntPoint center, int radius, Color color, int thickness)
  347. {
  348. if (thickness <= 0 || radius <= 0)
  349. return;
  350. // Care about clipping
  351. auto translated_a_rect = a_rect.translated(translation());
  352. auto rect = translated_a_rect.intersected(clip_rect());
  353. if (rect.is_empty())
  354. return;
  355. VERIFY(m_target->rect().contains(rect));
  356. // We got cut on the top!
  357. // FIXME: Also account for clipping on the x-axis
  358. int clip_offset = 0;
  359. if (translated_a_rect.y() < rect.y())
  360. clip_offset = rect.y() - translated_a_rect.y();
  361. if (thickness > radius)
  362. thickness = radius;
  363. int radius2 = radius * radius;
  364. auto is_on_arc = [&](int x, int y) {
  365. int distance2 = (center.x() - x) * (center.x() - x) + (center.y() - y) * (center.y() - y);
  366. // Is within a circle of radius 1/2 around (x,y), so basically within the current pixel.
  367. // Technically this is angle-dependent and should be between 1/2 and sqrt(2)/2, but this works.
  368. return distance2 <= (radius2 + radius + 0.25) && distance2 >= (radius2 - radius + 0.25);
  369. };
  370. ARGB32* dst = m_target->scanline(rect.top()) + rect.left();
  371. auto dst_format = target()->format();
  372. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  373. for (int i = rect.height() - 1; i >= 0; --i) {
  374. for (int j = 0; j < rect.width(); ++j)
  375. if (is_on_arc(j, rect.height() - i + clip_offset))
  376. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  377. dst += dst_skip;
  378. }
  379. return draw_circle_arc_intersecting(a_rect, center, radius - 1, color, thickness - 1);
  380. }
  381. // The callback will only be called for a quarter of the ellipse, the user is intended to deduce other points.
  382. // As the coordinate space is relative to the center of the rectangle, it's simply (x, y), (x, -y), (-x, y) and (-x, -y).
  383. static void on_each_ellipse_point(IntRect const& rect, Function<void(IntPoint)>&& callback)
  384. {
  385. // Note: This is an implementation of the Midpoint Ellipse Algorithm.
  386. double const a = rect.width() / 2;
  387. double const a_square = a * a;
  388. double const b = rect.height() / 2;
  389. double const b_square = b * b;
  390. int x = 0;
  391. auto y = static_cast<int>(b);
  392. double dx = 2 * b_square * x;
  393. double dy = 2 * a_square * y;
  394. // For region 1:
  395. auto decision_parameter = b_square - a_square * b + .25 * a_square;
  396. while (dx < dy) {
  397. callback({ x, y });
  398. if (decision_parameter >= 0) {
  399. y--;
  400. dy -= 2 * a_square;
  401. decision_parameter -= dy;
  402. }
  403. x++;
  404. dx += 2 * b_square;
  405. decision_parameter += dx + b_square;
  406. }
  407. // For region 2:
  408. decision_parameter = b_square * ((x + 0.5) * (x + 0.5)) + a_square * ((y - 1) * (y - 1)) - a_square * b_square;
  409. while (y >= 0) {
  410. callback({ x, y });
  411. if (decision_parameter <= 0) {
  412. x++;
  413. dx += 2 * b_square;
  414. decision_parameter += dx;
  415. }
  416. y--;
  417. dy -= 2 * a_square;
  418. decision_parameter += a_square - dy;
  419. }
  420. }
  421. void Painter::fill_ellipse(IntRect const& a_rect, Color color)
  422. {
  423. VERIFY(scale() == 1); // FIXME: Add scaling support.
  424. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  425. if (rect.is_empty())
  426. return;
  427. VERIFY(m_target->rect().contains(rect));
  428. auto const center = a_rect.center();
  429. on_each_ellipse_point(rect, [this, &color, center](IntPoint position) {
  430. IntPoint const directions[4] = { { position.x(), position.y() }, { -position.x(), position.y() }, { position.x(), -position.y() }, { -position.x(), -position.y() } };
  431. draw_line(center + directions[0], center + directions[1], color);
  432. draw_line(center + directions[2], center + directions[3], color);
  433. });
  434. }
  435. void Painter::draw_ellipse_intersecting(IntRect const& rect, Color color, int thickness)
  436. {
  437. VERIFY(scale() == 1); // FIXME: Add scaling support.
  438. if (thickness <= 0)
  439. return;
  440. auto const center = rect.center();
  441. on_each_ellipse_point(rect, [this, &color, thickness, center](IntPoint position) {
  442. IntPoint const directions[4] = { { position.x(), position.y() }, { position.x(), -position.y() }, { -position.x(), position.y() }, { -position.x(), -position.y() } };
  443. for (auto const delta : directions) {
  444. auto const point = center + delta;
  445. draw_line(point, point, color, thickness);
  446. }
  447. });
  448. }
  449. template<typename RectType, typename Callback>
  450. static void for_each_pixel_around_rect_clockwise(RectType const& rect, Callback callback)
  451. {
  452. if (rect.is_empty())
  453. return;
  454. for (auto x = rect.left(); x < rect.right(); ++x)
  455. callback(x, rect.top());
  456. for (auto y = rect.top() + 1; y < rect.bottom(); ++y)
  457. callback(rect.right() - 1, y);
  458. for (auto x = rect.right() - 2; x >= rect.left(); --x)
  459. callback(x, rect.bottom() - 1);
  460. for (auto y = rect.bottom() - 2; y > rect.top(); --y)
  461. callback(rect.left(), y);
  462. }
  463. void Painter::draw_focus_rect(IntRect const& rect, Color color)
  464. {
  465. VERIFY(scale() == 1); // FIXME: Add scaling support.
  466. if (rect.is_empty())
  467. return;
  468. bool state = false;
  469. for_each_pixel_around_rect_clockwise(rect, [&](auto x, auto y) {
  470. if (state)
  471. set_pixel(x, y, color);
  472. state = !state;
  473. });
  474. }
  475. void Painter::draw_rect(IntRect const& a_rect, Color color, bool rough)
  476. {
  477. IntRect rect = a_rect.translated(translation());
  478. auto clipped_rect = rect.intersected(clip_rect());
  479. if (clipped_rect.is_empty())
  480. return;
  481. int min_y = clipped_rect.top();
  482. int max_y = clipped_rect.bottom() - 1;
  483. int scale = this->scale();
  484. if (rect.top() >= clipped_rect.top() && rect.top() < clipped_rect.bottom()) {
  485. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  486. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  487. for (int i = 0; i < scale; ++i)
  488. fill_physical_scanline_with_draw_op(rect.top() * scale + i, start_x * scale, width * scale, color);
  489. ++min_y;
  490. }
  491. if (rect.bottom() > clipped_rect.top() && rect.bottom() <= clipped_rect.bottom()) {
  492. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  493. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  494. for (int i = 0; i < scale; ++i)
  495. fill_physical_scanline_with_draw_op(max_y * scale + i, start_x * scale, width * scale, color);
  496. --max_y;
  497. }
  498. bool draw_left_side = rect.left() >= clipped_rect.left();
  499. bool draw_right_side = rect.right() == clipped_rect.right();
  500. if (draw_left_side && draw_right_side) {
  501. // Specialized loop when drawing both sides.
  502. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  503. auto* bits = m_target->scanline(y);
  504. for (int i = 0; i < scale; ++i)
  505. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  506. for (int i = 0; i < scale; ++i)
  507. set_physical_pixel_with_draw_op(bits[(rect.right() - 1) * scale + i], color);
  508. }
  509. } else {
  510. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  511. auto* bits = m_target->scanline(y);
  512. if (draw_left_side)
  513. for (int i = 0; i < scale; ++i)
  514. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  515. if (draw_right_side)
  516. for (int i = 0; i < scale; ++i)
  517. set_physical_pixel_with_draw_op(bits[(rect.right() - 1) * scale + i], color);
  518. }
  519. }
  520. }
  521. void Painter::draw_rect_with_thickness(IntRect const& rect, Color color, int thickness)
  522. {
  523. if (thickness <= 0)
  524. return;
  525. IntPoint p1 = rect.location();
  526. IntPoint p2 = { rect.location().x() + rect.width(), rect.location().y() };
  527. IntPoint p3 = { rect.location().x() + rect.width(), rect.location().y() + rect.height() };
  528. IntPoint p4 = { rect.location().x(), rect.location().y() + rect.height() };
  529. draw_line(p1, p2, color, thickness);
  530. draw_line(p2, p3, color, thickness);
  531. draw_line(p3, p4, color, thickness);
  532. draw_line(p4, p1, color, thickness);
  533. }
  534. void Painter::draw_bitmap(IntPoint p, CharacterBitmap const& bitmap, Color color)
  535. {
  536. VERIFY(scale() == 1); // FIXME: Add scaling support.
  537. auto rect = IntRect(p, bitmap.size()).translated(translation());
  538. auto clipped_rect = rect.intersected(clip_rect());
  539. if (clipped_rect.is_empty())
  540. return;
  541. int const first_row = clipped_rect.top() - rect.top();
  542. int const last_row = clipped_rect.bottom() - rect.top();
  543. int const first_column = clipped_rect.left() - rect.left();
  544. int const last_column = clipped_rect.right() - rect.left();
  545. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  546. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  547. char const* bitmap_row = &bitmap.bits()[first_row * bitmap.width() + first_column];
  548. size_t const bitmap_skip = bitmap.width();
  549. for (int row = first_row; row < last_row; ++row) {
  550. for (int j = 0; j < (last_column - first_column); ++j) {
  551. char fc = bitmap_row[j];
  552. if (fc == '#')
  553. dst[j] = color.value();
  554. }
  555. bitmap_row += bitmap_skip;
  556. dst += dst_skip;
  557. }
  558. }
  559. void Painter::draw_bitmap(IntPoint p, GlyphBitmap const& bitmap, Color color)
  560. {
  561. auto dst_rect = IntRect(p, bitmap.size()).translated(translation());
  562. auto clipped_rect = dst_rect.intersected(clip_rect());
  563. if (clipped_rect.is_empty())
  564. return;
  565. int const first_row = clipped_rect.top() - dst_rect.top();
  566. int const last_row = clipped_rect.bottom() - dst_rect.top();
  567. int const first_column = clipped_rect.left() - dst_rect.left();
  568. int const last_column = clipped_rect.right() - dst_rect.left();
  569. int scale = this->scale();
  570. ARGB32* dst = m_target->scanline(clipped_rect.y() * scale) + clipped_rect.x() * scale;
  571. auto dst_format = target()->format();
  572. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  573. if (scale == 1) {
  574. for (int row = first_row; row < last_row; ++row) {
  575. for (int j = 0; j < (last_column - first_column); ++j) {
  576. if (bitmap.bit_at(j + first_column, row))
  577. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  578. }
  579. dst += dst_skip;
  580. }
  581. } else {
  582. for (int row = first_row; row < last_row; ++row) {
  583. for (int j = 0; j < (last_column - first_column); ++j) {
  584. if (bitmap.bit_at((j + first_column), row)) {
  585. for (int iy = 0; iy < scale; ++iy)
  586. for (int ix = 0; ix < scale; ++ix) {
  587. auto pixel_index = j * scale + ix + iy * dst_skip;
  588. dst[pixel_index] = color_for_format(dst_format, dst[pixel_index]).blend(color).value();
  589. }
  590. }
  591. }
  592. dst += dst_skip * scale;
  593. }
  594. }
  595. }
  596. void Painter::draw_triangle(IntPoint offset, ReadonlySpan<IntPoint> control_points, Color color)
  597. {
  598. VERIFY(control_points.size() == 3);
  599. draw_triangle(control_points[0] + offset, control_points[1] + offset, control_points[2] + offset, color);
  600. }
  601. void Painter::draw_triangle(IntPoint a, IntPoint b, IntPoint c, Color color)
  602. {
  603. IntPoint p0(to_physical(a));
  604. IntPoint p1(to_physical(b));
  605. IntPoint p2(to_physical(c));
  606. // sort points from top to bottom
  607. if (p0.y() > p1.y())
  608. swap(p0, p1);
  609. if (p0.y() > p2.y())
  610. swap(p0, p2);
  611. if (p1.y() > p2.y())
  612. swap(p1, p2);
  613. // return if top and bottom points are on same line
  614. if (p0.y() == p2.y())
  615. return;
  616. // return if all points are on the same line vertically
  617. if (p0.x() == p1.x() && p1.x() == p2.x())
  618. return;
  619. // return if top is below clip rect or bottom is above clip rect
  620. auto clip = clip_rect();
  621. if (p0.y() >= clip.bottom() - 1)
  622. return;
  623. if (p2.y() < clip.top())
  624. return;
  625. class BoundaryLine {
  626. private:
  627. IntPoint m_base {};
  628. IntPoint m_path {};
  629. public:
  630. BoundaryLine(IntPoint a, IntPoint b)
  631. {
  632. VERIFY(a.y() <= b.y());
  633. m_base = a;
  634. m_path = b - a;
  635. }
  636. int top_y() const { return m_base.y(); }
  637. int bottom_y() const { return m_base.y() + m_path.y(); }
  638. bool is_vertical() const { return m_path.x() == 0; }
  639. bool is_horizontal() const { return m_path.y() == 0; }
  640. bool in_y_range(int y) const { return y >= top_y() && y <= bottom_y(); }
  641. Optional<int> intersection_on_x(int y) const
  642. {
  643. if (!in_y_range(y))
  644. return {};
  645. if (is_horizontal())
  646. return {};
  647. if (is_vertical())
  648. return m_base.x();
  649. int y_diff = y - top_y();
  650. int x_d = m_path.x() * y_diff, y_d = m_path.y();
  651. return (x_d / y_d) + m_base.x();
  652. }
  653. };
  654. BoundaryLine l0(p0, p1), l1(p0, p2), l2(p1, p2);
  655. int rgba = color.value();
  656. for (int y = max(p0.y(), clip.top()); y < min(p2.y() + 1, clip.bottom()); y++) {
  657. Optional<int>
  658. x0 = l0.intersection_on_x(y),
  659. x1 = l1.intersection_on_x(y),
  660. x2 = l2.intersection_on_x(y);
  661. int result_a = 0, result_b = 0;
  662. if (x0.has_value()) {
  663. result_a = x0.value();
  664. if (x1.has_value() && ((!x2.has_value()) || (result_a != x1.value()))) {
  665. result_b = x1.value();
  666. } else {
  667. result_b = x2.value();
  668. }
  669. } else if (x1.has_value()) {
  670. result_a = x1.value();
  671. result_b = x2.value();
  672. }
  673. if (result_a > result_b)
  674. swap(result_a, result_b);
  675. int left_bound = result_a, right_bound = result_b;
  676. ARGB32* scanline = m_target->scanline(y);
  677. for (int x = max(left_bound, clip.left()); x <= min(right_bound, clip.right() - 1); x++)
  678. scanline[x] = rgba;
  679. }
  680. }
  681. struct BlitState {
  682. enum AlphaState {
  683. NoAlpha = 0,
  684. SrcAlpha = 1,
  685. DstAlpha = 2,
  686. BothAlpha = SrcAlpha | DstAlpha
  687. };
  688. ARGB32 const* src;
  689. ARGB32* dst;
  690. size_t src_pitch;
  691. size_t dst_pitch;
  692. int row_count;
  693. int column_count;
  694. float opacity;
  695. BitmapFormat src_format;
  696. };
  697. // FIXME: This is a hack to support blit_with_opacity() with RGBA8888 source.
  698. // Ideally we'd have a more generic solution that allows any source format.
  699. static void swap_red_and_blue_channels(Color& color)
  700. {
  701. u32 rgba = color.value();
  702. u32 bgra = (rgba & 0xff00ff00)
  703. | ((rgba & 0x000000ff) << 16)
  704. | ((rgba & 0x00ff0000) >> 16);
  705. color = Color::from_argb(bgra);
  706. }
  707. // FIXME: This function is very unoptimized.
  708. template<BlitState::AlphaState has_alpha>
  709. static void do_blit_with_opacity(BlitState& state)
  710. {
  711. for (int row = 0; row < state.row_count; ++row) {
  712. for (int x = 0; x < state.column_count; ++x) {
  713. Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_argb(state.dst[x]) : Color::from_rgb(state.dst[x]);
  714. if constexpr (has_alpha & BlitState::SrcAlpha) {
  715. Color src_color_with_alpha = Color::from_argb(state.src[x]);
  716. if (state.src_format == BitmapFormat::RGBA8888)
  717. swap_red_and_blue_channels(src_color_with_alpha);
  718. float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
  719. src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
  720. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  721. } else {
  722. Color src_color_with_alpha = Color::from_rgb(state.src[x]);
  723. if (state.src_format == BitmapFormat::RGBA8888)
  724. swap_red_and_blue_channels(src_color_with_alpha);
  725. src_color_with_alpha.set_alpha(state.opacity * 255);
  726. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  727. }
  728. }
  729. state.dst += state.dst_pitch;
  730. state.src += state.src_pitch;
  731. }
  732. }
  733. void Painter::blit_with_opacity(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  734. {
  735. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  736. if (opacity >= 1.0f && !(source.has_alpha_channel() && apply_alpha))
  737. return blit(position, source, a_src_rect);
  738. IntRect safe_src_rect = IntRect::intersection(a_src_rect, source.rect());
  739. if (scale() != source.scale())
  740. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  741. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  742. auto clipped_rect = dst_rect.intersected(clip_rect());
  743. if (clipped_rect.is_empty())
  744. return;
  745. int scale = this->scale();
  746. auto src_rect = a_src_rect * scale;
  747. clipped_rect *= scale;
  748. dst_rect *= scale;
  749. int const first_row = clipped_rect.top() - dst_rect.top();
  750. int const last_row = clipped_rect.bottom() - dst_rect.top();
  751. int const first_column = clipped_rect.left() - dst_rect.left();
  752. int const last_column = clipped_rect.right() - dst_rect.left();
  753. BlitState blit_state {
  754. .src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column,
  755. .dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x(),
  756. .src_pitch = source.pitch() / sizeof(ARGB32),
  757. .dst_pitch = m_target->pitch() / sizeof(ARGB32),
  758. .row_count = last_row - first_row,
  759. .column_count = last_column - first_column,
  760. .opacity = opacity,
  761. .src_format = source.format(),
  762. };
  763. if (source.has_alpha_channel() && apply_alpha) {
  764. if (m_target->has_alpha_channel())
  765. do_blit_with_opacity<BlitState::BothAlpha>(blit_state);
  766. else
  767. do_blit_with_opacity<BlitState::SrcAlpha>(blit_state);
  768. } else {
  769. if (m_target->has_alpha_channel())
  770. do_blit_with_opacity<BlitState::DstAlpha>(blit_state);
  771. else
  772. do_blit_with_opacity<BlitState::NoAlpha>(blit_state);
  773. }
  774. }
  775. void Painter::blit_filtered(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, Function<Color(Color)> const& filter, bool apply_alpha)
  776. {
  777. VERIFY((source.scale() == 1 || source.scale() == scale()) && "blit_filtered only supports integer upsampling");
  778. IntRect safe_src_rect = src_rect.intersected(source.rect());
  779. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  780. auto clipped_rect = dst_rect.intersected(clip_rect());
  781. if (clipped_rect.is_empty())
  782. return;
  783. int scale = this->scale();
  784. clipped_rect *= scale;
  785. dst_rect *= scale;
  786. safe_src_rect *= source.scale();
  787. int const first_row = clipped_rect.top() - dst_rect.top();
  788. int const last_row = clipped_rect.bottom() - dst_rect.top();
  789. int const first_column = clipped_rect.left() - dst_rect.left();
  790. int const last_column = clipped_rect.right() - dst_rect.left();
  791. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  792. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  793. auto dst_format = target()->format();
  794. auto src_format = source.format();
  795. int s = scale / source.scale();
  796. if (s == 1) {
  797. ARGB32 const* src = source.scanline(safe_src_rect.top() + first_row) + safe_src_rect.left() + first_column;
  798. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  799. for (int row = first_row; row < last_row; ++row) {
  800. for (int x = 0; x < (last_column - first_column); ++x) {
  801. auto source_color = color_for_format(src_format, src[x]);
  802. if (source_color.alpha() == 0)
  803. continue;
  804. auto filtered_color = filter(source_color);
  805. if (!apply_alpha || filtered_color.alpha() == 0xff)
  806. dst[x] = filtered_color.value();
  807. else
  808. dst[x] = color_for_format(dst_format, dst[x]).blend(filtered_color).value();
  809. }
  810. dst += dst_skip;
  811. src += src_skip;
  812. }
  813. } else {
  814. for (int row = first_row; row < last_row; ++row) {
  815. ARGB32 const* src = source.scanline(safe_src_rect.top() + row / s) + safe_src_rect.left() + first_column / s;
  816. for (int x = 0; x < (last_column - first_column); ++x) {
  817. auto source_color = color_for_format(src_format, src[x / s]);
  818. if (source_color.alpha() == 0)
  819. continue;
  820. auto filtered_color = filter(source_color);
  821. if (!apply_alpha || filtered_color.alpha() == 0xff)
  822. dst[x] = filtered_color.value();
  823. else
  824. dst[x] = color_for_format(dst_format, dst[x]).blend(filtered_color).value();
  825. }
  826. dst += dst_skip;
  827. }
  828. }
  829. }
  830. void Painter::blit_brightened(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  831. {
  832. return blit_filtered(position, source, src_rect, [](Color src) {
  833. return src.lightened();
  834. });
  835. }
  836. void Painter::blit_dimmed(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  837. {
  838. return blit_filtered(position, source, src_rect, [](Color src) {
  839. return src.to_grayscale().lightened();
  840. });
  841. }
  842. void Painter::draw_tiled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source)
  843. {
  844. VERIFY((source.scale() == 1 || source.scale() == scale()) && "draw_tiled_bitmap only supports integer upsampling");
  845. auto dst_rect = a_dst_rect.translated(translation());
  846. auto clipped_rect = dst_rect.intersected(clip_rect());
  847. if (clipped_rect.is_empty())
  848. return;
  849. int scale = this->scale();
  850. clipped_rect *= scale;
  851. dst_rect *= scale;
  852. int const first_row = clipped_rect.top() - dst_rect.top();
  853. int const last_row = clipped_rect.bottom() - dst_rect.top();
  854. int const first_column = clipped_rect.left() - dst_rect.left();
  855. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  856. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  857. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  858. int s = scale / source.scale();
  859. if (s == 1) {
  860. int x_start = first_column + a_dst_rect.left() * scale;
  861. for (int row = first_row; row < last_row; ++row) {
  862. ARGB32 const* sl = source.scanline((row + a_dst_rect.top() * scale) % source.physical_height());
  863. for (int x = x_start; x < clipped_rect.width() + x_start; ++x)
  864. dst[x - x_start] = sl[x % source.physical_width()];
  865. dst += dst_skip;
  866. }
  867. } else {
  868. int x_start = first_column + a_dst_rect.left() * scale;
  869. for (int row = first_row; row < last_row; ++row) {
  870. ARGB32 const* sl = source.scanline(((row + a_dst_rect.top() * scale) / s) % source.physical_height());
  871. for (int x = x_start; x < clipped_rect.width() + x_start; ++x)
  872. dst[x - x_start] = sl[(x / s) % source.physical_width()];
  873. dst += dst_skip;
  874. }
  875. }
  876. return;
  877. }
  878. VERIFY_NOT_REACHED();
  879. }
  880. void Painter::blit_offset(IntPoint a_position, Gfx::Bitmap const& source, IntRect const& a_src_rect, IntPoint offset)
  881. {
  882. auto src_rect = IntRect { a_src_rect.location() - offset, a_src_rect.size() };
  883. auto position = a_position;
  884. if (src_rect.x() < 0) {
  885. position.set_x(position.x() - src_rect.x());
  886. src_rect.set_x(0);
  887. }
  888. if (src_rect.y() < 0) {
  889. position.set_y(position.y() - src_rect.y());
  890. src_rect.set_y(0);
  891. }
  892. blit(position, source, src_rect);
  893. }
  894. void Painter::blit(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  895. {
  896. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  897. if (opacity < 1.0f || (source.has_alpha_channel() && apply_alpha))
  898. return blit_with_opacity(position, source, a_src_rect, opacity, apply_alpha);
  899. auto safe_src_rect = a_src_rect.intersected(source.rect());
  900. if (scale() != source.scale())
  901. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  902. // If we get here, the Painter might have a scale factor, but the source bitmap has the same scale factor.
  903. // We need to transform from logical to physical coordinates, but we can just copy pixels without resampling.
  904. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  905. auto clipped_rect = dst_rect.intersected(clip_rect());
  906. if (clipped_rect.is_empty())
  907. return;
  908. // All computations below are in physical coordinates.
  909. int scale = this->scale();
  910. auto src_rect = a_src_rect * scale;
  911. clipped_rect *= scale;
  912. dst_rect *= scale;
  913. int const first_row = clipped_rect.top() - dst_rect.top();
  914. int const last_row = clipped_rect.bottom() - dst_rect.top();
  915. int const first_column = clipped_rect.left() - dst_rect.left();
  916. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  917. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  918. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  919. ARGB32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  920. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  921. for (int row = first_row; row < last_row; ++row) {
  922. memcpy(dst, src, sizeof(ARGB32) * clipped_rect.width());
  923. dst += dst_skip;
  924. src += src_skip;
  925. }
  926. return;
  927. }
  928. if (source.format() == BitmapFormat::RGBA8888) {
  929. u32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  930. size_t const src_skip = source.pitch() / sizeof(u32);
  931. for (int row = first_row; row < last_row; ++row) {
  932. for (int i = 0; i < clipped_rect.width(); ++i) {
  933. u32 rgba = src[i];
  934. u32 bgra = (rgba & 0xff00ff00)
  935. | ((rgba & 0x000000ff) << 16)
  936. | ((rgba & 0x00ff0000) >> 16);
  937. dst[i] = bgra;
  938. }
  939. dst += dst_skip;
  940. src += src_skip;
  941. }
  942. return;
  943. }
  944. VERIFY_NOT_REACHED();
  945. }
  946. template<bool has_alpha_channel, typename GetPixel>
  947. ALWAYS_INLINE static void do_draw_integer_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& src_rect, Gfx::Bitmap const& source, int hfactor, int vfactor, GetPixel get_pixel, float opacity)
  948. {
  949. bool has_opacity = opacity != 1.0f;
  950. for (int y = 0; y < src_rect.height(); ++y) {
  951. int dst_y = dst_rect.y() + y * vfactor;
  952. for (int x = 0; x < src_rect.width(); ++x) {
  953. auto src_pixel = get_pixel(source, x + src_rect.left(), y + src_rect.top());
  954. if (has_opacity)
  955. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  956. for (int yo = 0; yo < vfactor; ++yo) {
  957. auto* scanline = (Color*)target.scanline(dst_y + yo);
  958. int dst_x = dst_rect.x() + x * hfactor;
  959. for (int xo = 0; xo < hfactor; ++xo) {
  960. if constexpr (has_alpha_channel)
  961. scanline[dst_x + xo] = scanline[dst_x + xo].blend(src_pixel);
  962. else
  963. scanline[dst_x + xo] = src_pixel;
  964. }
  965. }
  966. }
  967. }
  968. }
  969. template<bool has_alpha_channel, typename GetPixel>
  970. ALWAYS_INLINE static void do_draw_box_sampled_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity)
  971. {
  972. float source_pixel_width = src_rect.width() / dst_rect.width();
  973. float source_pixel_height = src_rect.height() / dst_rect.height();
  974. float source_pixel_area = source_pixel_width * source_pixel_height;
  975. FloatRect const pixel_box = { 0.f, 0.f, 1.f, 1.f };
  976. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  977. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  978. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  979. // Project the destination pixel in the source image
  980. FloatRect const source_box = {
  981. src_rect.left() + (x - dst_rect.x()) * source_pixel_width,
  982. src_rect.top() + (y - dst_rect.y()) * source_pixel_height,
  983. source_pixel_width,
  984. source_pixel_height,
  985. };
  986. IntRect enclosing_source_box = enclosing_int_rect(source_box).intersected(source.rect());
  987. // Sum the contribution of all source pixels inside the projected pixel
  988. float red_accumulator = 0.f;
  989. float green_accumulator = 0.f;
  990. float blue_accumulator = 0.f;
  991. float total_area = 0.f;
  992. for (int sy = enclosing_source_box.y(); sy < enclosing_source_box.bottom(); ++sy) {
  993. for (int sx = enclosing_source_box.x(); sx < enclosing_source_box.right(); ++sx) {
  994. float area = source_box.intersected(pixel_box.translated(sx, sy)).size().area();
  995. auto pixel = get_pixel(source, sx, sy);
  996. area *= pixel.alpha() / 255.f;
  997. red_accumulator += pixel.red() * area;
  998. green_accumulator += pixel.green() * area;
  999. blue_accumulator += pixel.blue() * area;
  1000. total_area += area;
  1001. }
  1002. }
  1003. Color src_pixel = {
  1004. round_to<u8>(min(red_accumulator / total_area, 255.f)),
  1005. round_to<u8>(min(green_accumulator / total_area, 255.f)),
  1006. round_to<u8>(min(blue_accumulator / total_area, 255.f)),
  1007. round_to<u8>(min(total_area * 255.f / source_pixel_area * opacity, 255.f)),
  1008. };
  1009. if constexpr (has_alpha_channel)
  1010. scanline[x] = scanline[x].blend(src_pixel);
  1011. else
  1012. scanline[x] = src_pixel;
  1013. }
  1014. }
  1015. }
  1016. template<bool has_alpha_channel, Painter::ScalingMode scaling_mode, typename GetPixel>
  1017. ALWAYS_INLINE static void do_draw_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity)
  1018. {
  1019. auto int_src_rect = enclosing_int_rect(src_rect);
  1020. auto clipped_src_rect = int_src_rect.intersected(source.rect());
  1021. if (clipped_src_rect.is_empty())
  1022. return;
  1023. if constexpr (scaling_mode == Painter::ScalingMode::NearestNeighbor || scaling_mode == Painter::ScalingMode::SmoothPixels) {
  1024. if (dst_rect == clipped_rect && int_src_rect == src_rect && !(dst_rect.width() % int_src_rect.width()) && !(dst_rect.height() % int_src_rect.height())) {
  1025. int hfactor = dst_rect.width() / int_src_rect.width();
  1026. int vfactor = dst_rect.height() / int_src_rect.height();
  1027. if (hfactor == 2 && vfactor == 2)
  1028. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 2, 2, get_pixel, opacity);
  1029. if (hfactor == 3 && vfactor == 3)
  1030. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 3, 3, get_pixel, opacity);
  1031. if (hfactor == 4 && vfactor == 4)
  1032. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 4, 4, get_pixel, opacity);
  1033. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  1034. }
  1035. }
  1036. if constexpr (scaling_mode == Painter::ScalingMode::BoxSampling)
  1037. return do_draw_box_sampled_scaled_bitmap<has_alpha_channel>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1038. bool has_opacity = opacity != 1.f;
  1039. i64 shift = 1ll << 32;
  1040. i64 fractional_mask = shift - 1;
  1041. i64 bilinear_offset_x = (1ll << 31) * (src_rect.width() / dst_rect.width() - 1);
  1042. i64 bilinear_offset_y = (1ll << 31) * (src_rect.height() / dst_rect.height() - 1);
  1043. i64 hscale = src_rect.width() * shift / dst_rect.width();
  1044. i64 vscale = src_rect.height() * shift / dst_rect.height();
  1045. i64 src_left = src_rect.left() * shift;
  1046. i64 src_top = src_rect.top() * shift;
  1047. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  1048. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  1049. auto desired_y = (y - dst_rect.y()) * vscale + src_top;
  1050. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  1051. auto desired_x = (x - dst_rect.x()) * hscale + src_left;
  1052. Color src_pixel;
  1053. if constexpr (scaling_mode == Painter::ScalingMode::BilinearBlend) {
  1054. auto shifted_x = desired_x + bilinear_offset_x;
  1055. auto shifted_y = desired_y + bilinear_offset_y;
  1056. auto scaled_x0 = clamp(shifted_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1057. auto scaled_x1 = clamp((shifted_x >> 32) + 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1058. auto scaled_y0 = clamp(shifted_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1059. auto scaled_y1 = clamp((shifted_y >> 32) + 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1060. float x_ratio = (shifted_x & fractional_mask) / static_cast<float>(shift);
  1061. float y_ratio = (shifted_y & fractional_mask) / static_cast<float>(shift);
  1062. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1063. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1064. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1065. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1066. auto top = top_left.mixed_with(top_right, x_ratio);
  1067. auto bottom = bottom_left.mixed_with(bottom_right, x_ratio);
  1068. src_pixel = top.mixed_with(bottom, y_ratio);
  1069. } else if constexpr (scaling_mode == Painter::ScalingMode::SmoothPixels) {
  1070. auto scaled_x1 = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1071. auto scaled_x0 = clamp(scaled_x1 - 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1072. auto scaled_y1 = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1073. auto scaled_y0 = clamp(scaled_y1 - 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1074. float x_ratio = (desired_x & fractional_mask) / (float)shift;
  1075. float y_ratio = (desired_y & fractional_mask) / (float)shift;
  1076. float scaled_x_ratio = clamp(x_ratio * dst_rect.width() / (float)src_rect.width(), 0.f, 1.f);
  1077. float scaled_y_ratio = clamp(y_ratio * dst_rect.height() / (float)src_rect.height(), 0.f, 1.f);
  1078. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1079. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1080. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1081. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1082. auto top = top_left.mixed_with(top_right, scaled_x_ratio);
  1083. auto bottom = bottom_left.mixed_with(bottom_right, scaled_x_ratio);
  1084. src_pixel = top.mixed_with(bottom, scaled_y_ratio);
  1085. } else {
  1086. auto scaled_x = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1087. auto scaled_y = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1088. src_pixel = get_pixel(source, scaled_x, scaled_y);
  1089. }
  1090. if (has_opacity)
  1091. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  1092. if constexpr (has_alpha_channel)
  1093. scanline[x] = scanline[x].blend(src_pixel);
  1094. else
  1095. scanline[x] = src_pixel;
  1096. }
  1097. }
  1098. }
  1099. template<bool has_alpha_channel, typename GetPixel>
  1100. ALWAYS_INLINE static void do_draw_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity, Painter::ScalingMode scaling_mode)
  1101. {
  1102. switch (scaling_mode) {
  1103. case Painter::ScalingMode::NearestNeighbor:
  1104. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::NearestNeighbor>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1105. break;
  1106. case Painter::ScalingMode::SmoothPixels:
  1107. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::SmoothPixels>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1108. break;
  1109. case Painter::ScalingMode::BilinearBlend:
  1110. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::BilinearBlend>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1111. break;
  1112. case Painter::ScalingMode::BoxSampling:
  1113. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::BoxSampling>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1114. break;
  1115. case Painter::ScalingMode::None:
  1116. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::None>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1117. break;
  1118. }
  1119. }
  1120. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1121. {
  1122. draw_scaled_bitmap(a_dst_rect, source, FloatRect { a_src_rect }, opacity, scaling_mode);
  1123. }
  1124. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, FloatRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1125. {
  1126. IntRect int_src_rect = enclosing_int_rect(a_src_rect);
  1127. if (scale() == source.scale() && a_src_rect == int_src_rect && a_dst_rect.size() == int_src_rect.size())
  1128. return blit(a_dst_rect.location(), source, int_src_rect, opacity);
  1129. if (scaling_mode == ScalingMode::None) {
  1130. IntRect clipped_draw_rect { (int)a_src_rect.location().x(), (int)a_src_rect.location().y(), a_dst_rect.size().width(), a_dst_rect.size().height() };
  1131. return blit(a_dst_rect.location(), source, clipped_draw_rect, opacity);
  1132. }
  1133. auto dst_rect = to_physical(a_dst_rect);
  1134. auto src_rect = a_src_rect * source.scale();
  1135. auto clipped_rect = dst_rect.intersected(clip_rect() * scale());
  1136. if (clipped_rect.is_empty())
  1137. return;
  1138. if (source.has_alpha_channel() || opacity != 1.0f) {
  1139. switch (source.format()) {
  1140. case BitmapFormat::BGRx8888:
  1141. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1142. break;
  1143. case BitmapFormat::BGRA8888:
  1144. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRA8888>, opacity, scaling_mode);
  1145. break;
  1146. default:
  1147. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1148. break;
  1149. }
  1150. } else {
  1151. switch (source.format()) {
  1152. case BitmapFormat::BGRx8888:
  1153. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1154. break;
  1155. default:
  1156. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Color color)
  1162. {
  1163. draw_glyph(point, code_point, font(), color);
  1164. }
  1165. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Font const& font, Color color)
  1166. {
  1167. auto top_left = point + FloatPoint(font.glyph_left_bearing(code_point), 0);
  1168. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  1169. auto glyph = font.glyph(code_point, glyph_position.subpixel_offset);
  1170. if (glyph.is_glyph_bitmap()) {
  1171. draw_bitmap(top_left.to_type<int>(), glyph.glyph_bitmap(), color);
  1172. } else if (glyph.is_color_bitmap()) {
  1173. float scaled_width = glyph.advance();
  1174. float ratio = static_cast<float>(glyph.bitmap()->height()) / static_cast<float>(glyph.bitmap()->width());
  1175. float scaled_height = scaled_width * ratio;
  1176. FloatRect rect(point.x(), point.y(), scaled_width, scaled_height);
  1177. draw_scaled_bitmap(rect.to_rounded<int>(), *glyph.bitmap(), glyph.bitmap()->rect(), 1.0f, ScalingMode::BilinearBlend);
  1178. } else if (color.alpha() != 255) {
  1179. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1180. return pixel.multiply(color);
  1181. });
  1182. } else {
  1183. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1184. return color.with_alpha(pixel.alpha());
  1185. });
  1186. }
  1187. }
  1188. void Painter::draw_emoji(IntPoint point, Gfx::Bitmap const& emoji, Font const& font)
  1189. {
  1190. IntRect dst_rect {
  1191. point.x(),
  1192. point.y(),
  1193. font.pixel_size_rounded_up() * emoji.width() / emoji.height(),
  1194. font.pixel_size_rounded_up(),
  1195. };
  1196. draw_scaled_bitmap(dst_rect, emoji, emoji.rect());
  1197. }
  1198. void Painter::draw_glyph_or_emoji(FloatPoint point, u32 code_point, Font const& font, Color color)
  1199. {
  1200. StringBuilder builder;
  1201. builder.append_code_point(code_point);
  1202. auto it = Utf8View { builder.string_view() }.begin();
  1203. return draw_glyph_or_emoji(point, it, font, color);
  1204. }
  1205. void Painter::draw_glyph_or_emoji(FloatPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1206. {
  1207. auto draw_glyph_or_emoji = prepare_draw_glyph_or_emoji(point, it, font);
  1208. if (draw_glyph_or_emoji.has<DrawGlyph>()) {
  1209. auto& glyph = draw_glyph_or_emoji.get<DrawGlyph>();
  1210. draw_glyph(glyph.position, glyph.code_point, *glyph.font, color);
  1211. } else {
  1212. auto& emoji = draw_glyph_or_emoji.get<DrawEmoji>();
  1213. draw_emoji(emoji.position.to_type<int>(), *emoji.emoji, *emoji.font);
  1214. }
  1215. }
  1216. void Painter::draw_glyph(IntPoint point, u32 code_point, Color color)
  1217. {
  1218. draw_glyph(point.to_type<float>(), code_point, font(), color);
  1219. }
  1220. void Painter::draw_glyph(IntPoint point, u32 code_point, Font const& font, Color color)
  1221. {
  1222. draw_glyph(point.to_type<float>(), code_point, font, color);
  1223. }
  1224. void Painter::draw_glyph_or_emoji(IntPoint point, u32 code_point, Font const& font, Color color)
  1225. {
  1226. draw_glyph_or_emoji(point.to_type<float>(), code_point, font, color);
  1227. }
  1228. void Painter::draw_glyph_or_emoji(IntPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1229. {
  1230. draw_glyph_or_emoji(point.to_type<float>(), it, font, color);
  1231. }
  1232. template<typename DrawGlyphFunction>
  1233. void draw_text_line(FloatRect const& a_rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextDirection direction, DrawGlyphFunction draw_glyph)
  1234. {
  1235. auto rect = a_rect;
  1236. switch (alignment) {
  1237. case TextAlignment::TopLeft:
  1238. case TextAlignment::CenterLeft:
  1239. case TextAlignment::BottomLeft:
  1240. break;
  1241. case TextAlignment::TopRight:
  1242. case TextAlignment::CenterRight:
  1243. case TextAlignment::BottomRight:
  1244. rect.set_x(rect.right() - 1 - font.width(text));
  1245. break;
  1246. case TextAlignment::TopCenter:
  1247. case TextAlignment::BottomCenter:
  1248. case TextAlignment::Center: {
  1249. auto shrunken_rect = rect;
  1250. shrunken_rect.set_width(font.width(text));
  1251. shrunken_rect.center_within(rect);
  1252. rect = shrunken_rect;
  1253. break;
  1254. }
  1255. default:
  1256. VERIFY_NOT_REACHED();
  1257. }
  1258. auto point = rect.location();
  1259. auto space_width = font.glyph_width(' ') + font.glyph_spacing();
  1260. if (direction == TextDirection::RTL) {
  1261. point.translate_by(rect.width(), 0); // Start drawing from the end
  1262. space_width = -space_width; // Draw spaces backwards
  1263. }
  1264. u32 last_code_point { 0 };
  1265. for (auto it = text.begin(); it != text.end(); ++it) {
  1266. auto code_point = *it;
  1267. if (should_paint_as_space(code_point)) {
  1268. point.translate_by(space_width, 0);
  1269. last_code_point = code_point;
  1270. continue;
  1271. }
  1272. auto kerning = font.glyphs_horizontal_kerning(last_code_point, code_point);
  1273. if (kerning != 0.0f)
  1274. point.translate_by(direction == TextDirection::LTR ? kerning : -kerning, 0);
  1275. auto it_copy = it; // The callback function will advance the iterator, so create a copy for this lookup.
  1276. FloatSize glyph_size(font.glyph_or_emoji_width(it_copy) + font.glyph_spacing(), font.pixel_size());
  1277. if (direction == TextDirection::RTL)
  1278. point.translate_by(-glyph_size.width(), 0); // If we are drawing right to left, we have to move backwards before drawing the glyph
  1279. draw_glyph({ point, glyph_size }, it);
  1280. if (direction == TextDirection::LTR)
  1281. point.translate_by(glyph_size.width(), 0);
  1282. // The callback function might have exhausted the iterator.
  1283. if (it == text.end())
  1284. break;
  1285. last_code_point = code_point;
  1286. }
  1287. }
  1288. static inline size_t draw_text_get_length(Utf8View const& text)
  1289. {
  1290. return text.byte_length();
  1291. }
  1292. Vector<DirectionalRun> Painter::split_text_into_directional_runs(Utf8View const& text, TextDirection initial_direction)
  1293. {
  1294. // FIXME: This is a *very* simplified version of the UNICODE BIDIRECTIONAL ALGORITHM (https://www.unicode.org/reports/tr9/), that can render most bidirectional text
  1295. // but also produces awkward results in a large amount of edge cases. This should probably be replaced with a fully spec compliant implementation at some point.
  1296. // FIXME: Support HTML "dir" attribute (how?)
  1297. u8 paragraph_embedding_level = initial_direction == TextDirection::LTR ? 0 : 1;
  1298. Vector<u8> embedding_levels;
  1299. embedding_levels.ensure_capacity(text.length());
  1300. for (size_t i = 0; i < text.length(); i++)
  1301. embedding_levels.unchecked_append(paragraph_embedding_level);
  1302. // FIXME: Support Explicit Directional Formatting Characters
  1303. Vector<BidirectionalClass> character_classes;
  1304. character_classes.ensure_capacity(text.length());
  1305. for (u32 code_point : text)
  1306. character_classes.unchecked_append(get_char_bidi_class(code_point));
  1307. // resolving weak types
  1308. BidirectionalClass paragraph_class = initial_direction == TextDirection::LTR ? BidirectionalClass::STRONG_LTR : BidirectionalClass::STRONG_RTL;
  1309. for (size_t i = 0; i < character_classes.size(); i++) {
  1310. if (character_classes[i] != BidirectionalClass::WEAK_SEPARATORS)
  1311. continue;
  1312. for (ssize_t j = i - 1; j >= 0; j--) {
  1313. auto character_class = character_classes[j];
  1314. if (character_class != BidirectionalClass::STRONG_RTL && character_class != BidirectionalClass::STRONG_LTR)
  1315. continue;
  1316. character_classes[i] = character_class;
  1317. break;
  1318. }
  1319. if (character_classes[i] == BidirectionalClass::WEAK_SEPARATORS)
  1320. character_classes[i] = paragraph_class;
  1321. }
  1322. // resolving neutral types
  1323. auto left_side = BidirectionalClass::NEUTRAL;
  1324. auto sequence_length = 0;
  1325. for (size_t i = 0; i < character_classes.size(); i++) {
  1326. auto character_class = character_classes[i];
  1327. if (left_side == BidirectionalClass::NEUTRAL) {
  1328. if (character_class != BidirectionalClass::NEUTRAL)
  1329. left_side = character_class;
  1330. else
  1331. character_classes[i] = paragraph_class;
  1332. continue;
  1333. }
  1334. if (character_class != BidirectionalClass::NEUTRAL) {
  1335. BidirectionalClass sequence_class;
  1336. if (bidi_class_to_direction(left_side) == bidi_class_to_direction(character_class)) {
  1337. sequence_class = left_side == BidirectionalClass::STRONG_RTL ? BidirectionalClass::STRONG_RTL : BidirectionalClass::STRONG_LTR;
  1338. } else {
  1339. sequence_class = paragraph_class;
  1340. }
  1341. for (auto j = 0; j < sequence_length; j++) {
  1342. character_classes[i - j - 1] = sequence_class;
  1343. }
  1344. sequence_length = 0;
  1345. left_side = character_class;
  1346. } else {
  1347. sequence_length++;
  1348. }
  1349. }
  1350. for (auto i = 0; i < sequence_length; i++)
  1351. character_classes[character_classes.size() - i - 1] = paragraph_class;
  1352. // resolving implicit levels
  1353. for (size_t i = 0; i < character_classes.size(); i++) {
  1354. auto character_class = character_classes[i];
  1355. if ((embedding_levels[i] % 2) == 0) {
  1356. if (character_class == BidirectionalClass::STRONG_RTL)
  1357. embedding_levels[i] += 1;
  1358. else if (character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1359. embedding_levels[i] += 2;
  1360. } else {
  1361. if (character_class == BidirectionalClass::STRONG_LTR || character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1362. embedding_levels[i] += 1;
  1363. }
  1364. }
  1365. // splitting into runs
  1366. auto run_code_points_start = text.begin();
  1367. auto next_code_points_slice = [&](auto length) {
  1368. Vector<u32> run_code_points;
  1369. run_code_points.ensure_capacity(length);
  1370. for (size_t j = 0; j < length; ++j, ++run_code_points_start)
  1371. run_code_points.unchecked_append(*run_code_points_start);
  1372. return run_code_points;
  1373. };
  1374. Vector<DirectionalRun> runs;
  1375. size_t start = 0;
  1376. u8 level = embedding_levels[0];
  1377. for (size_t i = 1; i < embedding_levels.size(); ++i) {
  1378. if (embedding_levels[i] == level)
  1379. continue;
  1380. auto code_points_slice = next_code_points_slice(i - start);
  1381. runs.append({ move(code_points_slice), level });
  1382. start = i;
  1383. level = embedding_levels[i];
  1384. }
  1385. auto code_points_slice = next_code_points_slice(embedding_levels.size() - start);
  1386. runs.append({ move(code_points_slice), level });
  1387. // reordering resolved levels
  1388. // FIXME: missing special cases for trailing whitespace characters
  1389. u8 minimum_level = 128;
  1390. u8 maximum_level = 0;
  1391. for (auto& run : runs) {
  1392. minimum_level = min(minimum_level, run.embedding_level());
  1393. maximum_level = max(minimum_level, run.embedding_level());
  1394. }
  1395. if ((minimum_level % 2) == 0)
  1396. minimum_level++;
  1397. auto runs_count = runs.size() - 1;
  1398. while (maximum_level <= minimum_level) {
  1399. size_t run_index = 0;
  1400. while (run_index < runs_count) {
  1401. while (run_index < runs_count && runs[run_index].embedding_level() < maximum_level)
  1402. run_index++;
  1403. auto reverse_start = run_index;
  1404. while (run_index <= runs_count && runs[run_index].embedding_level() >= maximum_level)
  1405. run_index++;
  1406. auto reverse_end = run_index - 1;
  1407. while (reverse_start < reverse_end) {
  1408. swap(runs[reverse_start], runs[reverse_end]);
  1409. reverse_start++;
  1410. reverse_end--;
  1411. }
  1412. }
  1413. maximum_level--;
  1414. }
  1415. // mirroring RTL mirror characters
  1416. for (auto& run : runs) {
  1417. if (run.direction() == TextDirection::LTR)
  1418. continue;
  1419. for (auto& code_point : run.code_points()) {
  1420. code_point = get_mirror_char(code_point);
  1421. }
  1422. }
  1423. return runs;
  1424. }
  1425. bool Painter::text_contains_bidirectional_text(Utf8View const& text, TextDirection initial_direction)
  1426. {
  1427. for (u32 code_point : text) {
  1428. auto char_class = get_char_bidi_class(code_point);
  1429. if (char_class == BidirectionalClass::NEUTRAL)
  1430. continue;
  1431. if (bidi_class_to_direction(char_class) != initial_direction)
  1432. return true;
  1433. }
  1434. return false;
  1435. }
  1436. template<typename DrawGlyphFunction>
  1437. void Painter::do_draw_text(FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping, DrawGlyphFunction draw_glyph)
  1438. {
  1439. if (draw_text_get_length(text) == 0)
  1440. return;
  1441. TextLayout layout(font, text, rect);
  1442. auto line_height = font.preferred_line_height();
  1443. auto lines = layout.lines(elision, wrapping);
  1444. auto bounding_rect = layout.bounding_rect(wrapping);
  1445. bounding_rect.align_within(rect, alignment);
  1446. for (size_t i = 0; i < lines.size(); ++i) {
  1447. auto line = Utf8View { lines[i] };
  1448. FloatRect line_rect { bounding_rect.x(), bounding_rect.y() + i * line_height, bounding_rect.width(), line_height };
  1449. TextDirection line_direction = get_text_direction(line);
  1450. if (text_contains_bidirectional_text(line, line_direction)) { // Slow Path: The line contains mixed BiDi classes
  1451. auto directional_runs = split_text_into_directional_runs(line, line_direction);
  1452. auto current_dx = line_direction == TextDirection::LTR ? 0 : line_rect.width();
  1453. for (auto& directional_run : directional_runs) {
  1454. auto run_width = font.width(directional_run.text());
  1455. if (line_direction == TextDirection::RTL)
  1456. current_dx -= run_width;
  1457. auto run_rect = line_rect.translated(current_dx, 0);
  1458. run_rect.set_width(run_width);
  1459. // NOTE: DirectionalRun returns Utf32View which isn't
  1460. // compatible with draw_text_line.
  1461. StringBuilder builder;
  1462. builder.append(directional_run.text());
  1463. auto line_text = Utf8View { builder.string_view() };
  1464. draw_text_line(run_rect, line_text, font, alignment, directional_run.direction(), draw_glyph);
  1465. if (line_direction == TextDirection::LTR)
  1466. current_dx += run_width;
  1467. }
  1468. } else {
  1469. draw_text_line(line_rect, line, font, alignment, line_direction, draw_glyph);
  1470. }
  1471. }
  1472. }
  1473. void Painter::draw_text(FloatRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1474. {
  1475. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1476. }
  1477. void Painter::draw_text(FloatRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1478. {
  1479. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1480. }
  1481. void Painter::draw_text(FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1482. {
  1483. Utf8View text { raw_text };
  1484. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1485. draw_glyph_or_emoji(r.location(), it, font, color);
  1486. });
  1487. }
  1488. void Painter::draw_text(FloatRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1489. {
  1490. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1491. // being some places might depend on it, so we do some internal conversion.
  1492. StringBuilder builder;
  1493. builder.append(raw_text);
  1494. auto text = Utf8View { builder.string_view() };
  1495. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1496. draw_glyph_or_emoji(r.location(), it, font, color);
  1497. });
  1498. }
  1499. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1500. {
  1501. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1502. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1503. draw_one_glyph(r, it);
  1504. });
  1505. }
  1506. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1507. {
  1508. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1509. Utf8View text { raw_text };
  1510. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1511. draw_one_glyph(r, it);
  1512. });
  1513. }
  1514. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, FloatRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1515. {
  1516. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1517. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1518. // being some places might depend on it, so we do some internal conversion.
  1519. StringBuilder builder;
  1520. builder.append(raw_text);
  1521. auto text = Utf8View { builder.string_view() };
  1522. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1523. draw_one_glyph(r, it);
  1524. });
  1525. }
  1526. void Painter::draw_text(IntRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1527. {
  1528. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1529. }
  1530. void Painter::draw_text(IntRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1531. {
  1532. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1533. }
  1534. void Painter::draw_text(IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1535. {
  1536. draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1537. }
  1538. void Painter::draw_text(IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1539. {
  1540. return draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1541. }
  1542. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1543. {
  1544. return draw_text(move(draw_one_glyph), rect.to_type<float>(), text, font, alignment, elision, wrapping);
  1545. }
  1546. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1547. {
  1548. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1549. }
  1550. void Painter::draw_text(Function<void(FloatRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1551. {
  1552. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1553. }
  1554. void Painter::set_pixel(IntPoint p, Color color, bool blend)
  1555. {
  1556. auto point = p;
  1557. point.translate_by(state().translation);
  1558. // Use the scale only to avoid clipping pixels set in drawing functions that handle
  1559. // scaling and call set_pixel() -- do not scale the pixel.
  1560. if (!clip_rect().contains(point / scale()))
  1561. return;
  1562. set_physical_pixel(point, color, blend);
  1563. }
  1564. void Painter::set_physical_pixel(IntPoint physical_point, Color color, bool blend)
  1565. {
  1566. // This function should only be called after translation, clipping, etc has been handled elsewhere
  1567. // if not use set_pixel().
  1568. auto& dst = m_target->scanline(physical_point.y())[physical_point.x()];
  1569. if (!blend || color.alpha() == 255)
  1570. dst = color.value();
  1571. else if (color.alpha())
  1572. dst = color_for_format(target()->format(), dst).blend(color).value();
  1573. }
  1574. Optional<Color> Painter::get_pixel(IntPoint p)
  1575. {
  1576. auto point = p;
  1577. point.translate_by(state().translation);
  1578. if (!clip_rect().contains(point / scale()))
  1579. return {};
  1580. return m_target->get_pixel(point);
  1581. }
  1582. ErrorOr<NonnullRefPtr<Bitmap>> Painter::get_region_bitmap(IntRect const& region, BitmapFormat format, Optional<IntRect&> actual_region)
  1583. {
  1584. VERIFY(scale() == 1);
  1585. auto bitmap_region = region.translated(state().translation).intersected(m_target->rect());
  1586. if (actual_region.has_value())
  1587. actual_region.value() = bitmap_region.translated(-state().translation);
  1588. return m_target->cropped(bitmap_region, format);
  1589. }
  1590. ALWAYS_INLINE void Painter::set_physical_pixel_with_draw_op(u32& pixel, Color color)
  1591. {
  1592. // This always sets a single physical pixel, independent of scale().
  1593. // This should only be called by routines that already handle scale.
  1594. switch (draw_op()) {
  1595. case DrawOp::Copy:
  1596. pixel = color.value();
  1597. break;
  1598. case DrawOp::Xor:
  1599. pixel = color.xored(Color::from_argb(pixel)).value();
  1600. break;
  1601. case DrawOp::Invert:
  1602. pixel = Color::from_argb(pixel).inverted().value();
  1603. break;
  1604. }
  1605. }
  1606. ALWAYS_INLINE void Painter::fill_physical_scanline_with_draw_op(int y, int x, int width, Color color)
  1607. {
  1608. // This always draws a single physical scanline, independent of scale().
  1609. // This should only be called by routines that already handle scale.
  1610. auto dst_format = m_target->format();
  1611. switch (draw_op()) {
  1612. case DrawOp::Copy:
  1613. fast_u32_fill(m_target->scanline(y) + x, color.value(), width);
  1614. break;
  1615. case DrawOp::Xor: {
  1616. auto* pixel = m_target->scanline(y) + x;
  1617. auto* end = pixel + width;
  1618. while (pixel < end) {
  1619. *pixel = color_for_format(dst_format, *pixel).xored(color).value();
  1620. pixel++;
  1621. }
  1622. break;
  1623. }
  1624. case DrawOp::Invert: {
  1625. auto* pixel = m_target->scanline(y) + x;
  1626. auto* end = pixel + width;
  1627. while (pixel < end) {
  1628. *pixel = color_for_format(dst_format, *pixel).inverted().value();
  1629. pixel++;
  1630. }
  1631. break;
  1632. }
  1633. }
  1634. }
  1635. void Painter::draw_physical_pixel(IntPoint physical_position, Color color, int thickness)
  1636. {
  1637. // This always draws a single physical pixel, independent of scale().
  1638. // This should only be called by routines that already handle scale
  1639. // (including scaling thickness).
  1640. VERIFY(draw_op() == DrawOp::Copy);
  1641. if (thickness <= 0)
  1642. return;
  1643. if (thickness == 1) { // Implies scale() == 1.
  1644. auto& pixel = m_target->scanline(physical_position.y())[physical_position.x()];
  1645. return set_physical_pixel_with_draw_op(pixel, color_for_format(m_target->format(), pixel).blend(color));
  1646. }
  1647. IntRect rect { physical_position, { thickness, thickness } };
  1648. rect.intersect(clip_rect() * scale());
  1649. fill_physical_rect(rect, color);
  1650. }
  1651. void Painter::draw_line(IntPoint a_p1, IntPoint a_p2, Color color, int thickness, LineStyle style, Color alternate_color)
  1652. {
  1653. if (clip_rect().is_empty())
  1654. return;
  1655. if (thickness <= 0)
  1656. return;
  1657. if (color.alpha() == 0)
  1658. return;
  1659. auto clip_rect = this->clip_rect() * scale();
  1660. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1661. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1662. auto point1 = to_physical(p1);
  1663. auto point2 = to_physical(p2);
  1664. thickness *= scale();
  1665. auto alternate_color_is_transparent = alternate_color == Color::Transparent;
  1666. // Special case: vertical line.
  1667. if (point1.x() == point2.x()) {
  1668. int const x = point1.x();
  1669. if (x < clip_rect.left() || x >= clip_rect.right())
  1670. return;
  1671. if (point1.y() > point2.y())
  1672. swap(point1, point2);
  1673. if (point1.y() >= clip_rect.bottom())
  1674. return;
  1675. if (point2.y() < clip_rect.top())
  1676. return;
  1677. int min_y = max(point1.y(), clip_rect.top());
  1678. int max_y = min(point2.y(), clip_rect.bottom() - 1);
  1679. if (style == LineStyle::Dotted) {
  1680. for (int y = min_y; y <= max_y; y += thickness * 2)
  1681. draw_physical_pixel({ x, y }, color, thickness);
  1682. } else if (style == LineStyle::Dashed) {
  1683. for (int y = min_y; y <= max_y; y += thickness * 6) {
  1684. draw_physical_pixel({ x, y }, color, thickness);
  1685. draw_physical_pixel({ x, min(y + thickness, max_y) }, color, thickness);
  1686. draw_physical_pixel({ x, min(y + thickness * 2, max_y) }, color, thickness);
  1687. if (!alternate_color_is_transparent) {
  1688. draw_physical_pixel({ x, min(y + thickness * 3, max_y) }, alternate_color, thickness);
  1689. draw_physical_pixel({ x, min(y + thickness * 4, max_y) }, alternate_color, thickness);
  1690. draw_physical_pixel({ x, min(y + thickness * 5, max_y) }, alternate_color, thickness);
  1691. }
  1692. }
  1693. } else {
  1694. for (int y = min_y; y <= max_y; y += thickness)
  1695. draw_physical_pixel({ x, y }, color, thickness);
  1696. draw_physical_pixel({ x, max_y }, color, thickness);
  1697. }
  1698. return;
  1699. }
  1700. // Special case: horizontal line.
  1701. if (point1.y() == point2.y()) {
  1702. int const y = point1.y();
  1703. if (y < clip_rect.top() || y >= clip_rect.bottom())
  1704. return;
  1705. if (point1.x() > point2.x())
  1706. swap(point1, point2);
  1707. if (point1.x() >= clip_rect.right())
  1708. return;
  1709. if (point2.x() < clip_rect.left())
  1710. return;
  1711. int min_x = max(point1.x(), clip_rect.left());
  1712. int max_x = min(point2.x(), clip_rect.right() - 1);
  1713. if (style == LineStyle::Dotted) {
  1714. for (int x = min_x; x <= max_x; x += thickness * 2)
  1715. draw_physical_pixel({ x, y }, color, thickness);
  1716. } else if (style == LineStyle::Dashed) {
  1717. for (int x = min_x; x <= max_x; x += thickness * 6) {
  1718. draw_physical_pixel({ x, y }, color, thickness);
  1719. draw_physical_pixel({ min(x + thickness, max_x), y }, color, thickness);
  1720. draw_physical_pixel({ min(x + thickness * 2, max_x), y }, color, thickness);
  1721. if (!alternate_color_is_transparent) {
  1722. draw_physical_pixel({ min(x + thickness * 3, max_x), y }, alternate_color, thickness);
  1723. draw_physical_pixel({ min(x + thickness * 4, max_x), y }, alternate_color, thickness);
  1724. draw_physical_pixel({ min(x + thickness * 5, max_x), y }, alternate_color, thickness);
  1725. }
  1726. }
  1727. } else {
  1728. for (int x = min_x; x <= max_x; x += thickness)
  1729. draw_physical_pixel({ x, y }, color, thickness);
  1730. draw_physical_pixel({ max_x, y }, color, thickness);
  1731. }
  1732. return;
  1733. }
  1734. int const adx = abs(point2.x() - point1.x());
  1735. int const ady = abs(point2.y() - point1.y());
  1736. if (adx > ady) {
  1737. if (point1.x() > point2.x())
  1738. swap(point1, point2);
  1739. } else {
  1740. if (point1.y() > point2.y())
  1741. swap(point1, point2);
  1742. }
  1743. int const dx = point2.x() - point1.x();
  1744. int const dy = point2.y() - point1.y();
  1745. int error = 0;
  1746. size_t number_of_pixels_drawn = 0;
  1747. auto draw_pixel_in_line = [&](int x, int y) {
  1748. bool should_draw_line = true;
  1749. if (style == LineStyle::Dotted && number_of_pixels_drawn % 2 == 1)
  1750. should_draw_line = false;
  1751. else if (style == LineStyle::Dashed && number_of_pixels_drawn % 6 >= 3)
  1752. should_draw_line = false;
  1753. if (should_draw_line)
  1754. draw_physical_pixel({ x, y }, color, thickness);
  1755. else if (!alternate_color_is_transparent)
  1756. draw_physical_pixel({ x, y }, alternate_color, thickness);
  1757. number_of_pixels_drawn++;
  1758. };
  1759. if (dx > dy) {
  1760. int const y_step = dy == 0 ? 0 : (dy > 0 ? 1 : -1);
  1761. int const delta_error = 2 * abs(dy);
  1762. int y = point1.y();
  1763. for (int x = point1.x(); x <= point2.x(); ++x) {
  1764. if (clip_rect.contains(x, y))
  1765. draw_pixel_in_line(x, y);
  1766. error += delta_error;
  1767. if (error >= dx) {
  1768. y += y_step;
  1769. error -= 2 * dx;
  1770. }
  1771. }
  1772. } else {
  1773. int const x_step = dx == 0 ? 0 : (dx > 0 ? 1 : -1);
  1774. int const delta_error = 2 * abs(dx);
  1775. int x = point1.x();
  1776. for (int y = point1.y(); y <= point2.y(); ++y) {
  1777. if (clip_rect.contains(x, y))
  1778. draw_pixel_in_line(x, y);
  1779. error += delta_error;
  1780. if (error >= dy) {
  1781. x += x_step;
  1782. error -= 2 * dy;
  1783. }
  1784. }
  1785. }
  1786. }
  1787. void Painter::draw_triangle_wave(IntPoint a_p1, IntPoint a_p2, Color color, int amplitude, int thickness)
  1788. {
  1789. // FIXME: Support more than horizontal waves
  1790. VERIFY(a_p1.y() == a_p2.y());
  1791. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1792. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1793. auto point1 = to_physical(p1);
  1794. auto point2 = to_physical(p2);
  1795. auto y = point1.y();
  1796. for (int x = 0; x <= point2.x() - point1.x(); ++x) {
  1797. auto y_offset = abs(x % (2 * amplitude) - amplitude) - amplitude;
  1798. draw_physical_pixel({ point1.x() + x, y + y_offset }, color, thickness);
  1799. }
  1800. }
  1801. static bool can_approximate_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control)
  1802. {
  1803. // TODO: Somehow calculate the required number of splits based on the curve (and its size).
  1804. constexpr float tolerance = 0.5f;
  1805. auto p1x = 3 * control.x() - 2 * p1.x() - p2.x();
  1806. auto p1y = 3 * control.y() - 2 * p1.y() - p2.y();
  1807. auto p2x = 3 * control.x() - 2 * p2.x() - p1.x();
  1808. auto p2y = 3 * control.y() - 2 * p2.y() - p1.y();
  1809. p1x = p1x * p1x;
  1810. p1y = p1y * p1y;
  1811. p2x = p2x * p2x;
  1812. p2y = p2y * p2y;
  1813. auto error = max(p1x, p2x) + max(p1y, p2y);
  1814. VERIFY(isfinite(error));
  1815. return error <= tolerance;
  1816. }
  1817. // static
  1818. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1819. {
  1820. struct SegmentDescriptor {
  1821. FloatPoint control_point;
  1822. FloatPoint p1;
  1823. FloatPoint p2;
  1824. };
  1825. static constexpr auto split_quadratic_bezier_curve = [](FloatPoint original_control, FloatPoint p1, FloatPoint p2, auto& segments) {
  1826. auto po1_midpoint = original_control + p1;
  1827. po1_midpoint /= 2;
  1828. auto po2_midpoint = original_control + p2;
  1829. po2_midpoint /= 2;
  1830. auto new_segment = po1_midpoint + po2_midpoint;
  1831. new_segment /= 2;
  1832. segments.append({ po2_midpoint, new_segment, p2 });
  1833. segments.append({ po1_midpoint, p1, new_segment });
  1834. };
  1835. Vector<SegmentDescriptor> segments;
  1836. segments.append({ control_point, p1, p2 });
  1837. while (!segments.is_empty()) {
  1838. auto segment = segments.take_last();
  1839. if (can_approximate_bezier_curve(segment.p1, segment.p2, segment.control_point))
  1840. callback(segment.p1, segment.p2);
  1841. else
  1842. split_quadratic_bezier_curve(segment.control_point, segment.p1, segment.p2, segments);
  1843. }
  1844. }
  1845. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1846. {
  1847. for_each_line_segment_on_bezier_curve(control_point, p1, p2, callback);
  1848. }
  1849. void Painter::draw_quadratic_bezier_curve(IntPoint control_point, IntPoint p1, IntPoint p2, Color color, int thickness, LineStyle style)
  1850. {
  1851. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1852. if (thickness <= 0)
  1853. return;
  1854. for_each_line_segment_on_bezier_curve(FloatPoint(control_point), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1855. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1856. });
  1857. }
  1858. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint control_point_0, FloatPoint control_point_1, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1859. {
  1860. for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback);
  1861. }
  1862. static bool can_approximate_cubic_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control_0, FloatPoint control_1)
  1863. {
  1864. // TODO: Somehow calculate the required number of splits based on the curve (and its size).
  1865. constexpr float tolerance = 0.5f;
  1866. auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x();
  1867. auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y();
  1868. auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x();
  1869. auto by = 3 * control_1.y() - p1.y() - 2 * p2.y();
  1870. ax *= ax;
  1871. ay *= ay;
  1872. bx *= bx;
  1873. by *= by;
  1874. auto error = max(ax, bx) + max(ay, by);
  1875. VERIFY(isfinite(error));
  1876. return error <= tolerance;
  1877. }
  1878. // static
  1879. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint control_point_0, FloatPoint control_point_1, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1880. {
  1881. struct ControlPair {
  1882. FloatPoint control_point_0;
  1883. FloatPoint control_point_1;
  1884. };
  1885. struct SegmentDescriptor {
  1886. ControlPair control_points;
  1887. FloatPoint p1;
  1888. FloatPoint p2;
  1889. };
  1890. static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint p1, FloatPoint p2, auto& segments) {
  1891. Array level_1_midpoints {
  1892. (p1 + original_controls.control_point_0) / 2,
  1893. (original_controls.control_point_0 + original_controls.control_point_1) / 2,
  1894. (original_controls.control_point_1 + p2) / 2,
  1895. };
  1896. Array level_2_midpoints {
  1897. (level_1_midpoints[0] + level_1_midpoints[1]) / 2,
  1898. (level_1_midpoints[1] + level_1_midpoints[2]) / 2,
  1899. };
  1900. auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2;
  1901. segments.append({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 });
  1902. segments.append({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint });
  1903. };
  1904. Vector<SegmentDescriptor> segments;
  1905. segments.append({ { control_point_0, control_point_1 }, p1, p2 });
  1906. while (!segments.is_empty()) {
  1907. auto segment = segments.take_last();
  1908. if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1))
  1909. callback(segment.p1, segment.p2);
  1910. else
  1911. split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments);
  1912. }
  1913. }
  1914. void Painter::draw_cubic_bezier_curve(IntPoint control_point_0, IntPoint control_point_1, IntPoint p1, IntPoint p2, Color color, int thickness, Painter::LineStyle style)
  1915. {
  1916. for_each_line_segment_on_cubic_bezier_curve(FloatPoint(control_point_0), FloatPoint(control_point_1), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1917. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1918. });
  1919. }
  1920. // static
  1921. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint p1, FloatPoint p2, FloatPoint center, FloatSize radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint, FloatPoint)>& callback)
  1922. {
  1923. if (radii.width() <= 0 || radii.height() <= 0)
  1924. return;
  1925. auto start = p1;
  1926. auto end = p2;
  1927. bool start_swapped = false;
  1928. if (theta_delta < 0) {
  1929. swap(start, end);
  1930. theta_1 = theta_1 + theta_delta;
  1931. theta_delta = fabsf(theta_delta);
  1932. start_swapped = true;
  1933. }
  1934. auto relative_start = start - center;
  1935. auto a = radii.width();
  1936. auto b = radii.height();
  1937. // The segments are at most 1 long
  1938. auto largest_radius = max(a, b);
  1939. float theta_step = AK::atan2(1.f, (float)largest_radius);
  1940. FloatPoint current_point = relative_start;
  1941. FloatPoint next_point = { 0, 0 };
  1942. float sin_x_axis, cos_x_axis;
  1943. AK::sincos(x_axis_rotation, sin_x_axis, cos_x_axis);
  1944. auto rotate_point = [sin_x_axis, cos_x_axis](FloatPoint& p) {
  1945. auto original_x = p.x();
  1946. auto original_y = p.y();
  1947. p.set_x(original_x * cos_x_axis - original_y * sin_x_axis);
  1948. p.set_y(original_x * sin_x_axis + original_y * cos_x_axis);
  1949. };
  1950. auto emit_point = [&](auto p0, auto p1) {
  1951. // NOTE: If we swap the start/end we must swap the emitted points, so correct winding orders can be calculated.
  1952. if (start_swapped)
  1953. swap(p0, p1);
  1954. callback(p0, p1);
  1955. };
  1956. for (float theta = theta_1; theta <= theta_1 + theta_delta; theta += theta_step) {
  1957. float s, c;
  1958. AK::sincos(theta, s, c);
  1959. next_point.set_x(a * c);
  1960. next_point.set_y(b * s);
  1961. rotate_point(next_point);
  1962. emit_point(current_point + center, next_point + center);
  1963. current_point = next_point;
  1964. }
  1965. emit_point(current_point + center, end);
  1966. }
  1967. // static
  1968. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint p1, FloatPoint p2, FloatPoint center, FloatSize radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint, FloatPoint)>&& callback)
  1969. {
  1970. for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, callback);
  1971. }
  1972. void Painter::draw_elliptical_arc(IntPoint p1, IntPoint p2, IntPoint center, FloatSize radii, float x_axis_rotation, float theta_1, float theta_delta, Color color, int thickness, LineStyle style)
  1973. {
  1974. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1975. if (thickness <= 0)
  1976. return;
  1977. for_each_line_segment_on_elliptical_arc(FloatPoint(p1), FloatPoint(p2), FloatPoint(center), radii, x_axis_rotation, theta_1, theta_delta, [&](FloatPoint fp1, FloatPoint fp2) {
  1978. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1979. });
  1980. }
  1981. void Painter::add_clip_rect(IntRect const& rect)
  1982. {
  1983. state().clip_rect.intersect(rect.translated(translation()));
  1984. state().clip_rect.intersect(m_target->rect()); // FIXME: This shouldn't be necessary?
  1985. }
  1986. void Painter::clear_clip_rect()
  1987. {
  1988. state().clip_rect = m_clip_origin;
  1989. }
  1990. PainterStateSaver::PainterStateSaver(Painter& painter)
  1991. : m_painter(painter)
  1992. {
  1993. m_painter.save();
  1994. }
  1995. PainterStateSaver::~PainterStateSaver()
  1996. {
  1997. m_painter.restore();
  1998. }
  1999. void Painter::stroke_path(Path const& path, Color color, int thickness)
  2000. {
  2001. if (thickness <= 0)
  2002. return;
  2003. fill_path(path.stroke_to_fill(thickness), color);
  2004. }
  2005. void Painter::blit_disabled(IntPoint location, Gfx::Bitmap const& bitmap, IntRect const& rect, Palette const& palette)
  2006. {
  2007. auto bright_color = palette.threed_highlight();
  2008. auto dark_color = palette.threed_shadow1();
  2009. blit_filtered(location.translated(1, 1), bitmap, rect, [&](auto) {
  2010. return bright_color;
  2011. });
  2012. blit_filtered(location, bitmap, rect, [&](Color src) {
  2013. int gray = src.to_grayscale().red();
  2014. if (gray > 160)
  2015. return bright_color;
  2016. return dark_color;
  2017. });
  2018. }
  2019. void Painter::blit_tiled(IntRect const& dst_rect, Gfx::Bitmap const& bitmap, IntRect const& rect)
  2020. {
  2021. auto tile_width = rect.width();
  2022. auto tile_height = rect.height();
  2023. auto dst_right = dst_rect.right() - 1;
  2024. auto dst_bottom = dst_rect.bottom() - 1;
  2025. for (int tile_y = dst_rect.top(); tile_y < dst_bottom; tile_y += tile_height) {
  2026. for (int tile_x = dst_rect.left(); tile_x < dst_right; tile_x += tile_width) {
  2027. IntRect tile_src_rect = rect;
  2028. auto tile_x_overflow = tile_x + tile_width - dst_right;
  2029. if (tile_x_overflow > 0)
  2030. tile_src_rect.set_width(tile_width - tile_x_overflow);
  2031. auto tile_y_overflow = tile_y + tile_height - dst_bottom;
  2032. if (tile_y_overflow > 0)
  2033. tile_src_rect.set_height(tile_height - tile_y_overflow);
  2034. blit(IntPoint(tile_x, tile_y), bitmap, tile_src_rect);
  2035. }
  2036. }
  2037. }
  2038. ByteString parse_ampersand_string(StringView raw_text, Optional<size_t>* underline_offset)
  2039. {
  2040. if (raw_text.is_empty())
  2041. return ByteString::empty();
  2042. StringBuilder builder;
  2043. for (size_t i = 0; i < raw_text.length(); ++i) {
  2044. if (raw_text[i] == '&') {
  2045. if (i != (raw_text.length() - 1) && raw_text[i + 1] == '&') {
  2046. builder.append(raw_text[i]);
  2047. ++i;
  2048. } else if (underline_offset && !(*underline_offset).has_value()) {
  2049. *underline_offset = i;
  2050. }
  2051. continue;
  2052. }
  2053. builder.append(raw_text[i]);
  2054. }
  2055. return builder.to_byte_string();
  2056. }
  2057. void Gfx::Painter::draw_ui_text(Gfx::IntRect const& rect, StringView text, Gfx::Font const& font, Gfx::TextAlignment text_alignment, Gfx::Color color)
  2058. {
  2059. Optional<size_t> underline_offset;
  2060. auto name_to_draw = parse_ampersand_string(text, &underline_offset);
  2061. Gfx::IntRect text_rect { 0, 0, font.width_rounded_up(name_to_draw), font.pixel_size_rounded_up() };
  2062. text_rect.align_within(rect, text_alignment);
  2063. draw_text(text_rect, name_to_draw, font, text_alignment, color);
  2064. if (underline_offset.has_value()) {
  2065. Utf8View utf8_view { name_to_draw };
  2066. float width = 0;
  2067. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  2068. if (utf8_view.byte_offset_of(it) >= underline_offset.value()) {
  2069. int y = text_rect.bottom();
  2070. int x1 = text_rect.left() + width;
  2071. int x2 = x1 + font.glyph_or_emoji_width(it);
  2072. draw_line({ x1, y }, { x2, y }, color);
  2073. break;
  2074. }
  2075. width += font.glyph_or_emoji_width(it) + font.glyph_spacing();
  2076. }
  2077. }
  2078. }
  2079. void Painter::draw_text_run(IntPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2080. {
  2081. draw_text_run(baseline_start.to_type<float>(), string, font, color);
  2082. }
  2083. void Painter::draw_text_run(FloatPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2084. {
  2085. auto font_list = Gfx::FontCascadeList::create();
  2086. font_list->add(font);
  2087. for_each_glyph_position(baseline_start, string, font_list, [&](DrawGlyphOrEmoji glyph_or_emoji) {
  2088. if (glyph_or_emoji.has<DrawGlyph>()) {
  2089. auto& glyph = glyph_or_emoji.get<DrawGlyph>();
  2090. draw_glyph(glyph.position, glyph.code_point, *glyph.font, color);
  2091. } else {
  2092. auto& emoji = glyph_or_emoji.get<DrawEmoji>();
  2093. draw_emoji(emoji.position.to_type<int>(), *emoji.emoji, *emoji.font);
  2094. }
  2095. });
  2096. }
  2097. void Painter::draw_scaled_bitmap_with_transform(IntRect const& dst_rect, Bitmap const& bitmap, FloatRect const& src_rect, AffineTransform const& transform, float opacity, Painter::ScalingMode scaling_mode)
  2098. {
  2099. if (transform.is_identity_or_translation()) {
  2100. translate(transform.e(), transform.f());
  2101. draw_scaled_bitmap(dst_rect, bitmap, src_rect, opacity, scaling_mode);
  2102. translate(-transform.e(), -transform.f());
  2103. } else {
  2104. // The painter has an affine transform, we have to draw through it!
  2105. // FIXME: This is kinda inefficient.
  2106. // What we currently do, roughly:
  2107. // - Map the destination rect through the context's transform.
  2108. // - Compute the bounding rect of the destination quad.
  2109. // - For each point in the clipped bounding rect, reverse-map it to a point in the source image.
  2110. // - Sample the source image at the computed point.
  2111. // - Set or blend (depending on alpha values) one pixel in the canvas.
  2112. // - Loop.
  2113. // FIXME: Painter should have an affine transform as part of its state and handle all of this instead.
  2114. if (opacity == 0.0f)
  2115. return;
  2116. auto inverse_transform = transform.inverse();
  2117. if (!inverse_transform.has_value())
  2118. return;
  2119. auto destination_quad = transform.map_to_quad(dst_rect.to_type<float>());
  2120. auto destination_bounding_rect = destination_quad.bounding_rect().to_rounded<int>();
  2121. auto source_rect = enclosing_int_rect(src_rect).intersected(bitmap.rect());
  2122. Gfx::AffineTransform source_transform;
  2123. source_transform.translate(src_rect.x(), src_rect.y());
  2124. source_transform.scale(src_rect.width() / dst_rect.width(), src_rect.height() / dst_rect.height());
  2125. source_transform.translate(-dst_rect.x(), -dst_rect.y());
  2126. auto translated_dest_rect = destination_bounding_rect.translated(translation());
  2127. auto clipped_bounding_rect = translated_dest_rect.intersected(clip_rect());
  2128. if (clipped_bounding_rect.is_empty())
  2129. return;
  2130. auto sample_transform = source_transform.multiply(*inverse_transform);
  2131. auto start_offset = destination_bounding_rect.location() + (clipped_bounding_rect.location() - translated_dest_rect.location());
  2132. for (int y = 0; y < clipped_bounding_rect.height(); ++y) {
  2133. for (int x = 0; x < clipped_bounding_rect.width(); ++x) {
  2134. auto point = Gfx::IntPoint { x, y };
  2135. auto sample_point = point + start_offset;
  2136. // AffineTransform::map(IntPoint) rounds internally, which is wrong here. So explicitly call the FloatPoint version, and then truncate the result.
  2137. auto source_point = Gfx::IntPoint { sample_transform.map(Gfx::FloatPoint { sample_point }) };
  2138. if (!source_rect.contains(source_point))
  2139. continue;
  2140. auto source_color = bitmap.get_pixel(source_point);
  2141. if (source_color.alpha() == 0)
  2142. continue;
  2143. if (opacity != 1.0f)
  2144. source_color = source_color.with_opacity(opacity);
  2145. set_physical_pixel(point + clipped_bounding_rect.location(), source_color, true);
  2146. }
  2147. }
  2148. }
  2149. }
  2150. void Painter::draw_signed_distance_field(IntRect const& dst_rect, Color color, Gfx::GrayscaleBitmap const& sdf, float smoothing)
  2151. {
  2152. auto target_rect = dst_rect.translated(translation());
  2153. auto clipped_rect = target_rect.intersected(clip_rect());
  2154. if (clipped_rect.is_empty())
  2155. return;
  2156. target_rect *= scale();
  2157. clipped_rect *= scale();
  2158. auto start_offset = clipped_rect.location() - target_rect.location();
  2159. auto x_ratio = static_cast<float>(sdf.width() - 1) / (dst_rect.width() - 1);
  2160. auto y_ratio = static_cast<float>(sdf.height() - 1) / (dst_rect.height() - 1);
  2161. auto smooth_step = [](auto edge0, auto edge1, auto x) {
  2162. x = clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
  2163. return x * x * (3 - 2 * x);
  2164. };
  2165. auto pixel_at = [&](unsigned x, unsigned y) -> u8 {
  2166. // Returning 255 means this pixel is outside the shape.
  2167. if (x >= sdf.width() || y >= sdf.height())
  2168. return 255;
  2169. return sdf.pixel_at(x, y);
  2170. };
  2171. for (int i = 0; i < clipped_rect.height(); ++i) {
  2172. for (int j = 0; j < clipped_rect.width(); ++j) {
  2173. auto point = IntPoint { j, i };
  2174. auto sample_point = point + start_offset;
  2175. auto target_x = static_cast<int>(x_ratio * sample_point.x());
  2176. auto target_y = static_cast<int>(y_ratio * sample_point.y());
  2177. auto target_fraction_x = (x_ratio * sample_point.x()) - target_x;
  2178. auto target_fraction_y = (y_ratio * sample_point.y()) - target_y;
  2179. auto a = pixel_at(target_x, target_y);
  2180. auto b = pixel_at(target_x + 1, target_y);
  2181. auto c = pixel_at(target_x, target_y + 1);
  2182. auto d = pixel_at(target_x + 1, target_y + 1);
  2183. float distance = (a * (1 - target_fraction_x) * (1 - target_fraction_y)
  2184. + b * target_fraction_x * (1 - target_fraction_y)
  2185. + c * (1 - target_fraction_x) * target_fraction_y
  2186. + d * target_fraction_x * target_fraction_y)
  2187. / 255.0f;
  2188. u8 alpha = (1 - clamp(smooth_step(0.5f - smoothing, 0.5f + smoothing, distance), 0.0f, 1.0f)) * 255;
  2189. set_physical_pixel(point + clipped_rect.location(), color.with_alpha(alpha), true);
  2190. }
  2191. }
  2192. }
  2193. }