Painter.cpp 103 KB

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