Painter.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. /*
  2. * Copyright (c) 2018-2021, 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. *
  9. * SPDX-License-Identifier: BSD-2-Clause
  10. */
  11. #include "Painter.h"
  12. #include "Bitmap.h"
  13. #include "Emoji.h"
  14. #include "Font.h"
  15. #include "FontDatabase.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/FillPathImplementation.h>
  30. #include <LibGfx/Palette.h>
  31. #include <LibGfx/Path.h>
  32. #include <LibGfx/TextDirection.h>
  33. #include <LibGfx/TextLayout.h>
  34. #include <stdio.h>
  35. #if defined(__GNUC__) && !defined(__clang__)
  36. # pragma GCC optimize("O3")
  37. #endif
  38. namespace Gfx {
  39. template<BitmapFormat format = BitmapFormat::Invalid>
  40. ALWAYS_INLINE Color get_pixel(Gfx::Bitmap const& bitmap, int x, int y)
  41. {
  42. if constexpr (format == BitmapFormat::Indexed8)
  43. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  44. if constexpr (format == BitmapFormat::Indexed4)
  45. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  46. if constexpr (format == BitmapFormat::Indexed2)
  47. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  48. if constexpr (format == BitmapFormat::Indexed1)
  49. return bitmap.palette_color(bitmap.scanline_u8(y)[x]);
  50. if constexpr (format == BitmapFormat::BGRx8888)
  51. return Color::from_rgb(bitmap.scanline(y)[x]);
  52. if constexpr (format == BitmapFormat::BGRA8888)
  53. return Color::from_rgba(bitmap.scanline(y)[x]);
  54. return bitmap.get_pixel(x, y);
  55. }
  56. Painter::Painter(Gfx::Bitmap& bitmap)
  57. : m_target(bitmap)
  58. {
  59. int scale = bitmap.scale();
  60. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRx8888 || bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  61. VERIFY(bitmap.physical_width() % scale == 0);
  62. VERIFY(bitmap.physical_height() % scale == 0);
  63. m_state_stack.append(State());
  64. state().font = nullptr;
  65. state().clip_rect = { { 0, 0 }, bitmap.size() };
  66. state().scale = scale;
  67. m_clip_origin = state().clip_rect;
  68. }
  69. Painter::~Painter()
  70. {
  71. }
  72. void Painter::fill_rect_with_draw_op(IntRect const& a_rect, Color color)
  73. {
  74. VERIFY(scale() == 1); // FIXME: Add scaling support.
  75. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  76. if (rect.is_empty())
  77. return;
  78. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  79. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  80. for (int i = rect.height() - 1; i >= 0; --i) {
  81. for (int j = 0; j < rect.width(); ++j)
  82. set_physical_pixel_with_draw_op(dst[j], color);
  83. dst += dst_skip;
  84. }
  85. }
  86. void Painter::clear_rect(IntRect const& a_rect, Color color)
  87. {
  88. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  89. if (rect.is_empty())
  90. return;
  91. VERIFY(m_target->rect().contains(rect));
  92. rect *= scale();
  93. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  94. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  95. for (int i = rect.height() - 1; i >= 0; --i) {
  96. fast_u32_fill(dst, color.value(), rect.width());
  97. dst += dst_skip;
  98. }
  99. }
  100. void Painter::fill_physical_rect(IntRect const& physical_rect, Color color)
  101. {
  102. // Callers must do clipping.
  103. RGBA32* dst = m_target->scanline(physical_rect.top()) + physical_rect.left();
  104. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  105. for (int i = physical_rect.height() - 1; i >= 0; --i) {
  106. for (int j = 0; j < physical_rect.width(); ++j)
  107. dst[j] = Color::from_rgba(dst[j]).blend(color).value();
  108. dst += dst_skip;
  109. }
  110. }
  111. void Painter::fill_rect(IntRect const& a_rect, Color color)
  112. {
  113. if (color.alpha() == 0)
  114. return;
  115. if (draw_op() != DrawOp::Copy) {
  116. fill_rect_with_draw_op(a_rect, color);
  117. return;
  118. }
  119. if (color.alpha() == 0xff) {
  120. clear_rect(a_rect, color);
  121. return;
  122. }
  123. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  124. if (rect.is_empty())
  125. return;
  126. VERIFY(m_target->rect().contains(rect));
  127. fill_physical_rect(rect * scale(), color);
  128. }
  129. void Painter::fill_rect_with_dither_pattern(IntRect const& a_rect, Color color_a, Color color_b)
  130. {
  131. VERIFY(scale() == 1); // FIXME: Add scaling support.
  132. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  133. if (rect.is_empty())
  134. return;
  135. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  136. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  137. for (int i = 0; i < rect.height(); ++i) {
  138. for (int j = 0; j < rect.width(); ++j) {
  139. bool checkboard_use_a = ((rect.left() + i) & 1) ^ ((rect.top() + j) & 1);
  140. if (checkboard_use_a && !color_a.alpha())
  141. continue;
  142. if (!checkboard_use_a && !color_b.alpha())
  143. continue;
  144. dst[j] = checkboard_use_a ? color_a.value() : color_b.value();
  145. }
  146. dst += dst_skip;
  147. }
  148. }
  149. void Painter::fill_rect_with_checkerboard(IntRect const& a_rect, IntSize const& cell_size, Color color_dark, Color color_light)
  150. {
  151. VERIFY(scale() == 1); // FIXME: Add scaling support.
  152. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  153. if (rect.is_empty())
  154. return;
  155. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  156. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  157. int first_cell_column = rect.x() / cell_size.width();
  158. int prologue_length = min(rect.width(), cell_size.width() - (rect.x() % cell_size.width()));
  159. int number_of_aligned_strips = (rect.width() - prologue_length) / cell_size.width();
  160. for (int i = 0; i < rect.height(); ++i) {
  161. int y = rect.y() + i;
  162. int cell_row = y / cell_size.height();
  163. bool odd_row = cell_row & 1;
  164. // Prologue: Paint the unaligned part up to the first intersection.
  165. int j = 0;
  166. int cell_column = first_cell_column;
  167. {
  168. bool odd_cell = cell_column & 1;
  169. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  170. fast_u32_fill(&dst[j], color, prologue_length);
  171. j += prologue_length;
  172. }
  173. // Aligned run: Paint the maximum number of aligned cell strips.
  174. for (int strip = 0; strip < number_of_aligned_strips; ++strip) {
  175. ++cell_column;
  176. bool odd_cell = cell_column & 1;
  177. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  178. fast_u32_fill(&dst[j], color, cell_size.width());
  179. j += cell_size.width();
  180. }
  181. // Epilogue: Paint the unaligned part until the end of the rect.
  182. if (j != rect.width()) {
  183. ++cell_column;
  184. bool odd_cell = cell_column & 1;
  185. auto color = (odd_row ^ odd_cell) ? color_light.value() : color_dark.value();
  186. int epilogue_length = rect.width() - j;
  187. fast_u32_fill(&dst[j], color, epilogue_length);
  188. j += epilogue_length;
  189. }
  190. dst += dst_skip;
  191. }
  192. }
  193. void Painter::fill_rect_with_gradient(Orientation orientation, IntRect const& a_rect, Color gradient_start, Color gradient_end)
  194. {
  195. if (gradient_start == gradient_end) {
  196. fill_rect(a_rect, gradient_start);
  197. return;
  198. }
  199. auto rect = to_physical(a_rect);
  200. auto clipped_rect = IntRect::intersection(rect, clip_rect() * scale());
  201. if (clipped_rect.is_empty())
  202. return;
  203. int offset = clipped_rect.primary_offset_for_orientation(orientation) - rect.primary_offset_for_orientation(orientation);
  204. RGBA32* dst = m_target->scanline(clipped_rect.top()) + clipped_rect.left();
  205. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  206. float increment = (1.0 / ((rect.primary_size_for_orientation(orientation))));
  207. float alpha_increment = increment * ((float)gradient_end.alpha() - (float)gradient_start.alpha());
  208. if (orientation == Orientation::Horizontal) {
  209. for (int i = clipped_rect.height() - 1; i >= 0; --i) {
  210. float c = offset * increment;
  211. float c_alpha = gradient_start.alpha() + offset * alpha_increment;
  212. for (int j = 0; j < clipped_rect.width(); ++j) {
  213. auto color = gamma_accurate_blend(gradient_start, gradient_end, c);
  214. color.set_alpha(c_alpha);
  215. dst[j] = color.value();
  216. c_alpha += alpha_increment;
  217. c += increment;
  218. }
  219. dst += dst_skip;
  220. }
  221. } else {
  222. float c = offset * increment;
  223. float c_alpha = gradient_start.alpha() + offset * alpha_increment;
  224. for (int i = clipped_rect.height() - 1; i >= 0; --i) {
  225. auto color = gamma_accurate_blend(gradient_end, gradient_start, c);
  226. color.set_alpha(c_alpha);
  227. for (int j = 0; j < clipped_rect.width(); ++j) {
  228. dst[j] = color.value();
  229. }
  230. c_alpha += alpha_increment;
  231. c += increment;
  232. dst += dst_skip;
  233. }
  234. }
  235. }
  236. void Painter::fill_rect_with_gradient(IntRect const& a_rect, Color gradient_start, Color gradient_end)
  237. {
  238. return fill_rect_with_gradient(Orientation::Horizontal, a_rect, gradient_start, gradient_end);
  239. }
  240. void Painter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  241. {
  242. return fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  243. }
  244. 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)
  245. {
  246. // Fasttrack for rects without any border radii
  247. if (!top_left_radius && !top_right_radius && !bottom_right_radius && !bottom_left_radius)
  248. return fill_rect(a_rect, color);
  249. // Fully transparent, dont care.
  250. if (color.alpha() == 0)
  251. return;
  252. // FIXME: Allow for elliptically rounded corners
  253. IntRect top_left_corner = {
  254. a_rect.x(),
  255. a_rect.y(),
  256. top_left_radius,
  257. top_left_radius
  258. };
  259. IntRect top_right_corner = {
  260. a_rect.x() + a_rect.width() - top_right_radius,
  261. a_rect.y(),
  262. top_right_radius,
  263. top_right_radius
  264. };
  265. IntRect bottom_right_corner = {
  266. a_rect.x() + a_rect.width() - bottom_right_radius,
  267. a_rect.y() + a_rect.height() - bottom_right_radius,
  268. bottom_right_radius,
  269. bottom_right_radius
  270. };
  271. IntRect bottom_left_corner = {
  272. a_rect.x(),
  273. a_rect.y() + a_rect.height() - bottom_left_radius,
  274. bottom_left_radius,
  275. bottom_left_radius
  276. };
  277. IntRect top_rect = {
  278. a_rect.x() + top_left_radius,
  279. a_rect.y(),
  280. a_rect.width() - top_left_radius - top_right_radius, top_left_radius
  281. };
  282. IntRect right_rect = {
  283. a_rect.x() + a_rect.width() - top_right_radius,
  284. a_rect.y() + top_right_radius,
  285. top_right_radius,
  286. a_rect.height() - top_right_radius - bottom_right_radius
  287. };
  288. IntRect bottom_rect = {
  289. a_rect.x() + bottom_left_radius,
  290. a_rect.y() + a_rect.height() - bottom_right_radius,
  291. a_rect.width() - bottom_left_radius - bottom_right_radius,
  292. bottom_right_radius
  293. };
  294. IntRect left_rect = {
  295. a_rect.x(),
  296. a_rect.y() + top_left_radius,
  297. bottom_left_radius,
  298. a_rect.height() - top_left_radius - bottom_left_radius
  299. };
  300. IntRect inner = {
  301. left_rect.x() + left_rect.width(),
  302. left_rect.y(),
  303. a_rect.width() - left_rect.width() - right_rect.width(),
  304. a_rect.height() - top_rect.height() - bottom_rect.height()
  305. };
  306. fill_rect(top_rect, color);
  307. fill_rect(right_rect, color);
  308. fill_rect(bottom_rect, color);
  309. fill_rect(left_rect, color);
  310. fill_rect(inner, color);
  311. if (top_left_radius)
  312. fill_rounded_corner(top_left_corner, top_left_radius, color, CornerOrientation::TopLeft);
  313. if (top_right_radius)
  314. fill_rounded_corner(top_right_corner, top_right_radius, color, CornerOrientation::TopRight);
  315. if (bottom_left_radius)
  316. fill_rounded_corner(bottom_left_corner, bottom_left_radius, color, CornerOrientation::BottomLeft);
  317. if (bottom_right_radius)
  318. fill_rounded_corner(bottom_right_corner, bottom_right_radius, color, CornerOrientation::BottomRight);
  319. }
  320. void Painter::fill_rounded_corner(IntRect const& a_rect, int radius, Color color, CornerOrientation orientation)
  321. {
  322. // Care about clipping
  323. auto translated_a_rect = a_rect.translated(translation());
  324. auto rect = translated_a_rect.intersected(clip_rect());
  325. if (rect.is_empty())
  326. return;
  327. VERIFY(m_target->rect().contains(rect));
  328. // We got cut on the top!
  329. // FIXME: Also account for clipping on the x-axis
  330. int clip_offset = 0;
  331. if (translated_a_rect.y() < rect.y())
  332. clip_offset = rect.y() - translated_a_rect.y();
  333. radius *= scale();
  334. rect *= scale();
  335. clip_offset *= scale();
  336. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  337. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  338. IntPoint circle_center;
  339. switch (orientation) {
  340. case CornerOrientation::TopLeft:
  341. circle_center = { radius, radius + 1 };
  342. break;
  343. case CornerOrientation::TopRight:
  344. circle_center = { -1, radius + 1 };
  345. break;
  346. case CornerOrientation::BottomRight:
  347. circle_center = { -1, 0 };
  348. break;
  349. case CornerOrientation::BottomLeft:
  350. circle_center = { radius, 0 };
  351. break;
  352. default:
  353. VERIFY_NOT_REACHED();
  354. }
  355. int radius2 = radius * radius;
  356. auto is_in_circle = [&](int x, int y) {
  357. int distance2 = (circle_center.x() - x) * (circle_center.x() - x) + (circle_center.y() - y) * (circle_center.y() - y);
  358. // To reflect the grid and be compatible with the draw_circle_arc_intersecting algorithm
  359. // add 1/2 to the radius
  360. return distance2 <= (radius2 + radius + 0.25);
  361. };
  362. for (int i = rect.height() - 1; i >= 0; --i) {
  363. for (int j = 0; j < rect.width(); ++j)
  364. if (is_in_circle(j, rect.height() - i + clip_offset))
  365. dst[j] = Color::from_rgba(dst[j]).blend(color).value();
  366. dst += dst_skip;
  367. }
  368. }
  369. void Painter::draw_circle_arc_intersecting(IntRect const& a_rect, IntPoint const& center, int radius, Color color, int thickness)
  370. {
  371. if (thickness <= 0)
  372. return;
  373. // Care about clipping
  374. auto translated_a_rect = a_rect.translated(translation());
  375. auto rect = translated_a_rect.intersected(clip_rect());
  376. if (rect.is_empty())
  377. return;
  378. VERIFY(m_target->rect().contains(rect));
  379. // We got cut on the top!
  380. // FIXME: Also account for clipping on the x-axis
  381. int clip_offset = 0;
  382. if (translated_a_rect.y() < rect.y())
  383. clip_offset = rect.y() - translated_a_rect.y();
  384. if (thickness > radius)
  385. thickness = radius;
  386. int radius2 = radius * radius;
  387. auto is_on_arc = [&](int x, int y) {
  388. int distance2 = (center.x() - x) * (center.x() - x) + (center.y() - y) * (center.y() - y);
  389. // Is within a circle of radius 1/2 around (x,y), so basically within the current pixel.
  390. // Technically this is angle-dependent and should be between 1/2 and sqrt(2)/2, but this works.
  391. return distance2 <= (radius2 + radius + 0.25) && distance2 >= (radius2 - radius + 0.25);
  392. };
  393. RGBA32* dst = m_target->scanline(rect.top()) + rect.left();
  394. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  395. for (int i = rect.height() - 1; i >= 0; --i) {
  396. for (int j = 0; j < rect.width(); ++j)
  397. if (is_on_arc(j, rect.height() - i + clip_offset))
  398. dst[j] = Color::from_rgba(dst[j]).blend(color).value();
  399. dst += dst_skip;
  400. }
  401. return draw_circle_arc_intersecting(a_rect, center, radius - 1, color, thickness - 1);
  402. }
  403. void Painter::fill_ellipse(IntRect const& a_rect, Color color)
  404. {
  405. VERIFY(scale() == 1); // FIXME: Add scaling support.
  406. auto rect = a_rect.translated(translation()).intersected(clip_rect());
  407. if (rect.is_empty())
  408. return;
  409. VERIFY(m_target->rect().contains(rect));
  410. for (int i = 1; i < a_rect.height(); i++) {
  411. double y = a_rect.height() * 0.5 - i;
  412. double x = a_rect.width() * sqrt(0.25 - y * y / a_rect.height() / a_rect.height());
  413. draw_line({ a_rect.x() + a_rect.width() / 2 - (int)x, a_rect.y() + i }, { a_rect.x() + a_rect.width() / 2 + (int)x - 1, a_rect.y() + i }, color);
  414. }
  415. }
  416. void Painter::draw_ellipse_intersecting(IntRect const& rect, Color color, int thickness)
  417. {
  418. VERIFY(scale() == 1); // FIXME: Add scaling support.
  419. if (thickness <= 0)
  420. return;
  421. constexpr int number_samples = 100; // FIXME: dynamically work out the number of samples based upon the rect size
  422. double increment = M_PI / number_samples;
  423. auto ellipse_x = [&](double theta) -> int {
  424. return (AK::cos(theta) * rect.width() / AK::sqrt(2.)) + rect.center().x();
  425. };
  426. auto ellipse_y = [&](double theta) -> int {
  427. return (AK::sin(theta) * rect.height() / AK::sqrt(2.)) + rect.center().y();
  428. };
  429. for (auto theta = 0.0; theta < 2 * M_PI; theta += increment) {
  430. draw_line({ ellipse_x(theta), ellipse_y(theta) }, { ellipse_x(theta + increment), ellipse_y(theta + increment) }, color, thickness);
  431. }
  432. }
  433. template<typename RectType, typename Callback>
  434. static void for_each_pixel_around_rect_clockwise(RectType const& rect, Callback callback)
  435. {
  436. if (rect.is_empty())
  437. return;
  438. for (auto x = rect.left(); x <= rect.right(); ++x) {
  439. callback(x, rect.top());
  440. }
  441. for (auto y = rect.top() + 1; y <= rect.bottom(); ++y) {
  442. callback(rect.right(), y);
  443. }
  444. for (auto x = rect.right() - 1; x >= rect.left(); --x) {
  445. callback(x, rect.bottom());
  446. }
  447. for (auto y = rect.bottom() - 1; y > rect.top(); --y) {
  448. callback(rect.left(), y);
  449. }
  450. }
  451. void Painter::draw_focus_rect(IntRect const& rect, Color color)
  452. {
  453. VERIFY(scale() == 1); // FIXME: Add scaling support.
  454. if (rect.is_empty())
  455. return;
  456. bool state = false;
  457. for_each_pixel_around_rect_clockwise(rect, [&](auto x, auto y) {
  458. if (state)
  459. set_pixel(x, y, color);
  460. state = !state;
  461. });
  462. }
  463. void Painter::draw_rect(IntRect const& a_rect, Color color, bool rough)
  464. {
  465. IntRect rect = a_rect.translated(translation());
  466. auto clipped_rect = rect.intersected(clip_rect());
  467. if (clipped_rect.is_empty())
  468. return;
  469. int min_y = clipped_rect.top();
  470. int max_y = clipped_rect.bottom();
  471. int scale = this->scale();
  472. if (rect.top() >= clipped_rect.top() && rect.top() <= clipped_rect.bottom()) {
  473. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  474. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  475. for (int i = 0; i < scale; ++i)
  476. fill_physical_scanline_with_draw_op(rect.top() * scale + i, start_x * scale, width * scale, color);
  477. ++min_y;
  478. }
  479. if (rect.bottom() >= clipped_rect.top() && rect.bottom() <= clipped_rect.bottom()) {
  480. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  481. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  482. for (int i = 0; i < scale; ++i)
  483. fill_physical_scanline_with_draw_op(max_y * scale + i, start_x * scale, width * scale, color);
  484. --max_y;
  485. }
  486. bool draw_left_side = rect.left() >= clipped_rect.left();
  487. bool draw_right_side = rect.right() == clipped_rect.right();
  488. if (draw_left_side && draw_right_side) {
  489. // Specialized loop when drawing both sides.
  490. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  491. auto* bits = m_target->scanline(y);
  492. for (int i = 0; i < scale; ++i)
  493. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  494. for (int i = 0; i < scale; ++i)
  495. set_physical_pixel_with_draw_op(bits[rect.right() * scale + i], color);
  496. }
  497. } else {
  498. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  499. auto* bits = m_target->scanline(y);
  500. if (draw_left_side)
  501. for (int i = 0; i < scale; ++i)
  502. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  503. if (draw_right_side)
  504. for (int i = 0; i < scale; ++i)
  505. set_physical_pixel_with_draw_op(bits[rect.right() * scale + i], color);
  506. }
  507. }
  508. }
  509. void Painter::draw_rect_with_thickness(IntRect const& rect, Color color, int thickness)
  510. {
  511. if (thickness <= 0)
  512. return;
  513. IntPoint p1 = rect.location();
  514. IntPoint p2 = { rect.location().x() + rect.width(), rect.location().y() };
  515. IntPoint p3 = { rect.location().x() + rect.width(), rect.location().y() + rect.height() };
  516. IntPoint p4 = { rect.location().x(), rect.location().y() + rect.height() };
  517. draw_line(p1, p2, color, thickness);
  518. draw_line(p2, p3, color, thickness);
  519. draw_line(p3, p4, color, thickness);
  520. draw_line(p4, p1, color, thickness);
  521. }
  522. void Painter::draw_bitmap(IntPoint const& p, CharacterBitmap const& bitmap, Color color)
  523. {
  524. VERIFY(scale() == 1); // FIXME: Add scaling support.
  525. auto rect = IntRect(p, bitmap.size()).translated(translation());
  526. auto clipped_rect = rect.intersected(clip_rect());
  527. if (clipped_rect.is_empty())
  528. return;
  529. int const first_row = clipped_rect.top() - rect.top();
  530. int const last_row = clipped_rect.bottom() - rect.top();
  531. int const first_column = clipped_rect.left() - rect.left();
  532. int const last_column = clipped_rect.right() - rect.left();
  533. RGBA32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  534. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  535. char const* bitmap_row = &bitmap.bits()[first_row * bitmap.width() + first_column];
  536. size_t const bitmap_skip = bitmap.width();
  537. for (int row = first_row; row <= last_row; ++row) {
  538. for (int j = 0; j <= (last_column - first_column); ++j) {
  539. char fc = bitmap_row[j];
  540. if (fc == '#')
  541. dst[j] = color.value();
  542. }
  543. bitmap_row += bitmap_skip;
  544. dst += dst_skip;
  545. }
  546. }
  547. void Painter::draw_bitmap(IntPoint const& p, GlyphBitmap const& bitmap, Color color)
  548. {
  549. auto dst_rect = IntRect(p, bitmap.size()).translated(translation());
  550. auto clipped_rect = dst_rect.intersected(clip_rect());
  551. if (clipped_rect.is_empty())
  552. return;
  553. int const first_row = clipped_rect.top() - dst_rect.top();
  554. int const last_row = clipped_rect.bottom() - dst_rect.top();
  555. int const first_column = clipped_rect.left() - dst_rect.left();
  556. int const last_column = clipped_rect.right() - dst_rect.left();
  557. int scale = this->scale();
  558. RGBA32* dst = m_target->scanline(clipped_rect.y() * scale) + clipped_rect.x() * scale;
  559. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  560. if (scale == 1) {
  561. for (int row = first_row; row <= last_row; ++row) {
  562. for (int j = 0; j <= (last_column - first_column); ++j) {
  563. if (bitmap.bit_at(j + first_column, row))
  564. dst[j] = Color::from_rgba(dst[j]).blend(color).value();
  565. }
  566. dst += dst_skip;
  567. }
  568. } else {
  569. for (int row = first_row; row <= last_row; ++row) {
  570. for (int j = 0; j <= (last_column - first_column); ++j) {
  571. if (bitmap.bit_at((j + first_column), row)) {
  572. for (int iy = 0; iy < scale; ++iy)
  573. for (int ix = 0; ix < scale; ++ix) {
  574. auto pixel_index = j * scale + ix + iy * dst_skip;
  575. dst[pixel_index] = Color::from_rgba(dst[pixel_index]).blend(color).value();
  576. }
  577. }
  578. }
  579. dst += dst_skip * scale;
  580. }
  581. }
  582. }
  583. void Painter::draw_triangle(IntPoint const& a, IntPoint const& b, IntPoint const& c, Color color)
  584. {
  585. IntPoint p0(to_physical(a));
  586. IntPoint p1(to_physical(b));
  587. IntPoint p2(to_physical(c));
  588. // sort points from top to bottom
  589. if (p0.y() > p1.y())
  590. swap(p0, p1);
  591. if (p0.y() > p2.y())
  592. swap(p0, p2);
  593. if (p1.y() > p2.y())
  594. swap(p1, p2);
  595. // return if top and bottom points are on same line
  596. if (p0.y() == p2.y())
  597. return;
  598. // return if top is below clip rect or bottom is above clip rect
  599. auto clip = clip_rect();
  600. if (p0.y() >= clip.bottom())
  601. return;
  602. if (p2.y() < clip.top())
  603. return;
  604. int rgba = color.value();
  605. float dx02 = (float)(p2.x() - p0.x()) / (p2.y() - p0.y());
  606. float x01 = p0.x();
  607. float x02 = p0.x();
  608. if (p0.y() != p1.y()) { // p0 and p1 are on different lines
  609. float dx01 = (float)(p1.x() - p0.x()) / (p1.y() - p0.y());
  610. int top = p0.y();
  611. if (top < clip.top()) {
  612. x01 += dx01 * (clip.top() - top);
  613. x02 += dx02 * (clip.top() - top);
  614. top = clip.top();
  615. }
  616. for (int y = top; y < p1.y() && y < clip.bottom(); ++y) { // XXX <=?
  617. int start = x01 > x02 ? max((int)x02, clip.left()) : max((int)x01, clip.left());
  618. int end = x01 > x02 ? min((int)x01, clip.right()) : min((int)x02, clip.right());
  619. auto* scanline = m_target->scanline(y);
  620. for (int x = start; x < end; x++) {
  621. scanline[x] = rgba;
  622. }
  623. x01 += dx01;
  624. x02 += dx02;
  625. }
  626. }
  627. // return if middle point and bottom point are on same line
  628. if (p1.y() == p2.y())
  629. return;
  630. float x12 = p1.x();
  631. float dx12 = (float)(p2.x() - p1.x()) / (p2.y() - p1.y());
  632. int top = p1.y();
  633. if (top < clip.top()) {
  634. x02 += dx02 * (clip.top() - top);
  635. x12 += dx12 * (clip.top() - top);
  636. top = clip.top();
  637. }
  638. for (int y = top; y < p2.y() && y < clip.bottom(); ++y) { // XXX <=?
  639. int start = x12 > x02 ? max((int)x02, clip.left()) : max((int)x12, clip.left());
  640. int end = x12 > x02 ? min((int)x12, clip.right()) : min((int)x02, clip.right());
  641. auto* scanline = m_target->scanline(y);
  642. for (int x = start; x < end; x++) {
  643. scanline[x] = rgba;
  644. }
  645. x02 += dx02;
  646. x12 += dx12;
  647. }
  648. }
  649. struct BlitState {
  650. enum AlphaState {
  651. NoAlpha = 0,
  652. SrcAlpha = 1,
  653. DstAlpha = 2,
  654. BothAlpha = SrcAlpha | DstAlpha
  655. };
  656. RGBA32 const* src;
  657. RGBA32* dst;
  658. size_t src_pitch;
  659. size_t dst_pitch;
  660. int row_count;
  661. int column_count;
  662. float opacity;
  663. };
  664. template<BlitState::AlphaState has_alpha>
  665. static void do_blit_with_opacity(BlitState& state)
  666. {
  667. for (int row = 0; row < state.row_count; ++row) {
  668. for (int x = 0; x < state.column_count; ++x) {
  669. Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_rgba(state.dst[x]) : Color::from_rgb(state.dst[x]);
  670. if constexpr (has_alpha & BlitState::SrcAlpha) {
  671. Color src_color_with_alpha = Color::from_rgba(state.src[x]);
  672. float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
  673. src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
  674. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  675. } else {
  676. Color src_color_with_alpha = Color::from_rgb(state.src[x]);
  677. src_color_with_alpha.set_alpha(state.opacity * 255);
  678. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  679. }
  680. }
  681. state.dst += state.dst_pitch;
  682. state.src += state.src_pitch;
  683. }
  684. }
  685. void Painter::blit_with_opacity(IntPoint const& position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  686. {
  687. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  688. if (opacity >= 1.0f && !(source.has_alpha_channel() && apply_alpha))
  689. return blit(position, source, a_src_rect);
  690. IntRect safe_src_rect = IntRect::intersection(a_src_rect, source.rect());
  691. if (scale() != source.scale())
  692. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  693. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  694. auto clipped_rect = dst_rect.intersected(clip_rect());
  695. if (clipped_rect.is_empty())
  696. return;
  697. int scale = this->scale();
  698. auto src_rect = a_src_rect * scale;
  699. clipped_rect *= scale;
  700. dst_rect *= scale;
  701. int const first_row = clipped_rect.top() - dst_rect.top();
  702. int const last_row = clipped_rect.bottom() - dst_rect.top();
  703. int const first_column = clipped_rect.left() - dst_rect.left();
  704. int const last_column = clipped_rect.right() - dst_rect.left();
  705. BlitState blit_state {
  706. .src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column,
  707. .dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x(),
  708. .src_pitch = source.pitch() / sizeof(RGBA32),
  709. .dst_pitch = m_target->pitch() / sizeof(RGBA32),
  710. .row_count = last_row - first_row + 1,
  711. .column_count = last_column - first_column + 1,
  712. .opacity = opacity
  713. };
  714. if (source.has_alpha_channel() && apply_alpha) {
  715. if (m_target->has_alpha_channel())
  716. do_blit_with_opacity<BlitState::BothAlpha>(blit_state);
  717. else
  718. do_blit_with_opacity<BlitState::SrcAlpha>(blit_state);
  719. } else {
  720. if (m_target->has_alpha_channel())
  721. do_blit_with_opacity<BlitState::DstAlpha>(blit_state);
  722. else
  723. do_blit_with_opacity<BlitState::NoAlpha>(blit_state);
  724. }
  725. }
  726. void Painter::blit_filtered(IntPoint const& position, Gfx::Bitmap const& source, IntRect const& src_rect, Function<Color(Color)> filter)
  727. {
  728. VERIFY((source.scale() == 1 || source.scale() == scale()) && "blit_filtered only supports integer upsampling");
  729. IntRect safe_src_rect = src_rect.intersected(source.rect());
  730. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  731. auto clipped_rect = dst_rect.intersected(clip_rect());
  732. if (clipped_rect.is_empty())
  733. return;
  734. int scale = this->scale();
  735. clipped_rect *= scale;
  736. dst_rect *= scale;
  737. safe_src_rect *= source.scale();
  738. int const first_row = clipped_rect.top() - dst_rect.top();
  739. int const last_row = clipped_rect.bottom() - dst_rect.top();
  740. int const first_column = clipped_rect.left() - dst_rect.left();
  741. int const last_column = clipped_rect.right() - dst_rect.left();
  742. RGBA32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  743. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  744. int s = scale / source.scale();
  745. if (s == 1) {
  746. RGBA32 const* src = source.scanline(safe_src_rect.top() + first_row) + safe_src_rect.left() + first_column;
  747. size_t const src_skip = source.pitch() / sizeof(RGBA32);
  748. for (int row = first_row; row <= last_row; ++row) {
  749. for (int x = 0; x <= (last_column - first_column); ++x) {
  750. u8 alpha = Color::from_rgba(src[x]).alpha();
  751. if (alpha == 0xff) {
  752. auto color = filter(Color::from_rgba(src[x]));
  753. if (color.alpha() == 0xff)
  754. dst[x] = color.value();
  755. else
  756. dst[x] = Color::from_rgba(dst[x]).blend(color).value();
  757. } else if (!alpha)
  758. continue;
  759. else
  760. dst[x] = Color::from_rgba(dst[x]).blend(filter(Color::from_rgba(src[x]))).value();
  761. }
  762. dst += dst_skip;
  763. src += src_skip;
  764. }
  765. } else {
  766. for (int row = first_row; row <= last_row; ++row) {
  767. RGBA32 const* src = source.scanline(safe_src_rect.top() + row / s) + safe_src_rect.left() + first_column / s;
  768. for (int x = 0; x <= (last_column - first_column); ++x) {
  769. u8 alpha = Color::from_rgba(src[x / s]).alpha();
  770. if (alpha == 0xff) {
  771. auto color = filter(Color::from_rgba(src[x / s]));
  772. if (color.alpha() == 0xff)
  773. dst[x] = color.value();
  774. else
  775. dst[x] = Color::from_rgba(dst[x]).blend(color).value();
  776. } else if (!alpha)
  777. continue;
  778. else
  779. dst[x] = Color::from_rgba(dst[x]).blend(filter(Color::from_rgba(src[x / s]))).value();
  780. }
  781. dst += dst_skip;
  782. }
  783. }
  784. }
  785. void Painter::blit_brightened(IntPoint const& position, Gfx::Bitmap const& source, IntRect const& src_rect)
  786. {
  787. return blit_filtered(position, source, src_rect, [](Color src) {
  788. return src.lightened();
  789. });
  790. }
  791. void Painter::blit_dimmed(IntPoint const& position, Gfx::Bitmap const& source, IntRect const& src_rect)
  792. {
  793. return blit_filtered(position, source, src_rect, [](Color src) {
  794. return src.to_grayscale().lightened();
  795. });
  796. }
  797. void Painter::draw_tiled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source)
  798. {
  799. VERIFY((source.scale() == 1 || source.scale() == scale()) && "draw_tiled_bitmap only supports integer upsampling");
  800. auto dst_rect = a_dst_rect.translated(translation());
  801. auto clipped_rect = dst_rect.intersected(clip_rect());
  802. if (clipped_rect.is_empty())
  803. return;
  804. int scale = this->scale();
  805. clipped_rect *= scale;
  806. dst_rect *= scale;
  807. int const first_row = (clipped_rect.top() - dst_rect.top());
  808. int const last_row = (clipped_rect.bottom() - dst_rect.top());
  809. int const first_column = (clipped_rect.left() - dst_rect.left());
  810. RGBA32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  811. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  812. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  813. int s = scale / source.scale();
  814. if (s == 1) {
  815. int x_start = first_column + a_dst_rect.left() * scale;
  816. for (int row = first_row; row <= last_row; ++row) {
  817. RGBA32 const* sl = source.scanline((row + a_dst_rect.top() * scale) % source.physical_height());
  818. for (int x = x_start; x < clipped_rect.width() + x_start; ++x) {
  819. dst[x - x_start] = sl[x % source.physical_width()];
  820. }
  821. dst += dst_skip;
  822. }
  823. } else {
  824. int x_start = first_column + a_dst_rect.left() * scale;
  825. for (int row = first_row; row <= last_row; ++row) {
  826. RGBA32 const* sl = source.scanline(((row + a_dst_rect.top() * scale) / s) % source.physical_height());
  827. for (int x = x_start; x < clipped_rect.width() + x_start; ++x) {
  828. dst[x - x_start] = sl[(x / s) % source.physical_width()];
  829. }
  830. dst += dst_skip;
  831. }
  832. }
  833. return;
  834. }
  835. VERIFY_NOT_REACHED();
  836. }
  837. void Painter::blit_offset(IntPoint const& a_position, Gfx::Bitmap const& source, IntRect const& a_src_rect, IntPoint const& offset)
  838. {
  839. auto src_rect = IntRect { a_src_rect.location() - offset, a_src_rect.size() };
  840. auto position = a_position;
  841. if (src_rect.x() < 0) {
  842. position.set_x(position.x() - src_rect.x());
  843. src_rect.set_x(0);
  844. }
  845. if (src_rect.y() < 0) {
  846. position.set_y(position.y() - src_rect.y());
  847. src_rect.set_y(0);
  848. }
  849. blit(position, source, src_rect);
  850. }
  851. void Painter::blit(IntPoint const& position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  852. {
  853. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  854. if (opacity < 1.0f || (source.has_alpha_channel() && apply_alpha))
  855. return blit_with_opacity(position, source, a_src_rect, opacity, apply_alpha);
  856. auto safe_src_rect = a_src_rect.intersected(source.rect());
  857. if (scale() != source.scale())
  858. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  859. // If we get here, the Painter might have a scale factor, but the source bitmap has the same scale factor.
  860. // We need to transform from logical to physical coordinates, but we can just copy pixels without resampling.
  861. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  862. auto clipped_rect = dst_rect.intersected(clip_rect());
  863. if (clipped_rect.is_empty())
  864. return;
  865. // All computations below are in physical coordinates.
  866. int scale = this->scale();
  867. auto src_rect = a_src_rect * scale;
  868. clipped_rect *= scale;
  869. dst_rect *= scale;
  870. int const first_row = clipped_rect.top() - dst_rect.top();
  871. int const last_row = clipped_rect.bottom() - dst_rect.top();
  872. int const first_column = clipped_rect.left() - dst_rect.left();
  873. RGBA32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  874. size_t const dst_skip = m_target->pitch() / sizeof(RGBA32);
  875. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  876. RGBA32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  877. size_t const src_skip = source.pitch() / sizeof(RGBA32);
  878. for (int row = first_row; row <= last_row; ++row) {
  879. fast_u32_copy(dst, src, clipped_rect.width());
  880. dst += dst_skip;
  881. src += src_skip;
  882. }
  883. return;
  884. }
  885. if (source.format() == BitmapFormat::RGBA8888) {
  886. u32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  887. size_t const src_skip = source.pitch() / sizeof(u32);
  888. for (int row = first_row; row <= last_row; ++row) {
  889. for (int i = 0; i < clipped_rect.width(); ++i) {
  890. u32 rgba = src[i];
  891. u32 bgra = (rgba & 0xff00ff00)
  892. | ((rgba & 0x000000ff) << 16)
  893. | ((rgba & 0x00ff0000) >> 16);
  894. dst[i] = bgra;
  895. }
  896. dst += dst_skip;
  897. src += src_skip;
  898. }
  899. return;
  900. }
  901. if (Bitmap::is_indexed(source.format())) {
  902. u8 const* src = source.scanline_u8(src_rect.top() + first_row) + src_rect.left() + first_column;
  903. size_t const src_skip = source.pitch();
  904. for (int row = first_row; row <= last_row; ++row) {
  905. for (int i = 0; i < clipped_rect.width(); ++i)
  906. dst[i] = source.palette_color(src[i]).value();
  907. dst += dst_skip;
  908. src += src_skip;
  909. }
  910. return;
  911. }
  912. VERIFY_NOT_REACHED();
  913. }
  914. template<bool has_alpha_channel, typename GetPixel>
  915. 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)
  916. {
  917. bool has_opacity = opacity != 1.0f;
  918. for (int y = 0; y < src_rect.height(); ++y) {
  919. int dst_y = dst_rect.y() + y * vfactor;
  920. for (int x = 0; x < src_rect.width(); ++x) {
  921. auto src_pixel = get_pixel(source, x + src_rect.left(), y + src_rect.top());
  922. if (has_opacity)
  923. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  924. for (int yo = 0; yo < vfactor; ++yo) {
  925. auto* scanline = (Color*)target.scanline(dst_y + yo);
  926. int dst_x = dst_rect.x() + x * hfactor;
  927. for (int xo = 0; xo < hfactor; ++xo) {
  928. if constexpr (has_alpha_channel)
  929. scanline[dst_x + xo] = scanline[dst_x + xo].blend(src_pixel);
  930. else
  931. scanline[dst_x + xo] = src_pixel;
  932. }
  933. }
  934. }
  935. }
  936. }
  937. template<bool has_alpha_channel, bool do_bilinear_blend, typename GetPixel>
  938. 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)
  939. {
  940. if constexpr (!do_bilinear_blend) {
  941. IntRect int_src_rect = enclosing_int_rect(src_rect);
  942. if (dst_rect == clipped_rect && int_src_rect == src_rect && !(dst_rect.width() % int_src_rect.width()) && !(dst_rect.height() % int_src_rect.height())) {
  943. int hfactor = dst_rect.width() / int_src_rect.width();
  944. int vfactor = dst_rect.height() / int_src_rect.height();
  945. if (hfactor == 2 && vfactor == 2)
  946. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 2, 2, get_pixel, opacity);
  947. if (hfactor == 3 && vfactor == 3)
  948. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 3, 3, get_pixel, opacity);
  949. if (hfactor == 4 && vfactor == 4)
  950. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 4, 4, get_pixel, opacity);
  951. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  952. }
  953. }
  954. bool has_opacity = opacity != 1.0f;
  955. i64 shift = (i64)1 << 32;
  956. i64 fractional_mask = (shift - (u64)1);
  957. i64 half_pixel = (i64)1 << 31;
  958. i64 hscale = (src_rect.width() * shift) / dst_rect.width();
  959. i64 vscale = (src_rect.height() * shift) / dst_rect.height();
  960. i64 src_left = src_rect.left() * shift;
  961. i64 src_top = src_rect.top() * shift;
  962. for (int y = clipped_rect.top(); y <= clipped_rect.bottom(); ++y) {
  963. auto* scanline = (Color*)target.scanline(y);
  964. for (int x = clipped_rect.left(); x <= clipped_rect.right(); ++x) {
  965. auto desired_x = ((x - dst_rect.x()) * hscale + src_left);
  966. auto desired_y = ((y - dst_rect.y()) * vscale + src_top);
  967. Color src_pixel;
  968. if constexpr (do_bilinear_blend) {
  969. auto scaled_x0 = clamp((desired_x - half_pixel) >> 32, 0, src_rect.width() - 1);
  970. auto scaled_x1 = clamp((desired_x + half_pixel) >> 32, 0, src_rect.width() - 1);
  971. auto scaled_y0 = clamp((desired_y - half_pixel) >> 32, 0, src_rect.height() - 1);
  972. auto scaled_y1 = clamp((desired_y + half_pixel) >> 32, 0, src_rect.height() - 1);
  973. float x_ratio = (((desired_x + half_pixel) & fractional_mask) / (float)shift);
  974. float y_ratio = (((desired_y + half_pixel) & fractional_mask) / (float)shift);
  975. src_pixel = get_pixel(source, scaled_x0, scaled_y0).interpolate(get_pixel(source, scaled_x1, scaled_y0), x_ratio).interpolate(get_pixel(source, scaled_x0, scaled_y1).interpolate(get_pixel(source, scaled_x1, scaled_y1), x_ratio), y_ratio);
  976. } else {
  977. auto scaled_x = desired_x >> 32;
  978. auto scaled_y = desired_y >> 32;
  979. src_pixel = get_pixel(source, scaled_x, scaled_y);
  980. }
  981. if (has_opacity)
  982. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  983. if constexpr (has_alpha_channel) {
  984. scanline[x] = scanline[x].blend(src_pixel);
  985. } else {
  986. scanline[x] = src_pixel;
  987. }
  988. }
  989. }
  990. }
  991. template<bool has_alpha_channel, typename GetPixel>
  992. 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)
  993. {
  994. switch (scaling_mode) {
  995. case Painter::ScalingMode::NearestNeighbor:
  996. do_draw_scaled_bitmap<has_alpha_channel, false>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  997. break;
  998. case Painter::ScalingMode::BilinearBlend:
  999. do_draw_scaled_bitmap<has_alpha_channel, true>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1000. break;
  1001. }
  1002. }
  1003. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1004. {
  1005. draw_scaled_bitmap(a_dst_rect, source, FloatRect { a_src_rect }, opacity, scaling_mode);
  1006. }
  1007. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, FloatRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1008. {
  1009. IntRect int_src_rect = enclosing_int_rect(a_src_rect);
  1010. if (scale() == source.scale() && a_src_rect == int_src_rect && a_dst_rect.size() == int_src_rect.size())
  1011. return blit(a_dst_rect.location(), source, int_src_rect, opacity);
  1012. auto dst_rect = to_physical(a_dst_rect);
  1013. auto src_rect = a_src_rect * source.scale();
  1014. auto clipped_rect = dst_rect.intersected(clip_rect() * scale());
  1015. if (clipped_rect.is_empty())
  1016. return;
  1017. if (source.has_alpha_channel() || opacity != 1.0f) {
  1018. switch (source.format()) {
  1019. case BitmapFormat::BGRx8888:
  1020. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1021. break;
  1022. case BitmapFormat::BGRA8888:
  1023. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::BGRA8888>, opacity, scaling_mode);
  1024. break;
  1025. case BitmapFormat::Indexed8:
  1026. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1027. break;
  1028. case BitmapFormat::Indexed4:
  1029. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Indexed4>, opacity, scaling_mode);
  1030. break;
  1031. case BitmapFormat::Indexed2:
  1032. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Indexed2>, opacity, scaling_mode);
  1033. break;
  1034. case BitmapFormat::Indexed1:
  1035. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Indexed1>, opacity, scaling_mode);
  1036. break;
  1037. default:
  1038. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1039. break;
  1040. }
  1041. } else {
  1042. switch (source.format()) {
  1043. case BitmapFormat::BGRx8888:
  1044. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1045. break;
  1046. case BitmapFormat::Indexed8:
  1047. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1048. break;
  1049. default:
  1050. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1051. break;
  1052. }
  1053. }
  1054. }
  1055. FLATTEN void Painter::draw_glyph(IntPoint const& point, u32 code_point, Color color)
  1056. {
  1057. draw_glyph(point, code_point, font(), color);
  1058. }
  1059. FLATTEN void Painter::draw_glyph(IntPoint const& point, u32 code_point, Font const& font, Color color)
  1060. {
  1061. auto glyph = font.glyph(code_point);
  1062. auto top_left = point + IntPoint(glyph.left_bearing(), 0);
  1063. if (glyph.is_glyph_bitmap()) {
  1064. draw_bitmap(top_left, glyph.glyph_bitmap(), color);
  1065. } else {
  1066. blit_filtered(top_left, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1067. return pixel.multiply(color);
  1068. });
  1069. }
  1070. }
  1071. void Painter::draw_emoji(IntPoint const& point, Gfx::Bitmap const& emoji, Font const& font)
  1072. {
  1073. IntRect dst_rect {
  1074. point.x(),
  1075. point.y(),
  1076. font.glyph_height() * emoji.width() / emoji.height(),
  1077. font.glyph_height()
  1078. };
  1079. draw_scaled_bitmap(dst_rect, emoji, emoji.rect());
  1080. }
  1081. void Painter::draw_glyph_or_emoji(IntPoint const& point, u32 code_point, Font const& font, Color color)
  1082. {
  1083. StringBuilder builder;
  1084. builder.append_code_point(code_point);
  1085. auto it = Utf8View { builder.string_view() }.begin();
  1086. return draw_glyph_or_emoji(point, it, font, color);
  1087. }
  1088. void Painter::draw_glyph_or_emoji(IntPoint const& point, Utf8CodePointIterator& it, Font const& font, Color color)
  1089. {
  1090. // FIXME: Handle variation selectors. Additionally, some emojis start with a 'regular' character,
  1091. // so the 'font contains' check isn't sufficient for all of them - we'll have to peek.
  1092. u32 code_point = *it;
  1093. if (font.contains_glyph(code_point)) {
  1094. draw_glyph(point, code_point, font, color);
  1095. return;
  1096. }
  1097. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it)) {
  1098. draw_emoji(point, *emoji, font);
  1099. return;
  1100. }
  1101. dbgln_if(EMOJI_DEBUG, "Failed to find a glyph or emoji for code_point {}", code_point);
  1102. draw_glyph(point, 0xFFFD, font, color);
  1103. }
  1104. template<typename DrawGlyphFunction>
  1105. void draw_text_line(IntRect const& a_rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextDirection direction, DrawGlyphFunction draw_glyph)
  1106. {
  1107. auto rect = a_rect;
  1108. switch (alignment) {
  1109. case TextAlignment::TopLeft:
  1110. case TextAlignment::CenterLeft:
  1111. case TextAlignment::BottomLeft:
  1112. break;
  1113. case TextAlignment::TopRight:
  1114. case TextAlignment::CenterRight:
  1115. case TextAlignment::BottomRight:
  1116. rect.set_x(rect.right() - font.width(text));
  1117. break;
  1118. case TextAlignment::Center: {
  1119. auto shrunken_rect = rect;
  1120. shrunken_rect.set_width(font.width(text));
  1121. shrunken_rect.center_within(rect);
  1122. rect = shrunken_rect;
  1123. break;
  1124. }
  1125. default:
  1126. VERIFY_NOT_REACHED();
  1127. }
  1128. if (is_vertically_centered_text_alignment(alignment)) {
  1129. int distance_from_baseline_to_bottom = (font.glyph_height() - 1) - font.baseline();
  1130. rect.translate_by(0, distance_from_baseline_to_bottom / 2);
  1131. }
  1132. auto point = rect.location();
  1133. int space_width = font.glyph_width(' ') + font.glyph_spacing();
  1134. if (direction == TextDirection::RTL) {
  1135. point.translate_by(rect.width(), 0); // Start drawing from the end
  1136. space_width = -space_width; // Draw spaces backwards
  1137. }
  1138. for (auto it = text.begin(); it != text.end(); ++it) {
  1139. auto code_point = *it;
  1140. if (code_point == ' ') {
  1141. point.translate_by(space_width, 0);
  1142. continue;
  1143. }
  1144. IntSize glyph_size(font.glyph_or_emoji_width(code_point) + font.glyph_spacing(), font.glyph_height());
  1145. if (direction == TextDirection::RTL)
  1146. point.translate_by(-glyph_size.width(), 0); // If we are drawing right to left, we have to move backwards before drawing the glyph
  1147. draw_glyph({ point, glyph_size }, it);
  1148. if (direction == TextDirection::LTR)
  1149. point.translate_by(glyph_size.width(), 0);
  1150. // The callback function might have exhausted the iterator.
  1151. if (it == text.end())
  1152. break;
  1153. }
  1154. }
  1155. static inline size_t draw_text_get_length(Utf8View const& text)
  1156. {
  1157. return text.byte_length();
  1158. }
  1159. Vector<DirectionalRun> Painter::split_text_into_directional_runs(Utf8View const& text, TextDirection initial_direction)
  1160. {
  1161. // FIXME: This is a *very* simplified version of the UNICODE BIDIRECTIONAL ALGORITHM (https://www.unicode.org/reports/tr9/), that can render most bidirectional text
  1162. // 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.
  1163. // FIXME: Support HTML "dir" attribute (how?)
  1164. u8 paragraph_embedding_level = initial_direction == TextDirection::LTR ? 0 : 1;
  1165. Vector<u8> embedding_levels;
  1166. embedding_levels.ensure_capacity(text.length());
  1167. for (size_t i = 0; i < text.length(); i++)
  1168. embedding_levels.unchecked_append(paragraph_embedding_level);
  1169. // FIXME: Support Explicit Directional Formatting Characters
  1170. Vector<BidirectionalClass> character_classes;
  1171. character_classes.ensure_capacity(text.length());
  1172. for (u32 code_point : text)
  1173. character_classes.unchecked_append(get_char_bidi_class(code_point));
  1174. // resolving weak types
  1175. BidirectionalClass paragraph_class = initial_direction == TextDirection::LTR ? BidirectionalClass::STRONG_LTR : BidirectionalClass::STRONG_RTL;
  1176. for (size_t i = 0; i < character_classes.size(); i++) {
  1177. if (character_classes[i] != BidirectionalClass::WEAK_SEPARATORS)
  1178. continue;
  1179. for (ssize_t j = i - 1; j >= 0; j--) {
  1180. auto character_class = character_classes[j];
  1181. if (character_class != BidirectionalClass::STRONG_RTL && character_class != BidirectionalClass::STRONG_LTR)
  1182. continue;
  1183. character_classes[i] = character_class;
  1184. break;
  1185. }
  1186. if (character_classes[i] == BidirectionalClass::WEAK_SEPARATORS)
  1187. character_classes[i] = paragraph_class;
  1188. }
  1189. // resolving neutral types
  1190. auto left_side = BidirectionalClass::NEUTRAL;
  1191. auto sequence_length = 0;
  1192. for (size_t i = 0; i < character_classes.size(); i++) {
  1193. auto character_class = character_classes[i];
  1194. if (left_side == BidirectionalClass::NEUTRAL) {
  1195. if (character_class != BidirectionalClass::NEUTRAL)
  1196. left_side = character_class;
  1197. else
  1198. character_classes[i] = paragraph_class;
  1199. continue;
  1200. }
  1201. if (character_class != BidirectionalClass::NEUTRAL) {
  1202. BidirectionalClass sequence_class;
  1203. if (bidi_class_to_direction(left_side) == bidi_class_to_direction(character_class)) {
  1204. sequence_class = left_side == BidirectionalClass::STRONG_RTL ? BidirectionalClass::STRONG_RTL : BidirectionalClass::STRONG_LTR;
  1205. } else {
  1206. sequence_class = paragraph_class;
  1207. }
  1208. for (auto j = 0; j < sequence_length; j++) {
  1209. character_classes[i - j - 1] = sequence_class;
  1210. }
  1211. sequence_length = 0;
  1212. left_side = character_class;
  1213. } else {
  1214. sequence_length++;
  1215. }
  1216. }
  1217. for (auto i = 0; i < sequence_length; i++)
  1218. character_classes[character_classes.size() - i - 1] = paragraph_class;
  1219. // resolving implicit levels
  1220. for (size_t i = 0; i < character_classes.size(); i++) {
  1221. auto character_class = character_classes[i];
  1222. if ((embedding_levels[i] % 2) == 0) {
  1223. if (character_class == BidirectionalClass::STRONG_RTL)
  1224. embedding_levels[i] += 1;
  1225. else if (character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1226. embedding_levels[i] += 2;
  1227. } else {
  1228. if (character_class == BidirectionalClass::STRONG_LTR || character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1229. embedding_levels[i] += 1;
  1230. }
  1231. }
  1232. // splitting into runs
  1233. auto run_code_points_start = text.begin();
  1234. auto next_code_points_slice = [&](auto length) {
  1235. Vector<u32> run_code_points;
  1236. run_code_points.ensure_capacity(length);
  1237. for (size_t j = 0; j < length; ++j, ++run_code_points_start)
  1238. run_code_points.unchecked_append(*run_code_points_start);
  1239. return run_code_points;
  1240. };
  1241. Vector<DirectionalRun> runs;
  1242. size_t start = 0;
  1243. u8 level = embedding_levels[0];
  1244. for (size_t i = 1; i < embedding_levels.size(); ++i) {
  1245. if (embedding_levels[i] == level)
  1246. continue;
  1247. auto code_points_slice = next_code_points_slice(i - start);
  1248. runs.append({ move(code_points_slice), level });
  1249. start = i;
  1250. level = embedding_levels[i];
  1251. }
  1252. auto code_points_slice = next_code_points_slice(embedding_levels.size() - start);
  1253. runs.append({ move(code_points_slice), level });
  1254. // reordering resolved levels
  1255. // FIXME: missing special cases for trailing whitespace characters
  1256. u8 minimum_level = 128;
  1257. u8 maximum_level = 0;
  1258. for (auto& run : runs) {
  1259. minimum_level = min(minimum_level, run.embedding_level());
  1260. maximum_level = max(minimum_level, run.embedding_level());
  1261. }
  1262. if ((minimum_level % 2) == 0)
  1263. minimum_level++;
  1264. auto runs_count = runs.size() - 1;
  1265. while (maximum_level <= minimum_level) {
  1266. size_t run_index = 0;
  1267. while (run_index < runs_count) {
  1268. while (run_index < runs_count && runs[run_index].embedding_level() < maximum_level)
  1269. run_index++;
  1270. auto reverse_start = run_index;
  1271. while (run_index <= runs_count && runs[run_index].embedding_level() >= maximum_level)
  1272. run_index++;
  1273. auto reverse_end = run_index - 1;
  1274. while (reverse_start < reverse_end) {
  1275. swap(runs[reverse_start], runs[reverse_end]);
  1276. reverse_start++;
  1277. reverse_end--;
  1278. }
  1279. }
  1280. maximum_level--;
  1281. }
  1282. // mirroring RTL mirror characters
  1283. for (auto& run : runs) {
  1284. if (run.direction() == TextDirection::LTR)
  1285. continue;
  1286. for (auto& code_point : run.code_points()) {
  1287. code_point = get_mirror_char(code_point);
  1288. }
  1289. }
  1290. return runs;
  1291. }
  1292. bool Painter::text_contains_bidirectional_text(Utf8View const& text, TextDirection initial_direction)
  1293. {
  1294. for (u32 code_point : text) {
  1295. auto char_class = get_char_bidi_class(code_point);
  1296. if (char_class == BidirectionalClass::NEUTRAL)
  1297. continue;
  1298. if (bidi_class_to_direction(char_class) != initial_direction)
  1299. return true;
  1300. }
  1301. return false;
  1302. }
  1303. template<typename DrawGlyphFunction>
  1304. void Painter::do_draw_text(IntRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping, DrawGlyphFunction draw_glyph)
  1305. {
  1306. if (draw_text_get_length(text) == 0)
  1307. return;
  1308. TextLayout layout(&font, text, rect);
  1309. static int const line_spacing = 4;
  1310. int line_height = font.glyph_height() + line_spacing;
  1311. auto lines = layout.lines(elision, wrapping, line_spacing);
  1312. auto bounding_rect = layout.bounding_rect(wrapping, line_spacing);
  1313. switch (alignment) {
  1314. case TextAlignment::TopLeft:
  1315. bounding_rect.set_location(rect.location());
  1316. break;
  1317. case TextAlignment::TopRight:
  1318. bounding_rect.set_location({ (rect.right() + 1) - bounding_rect.width(), rect.y() });
  1319. break;
  1320. case TextAlignment::CenterLeft:
  1321. bounding_rect.set_location({ rect.x(), rect.center().y() - (bounding_rect.height() / 2) });
  1322. break;
  1323. case TextAlignment::CenterRight:
  1324. bounding_rect.set_location({ (rect.right() + 1) - bounding_rect.width(), rect.center().y() - (bounding_rect.height() / 2) });
  1325. break;
  1326. case TextAlignment::Center:
  1327. bounding_rect.center_within(rect);
  1328. break;
  1329. case TextAlignment::BottomLeft:
  1330. bounding_rect.set_location({ rect.x(), (rect.bottom() + 1) - bounding_rect.height() });
  1331. break;
  1332. case TextAlignment::BottomRight:
  1333. bounding_rect.set_location({ (rect.right() + 1) - bounding_rect.width(), (rect.bottom() + 1) - bounding_rect.height() });
  1334. break;
  1335. default:
  1336. VERIFY_NOT_REACHED();
  1337. }
  1338. bounding_rect.intersect(rect);
  1339. for (size_t i = 0; i < lines.size(); ++i) {
  1340. auto line = Utf8View { lines[i] };
  1341. IntRect line_rect { bounding_rect.x(), bounding_rect.y() + static_cast<int>(i) * line_height, bounding_rect.width(), line_height };
  1342. line_rect.intersect(rect);
  1343. TextDirection line_direction = get_text_direction(line);
  1344. if (text_contains_bidirectional_text(line, line_direction)) { // Slow Path: The line contains mixed BiDi classes
  1345. auto directional_runs = split_text_into_directional_runs(line, line_direction);
  1346. auto current_dx = line_direction == TextDirection::LTR ? 0 : line_rect.width();
  1347. for (auto& directional_run : directional_runs) {
  1348. auto run_width = font.width(directional_run.text());
  1349. if (line_direction == TextDirection::RTL)
  1350. current_dx -= run_width;
  1351. auto run_rect = line_rect.translated(current_dx, 0);
  1352. run_rect.set_width(run_width);
  1353. // NOTE: DirectionalRun returns Utf32View which isn't
  1354. // compatible with draw_text_line.
  1355. StringBuilder builder;
  1356. builder.append(directional_run.text());
  1357. auto line_text = Utf8View { builder.string_view() };
  1358. draw_text_line(run_rect, line_text, font, alignment, directional_run.direction(), draw_glyph);
  1359. if (line_direction == TextDirection::LTR)
  1360. current_dx += run_width;
  1361. }
  1362. } else {
  1363. draw_text_line(line_rect, line, font, alignment, line_direction, draw_glyph);
  1364. }
  1365. }
  1366. }
  1367. void Painter::draw_text(IntRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1368. {
  1369. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1370. }
  1371. void Painter::draw_text(IntRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1372. {
  1373. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1374. }
  1375. void Painter::draw_text(IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1376. {
  1377. Utf8View text { raw_text };
  1378. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](IntRect const& r, Utf8CodePointIterator& it) {
  1379. draw_glyph_or_emoji(r.location(), it, font, color);
  1380. });
  1381. }
  1382. void Painter::draw_text(IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1383. {
  1384. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1385. // being some places might depend on it, so we do some internal conversion.
  1386. StringBuilder builder;
  1387. builder.append(raw_text);
  1388. auto text = Utf8View { builder.string_view() };
  1389. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](IntRect const& r, Utf8CodePointIterator& it) {
  1390. draw_glyph_or_emoji(r.location(), it, font, color);
  1391. });
  1392. }
  1393. void Painter::draw_text(Function<void(IntRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1394. {
  1395. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1396. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](IntRect const& r, Utf8CodePointIterator& it) {
  1397. draw_one_glyph(r, it);
  1398. });
  1399. }
  1400. void Painter::draw_text(Function<void(IntRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1401. {
  1402. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1403. Utf8View text { raw_text };
  1404. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](IntRect const& r, Utf8CodePointIterator& it) {
  1405. draw_one_glyph(r, it);
  1406. });
  1407. }
  1408. void Painter::draw_text(Function<void(IntRect const&, Utf8CodePointIterator&)> draw_one_glyph, IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping)
  1409. {
  1410. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1411. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1412. // being some places might depend on it, so we do some internal conversion.
  1413. StringBuilder builder;
  1414. builder.append(raw_text);
  1415. auto text = Utf8View { builder.string_view() };
  1416. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](IntRect const& r, Utf8CodePointIterator& it) {
  1417. draw_one_glyph(r, it);
  1418. });
  1419. }
  1420. void Painter::set_pixel(IntPoint const& p, Color color)
  1421. {
  1422. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1423. auto point = p;
  1424. point.translate_by(state().translation);
  1425. if (!clip_rect().contains(point))
  1426. return;
  1427. m_target->scanline(point.y())[point.x()] = color.value();
  1428. }
  1429. ALWAYS_INLINE void Painter::set_physical_pixel_with_draw_op(u32& pixel, Color const& color)
  1430. {
  1431. // This always sets a single physical pixel, independent of scale().
  1432. // This should only be called by routines that already handle scale.
  1433. switch (draw_op()) {
  1434. case DrawOp::Copy:
  1435. pixel = color.value();
  1436. break;
  1437. case DrawOp::Xor:
  1438. pixel = color.xored(Color::from_rgba(pixel)).value();
  1439. break;
  1440. case DrawOp::Invert:
  1441. pixel = Color::from_rgba(pixel).inverted().value();
  1442. break;
  1443. }
  1444. }
  1445. ALWAYS_INLINE void Painter::fill_physical_scanline_with_draw_op(int y, int x, int width, Color const& color)
  1446. {
  1447. // This always draws a single physical scanline, independent of scale().
  1448. // This should only be called by routines that already handle scale.
  1449. switch (draw_op()) {
  1450. case DrawOp::Copy:
  1451. fast_u32_fill(m_target->scanline(y) + x, color.value(), width);
  1452. break;
  1453. case DrawOp::Xor: {
  1454. auto* pixel = m_target->scanline(y) + x;
  1455. auto* end = pixel + width;
  1456. while (pixel < end) {
  1457. *pixel = Color::from_rgba(*pixel).xored(color).value();
  1458. pixel++;
  1459. }
  1460. break;
  1461. }
  1462. case DrawOp::Invert: {
  1463. auto* pixel = m_target->scanline(y) + x;
  1464. auto* end = pixel + width;
  1465. while (pixel < end) {
  1466. *pixel = Color::from_rgba(*pixel).inverted().value();
  1467. pixel++;
  1468. }
  1469. break;
  1470. }
  1471. }
  1472. }
  1473. void Painter::draw_physical_pixel(IntPoint const& physical_position, Color color, int thickness)
  1474. {
  1475. // This always draws a single physical pixel, independent of scale().
  1476. // This should only be called by routines that already handle scale
  1477. // (including scaling thickness).
  1478. VERIFY(draw_op() == DrawOp::Copy);
  1479. if (thickness <= 0)
  1480. return;
  1481. if (thickness == 1) { // Implies scale() == 1.
  1482. auto& pixel = m_target->scanline(physical_position.y())[physical_position.x()];
  1483. return set_physical_pixel_with_draw_op(pixel, Color::from_rgba(pixel).blend(color));
  1484. }
  1485. IntRect rect { physical_position, { thickness, thickness } };
  1486. rect.intersect(clip_rect() * scale());
  1487. fill_physical_rect(rect, color);
  1488. }
  1489. void Painter::draw_line(IntPoint const& a_p1, IntPoint const& a_p2, Color color, int thickness, LineStyle style, Color alternate_color)
  1490. {
  1491. if (thickness <= 0)
  1492. return;
  1493. if (color.alpha() == 0)
  1494. return;
  1495. auto clip_rect = this->clip_rect() * scale();
  1496. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1497. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1498. auto point1 = to_physical(p1);
  1499. auto point2 = to_physical(p2);
  1500. thickness *= scale();
  1501. auto alternate_color_is_transparent = alternate_color == Color::Transparent;
  1502. // Special case: vertical line.
  1503. if (point1.x() == point2.x()) {
  1504. int const x = point1.x();
  1505. if (x < clip_rect.left() || x > clip_rect.right())
  1506. return;
  1507. if (point1.y() > point2.y())
  1508. swap(point1, point2);
  1509. if (point1.y() > clip_rect.bottom())
  1510. return;
  1511. if (point2.y() < clip_rect.top())
  1512. return;
  1513. int min_y = max(point1.y(), clip_rect.top());
  1514. int max_y = min(point2.y(), clip_rect.bottom());
  1515. if (style == LineStyle::Dotted) {
  1516. for (int y = min_y; y <= max_y; y += thickness * 2)
  1517. draw_physical_pixel({ x, y }, color, thickness);
  1518. } else if (style == LineStyle::Dashed) {
  1519. for (int y = min_y; y <= max_y; y += thickness * 6) {
  1520. draw_physical_pixel({ x, y }, color, thickness);
  1521. draw_physical_pixel({ x, min(y + thickness, max_y) }, color, thickness);
  1522. draw_physical_pixel({ x, min(y + thickness * 2, max_y) }, color, thickness);
  1523. if (!alternate_color_is_transparent) {
  1524. draw_physical_pixel({ x, min(y + thickness * 3, max_y) }, alternate_color, thickness);
  1525. draw_physical_pixel({ x, min(y + thickness * 4, max_y) }, alternate_color, thickness);
  1526. draw_physical_pixel({ x, min(y + thickness * 5, max_y) }, alternate_color, thickness);
  1527. }
  1528. }
  1529. } else {
  1530. for (int y = min_y; y <= max_y; y += thickness)
  1531. draw_physical_pixel({ x, y }, color, thickness);
  1532. draw_physical_pixel({ x, max_y }, color, thickness);
  1533. }
  1534. return;
  1535. }
  1536. // Special case: horizontal line.
  1537. if (point1.y() == point2.y()) {
  1538. int const y = point1.y();
  1539. if (y < clip_rect.top() || y > clip_rect.bottom())
  1540. return;
  1541. if (point1.x() > point2.x())
  1542. swap(point1, point2);
  1543. if (point1.x() > clip_rect.right())
  1544. return;
  1545. if (point2.x() < clip_rect.left())
  1546. return;
  1547. int min_x = max(point1.x(), clip_rect.left());
  1548. int max_x = min(point2.x(), clip_rect.right());
  1549. if (style == LineStyle::Dotted) {
  1550. for (int x = min_x; x <= max_x; x += thickness * 2)
  1551. draw_physical_pixel({ x, y }, color, thickness);
  1552. } else if (style == LineStyle::Dashed) {
  1553. for (int x = min_x; x <= max_x; x += thickness * 6) {
  1554. draw_physical_pixel({ x, y }, color, thickness);
  1555. draw_physical_pixel({ min(x + thickness, max_x), y }, color, thickness);
  1556. draw_physical_pixel({ min(x + thickness * 2, max_x), y }, color, thickness);
  1557. if (!alternate_color_is_transparent) {
  1558. draw_physical_pixel({ min(x + thickness * 3, max_x), y }, alternate_color, thickness);
  1559. draw_physical_pixel({ min(x + thickness * 4, max_x), y }, alternate_color, thickness);
  1560. draw_physical_pixel({ min(x + thickness * 5, max_x), y }, alternate_color, thickness);
  1561. }
  1562. }
  1563. } else {
  1564. for (int x = min_x; x <= max_x; x += thickness)
  1565. draw_physical_pixel({ x, y }, color, thickness);
  1566. draw_physical_pixel({ max_x, y }, color, thickness);
  1567. }
  1568. return;
  1569. }
  1570. // FIXME: Implement dotted/dashed diagonal lines.
  1571. VERIFY(style == LineStyle::Solid);
  1572. int const adx = abs(point2.x() - point1.x());
  1573. int const ady = abs(point2.y() - point1.y());
  1574. if (adx > ady) {
  1575. if (point1.x() > point2.x())
  1576. swap(point1, point2);
  1577. } else {
  1578. if (point1.y() > point2.y())
  1579. swap(point1, point2);
  1580. }
  1581. // FIXME: Implement clipping below.
  1582. int const dx = point2.x() - point1.x();
  1583. int const dy = point2.y() - point1.y();
  1584. int error = 0;
  1585. if (dx > dy) {
  1586. int const y_step = dy == 0 ? 0 : (dy > 0 ? 1 : -1);
  1587. int const delta_error = 2 * abs(dy);
  1588. int y = point1.y();
  1589. for (int x = point1.x(); x <= point2.x(); ++x) {
  1590. if (clip_rect.contains(x, y))
  1591. draw_physical_pixel({ x, y }, color, thickness);
  1592. error += delta_error;
  1593. if (error >= dx) {
  1594. y += y_step;
  1595. error -= 2 * dx;
  1596. }
  1597. }
  1598. } else {
  1599. int const x_step = dx == 0 ? 0 : (dx > 0 ? 1 : -1);
  1600. int const delta_error = 2 * abs(dx);
  1601. int x = point1.x();
  1602. for (int y = point1.y(); y <= point2.y(); ++y) {
  1603. if (clip_rect.contains(x, y))
  1604. draw_physical_pixel({ x, y }, color, thickness);
  1605. error += delta_error;
  1606. if (error >= dy) {
  1607. x += x_step;
  1608. error -= 2 * dy;
  1609. }
  1610. }
  1611. }
  1612. }
  1613. void Painter::draw_triangle_wave(IntPoint const& a_p1, IntPoint const& a_p2, Color color, int amplitude, int thickness)
  1614. {
  1615. // FIXME: Support more than horizontal waves
  1616. VERIFY(a_p1.y() == a_p2.y());
  1617. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1618. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1619. auto point1 = to_physical(p1);
  1620. auto point2 = to_physical(p2);
  1621. auto y = point1.y();
  1622. for (int x = 0; x <= point2.x() - point1.x(); ++x) {
  1623. auto y_offset = abs(x % (2 * amplitude) - amplitude) - amplitude;
  1624. draw_physical_pixel({ point1.x() + x, y + y_offset }, color, thickness);
  1625. }
  1626. }
  1627. static bool can_approximate_bezier_curve(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& control)
  1628. {
  1629. constexpr static int tolerance = 15;
  1630. auto p1x = 3 * control.x() - 2 * p1.x() - p2.x();
  1631. auto p1y = 3 * control.y() - 2 * p1.y() - p2.y();
  1632. auto p2x = 3 * control.x() - 2 * p2.x() - p1.x();
  1633. auto p2y = 3 * control.y() - 2 * p2.y() - p1.y();
  1634. p1x = p1x * p1x;
  1635. p1y = p1y * p1y;
  1636. p2x = p2x * p2x;
  1637. p2y = p2y * p2y;
  1638. return max(p1x, p2x) + max(p1y, p2y) <= tolerance;
  1639. }
  1640. // static
  1641. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint const& control_point, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>& callback)
  1642. {
  1643. struct SegmentDescriptor {
  1644. FloatPoint control_point;
  1645. FloatPoint p1;
  1646. FloatPoint p2;
  1647. };
  1648. static constexpr auto split_quadratic_bezier_curve = [](FloatPoint const& original_control, FloatPoint const& p1, FloatPoint const& p2, auto& segments) {
  1649. auto po1_midpoint = original_control + p1;
  1650. po1_midpoint /= 2;
  1651. auto po2_midpoint = original_control + p2;
  1652. po2_midpoint /= 2;
  1653. auto new_segment = po1_midpoint + po2_midpoint;
  1654. new_segment /= 2;
  1655. segments.enqueue({ po1_midpoint, p1, new_segment });
  1656. segments.enqueue({ po2_midpoint, new_segment, p2 });
  1657. };
  1658. Queue<SegmentDescriptor> segments;
  1659. segments.enqueue({ control_point, p1, p2 });
  1660. while (!segments.is_empty()) {
  1661. auto segment = segments.dequeue();
  1662. if (can_approximate_bezier_curve(segment.p1, segment.p2, segment.control_point))
  1663. callback(segment.p1, segment.p2);
  1664. else
  1665. split_quadratic_bezier_curve(segment.control_point, segment.p1, segment.p2, segments);
  1666. }
  1667. }
  1668. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint const& control_point, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&& callback)
  1669. {
  1670. for_each_line_segment_on_bezier_curve(control_point, p1, p2, callback);
  1671. }
  1672. void Painter::draw_quadratic_bezier_curve(IntPoint const& control_point, IntPoint const& p1, IntPoint const& p2, Color color, int thickness, LineStyle style)
  1673. {
  1674. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1675. if (thickness <= 0)
  1676. return;
  1677. for_each_line_segment_on_bezier_curve(FloatPoint(control_point), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  1678. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1679. });
  1680. }
  1681. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>&& callback)
  1682. {
  1683. for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback);
  1684. }
  1685. static bool can_approximate_cubic_bezier_curve(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& control_0, FloatPoint const& control_1)
  1686. {
  1687. constexpr float tolerance = 15; // Arbitrary, seems like 10-30 produces nice results.
  1688. auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x();
  1689. auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y();
  1690. auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x();
  1691. auto by = 3 * control_1.y() - p1.y() - 2 * p2.y();
  1692. ax *= ax;
  1693. ay *= ay;
  1694. bx *= bx;
  1695. by *= by;
  1696. return max(ax, bx) + max(ay, by) <= tolerance;
  1697. }
  1698. // static
  1699. void Painter::for_each_line_segment_on_cubic_bezier_curve(FloatPoint const& control_point_0, FloatPoint const& control_point_1, FloatPoint const& p1, FloatPoint const& p2, Function<void(FloatPoint const&, FloatPoint const&)>& callback)
  1700. {
  1701. struct ControlPair {
  1702. FloatPoint control_point_0;
  1703. FloatPoint control_point_1;
  1704. };
  1705. struct SegmentDescriptor {
  1706. ControlPair control_points;
  1707. FloatPoint p1;
  1708. FloatPoint p2;
  1709. };
  1710. static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint const& p1, FloatPoint const& p2, auto& segments) {
  1711. Array level_1_midpoints {
  1712. (p1 + original_controls.control_point_0) / 2,
  1713. (original_controls.control_point_0 + original_controls.control_point_1) / 2,
  1714. (original_controls.control_point_1 + p2) / 2,
  1715. };
  1716. Array level_2_midpoints {
  1717. (level_1_midpoints[0] + level_1_midpoints[1]) / 2,
  1718. (level_1_midpoints[1] + level_1_midpoints[2]) / 2,
  1719. };
  1720. auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2;
  1721. segments.enqueue({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint });
  1722. segments.enqueue({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 });
  1723. };
  1724. Queue<SegmentDescriptor> segments;
  1725. segments.enqueue({ { control_point_0, control_point_1 }, p1, p2 });
  1726. while (!segments.is_empty()) {
  1727. auto segment = segments.dequeue();
  1728. if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1))
  1729. callback(segment.p1, segment.p2);
  1730. else
  1731. split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments);
  1732. }
  1733. }
  1734. void Painter::draw_cubic_bezier_curve(IntPoint const& control_point_0, IntPoint const& control_point_1, IntPoint const& p1, IntPoint const& p2, Color color, int thickness, Painter::LineStyle style)
  1735. {
  1736. for_each_line_segment_on_cubic_bezier_curve(FloatPoint(control_point_0), FloatPoint(control_point_1), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  1737. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1738. });
  1739. }
  1740. // static
  1741. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint const&, FloatPoint const&)>& callback)
  1742. {
  1743. if (radii.x() <= 0 || radii.y() <= 0)
  1744. return;
  1745. auto start = p1;
  1746. auto end = p2;
  1747. if (theta_delta < 0) {
  1748. swap(start, end);
  1749. theta_1 = theta_1 + theta_delta;
  1750. theta_delta = fabsf(theta_delta);
  1751. }
  1752. auto relative_start = start - center;
  1753. auto a = radii.x();
  1754. auto b = radii.y();
  1755. // The segments are at most 1 long
  1756. auto largest_radius = max(a, b);
  1757. double theta_step = atan(1 / (double)largest_radius);
  1758. FloatPoint current_point = relative_start;
  1759. FloatPoint next_point = { 0, 0 };
  1760. auto sin_x_axis = AK::sin(x_axis_rotation);
  1761. auto cos_x_axis = AK::cos(x_axis_rotation);
  1762. auto rotate_point = [sin_x_axis, cos_x_axis](FloatPoint& p) {
  1763. auto original_x = p.x();
  1764. auto original_y = p.y();
  1765. p.set_x(original_x * cos_x_axis - original_y * sin_x_axis);
  1766. p.set_y(original_x * sin_x_axis + original_y * cos_x_axis);
  1767. };
  1768. for (double theta = theta_1; theta <= ((double)theta_1 + (double)theta_delta); theta += theta_step) {
  1769. next_point.set_x(a * AK::cos<float>(theta));
  1770. next_point.set_y(b * AK::sin<float>(theta));
  1771. rotate_point(next_point);
  1772. callback(current_point + center, next_point + center);
  1773. current_point = next_point;
  1774. }
  1775. callback(current_point + center, end);
  1776. }
  1777. // static
  1778. void Painter::for_each_line_segment_on_elliptical_arc(FloatPoint const& p1, FloatPoint const& p2, FloatPoint const& center, FloatPoint const radii, float x_axis_rotation, float theta_1, float theta_delta, Function<void(FloatPoint const&, FloatPoint const&)>&& callback)
  1779. {
  1780. for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, callback);
  1781. }
  1782. void Painter::draw_elliptical_arc(IntPoint const& p1, IntPoint const& p2, IntPoint const& center, FloatPoint const& radii, float x_axis_rotation, float theta_1, float theta_delta, Color color, int thickness, LineStyle style)
  1783. {
  1784. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1785. if (thickness <= 0)
  1786. return;
  1787. for_each_line_segment_on_elliptical_arc(FloatPoint(p1), FloatPoint(p2), FloatPoint(center), radii, x_axis_rotation, theta_1, theta_delta, [&](FloatPoint const& fp1, FloatPoint const& fp2) {
  1788. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1789. });
  1790. }
  1791. void Painter::add_clip_rect(IntRect const& rect)
  1792. {
  1793. state().clip_rect.intersect(rect.translated(translation()));
  1794. state().clip_rect.intersect(m_target->rect()); // FIXME: This shouldn't be necessary?
  1795. }
  1796. void Painter::clear_clip_rect()
  1797. {
  1798. state().clip_rect = m_clip_origin;
  1799. }
  1800. PainterStateSaver::PainterStateSaver(Painter& painter)
  1801. : m_painter(painter)
  1802. {
  1803. m_painter.save();
  1804. }
  1805. PainterStateSaver::~PainterStateSaver()
  1806. {
  1807. m_painter.restore();
  1808. }
  1809. void Painter::stroke_path(Path const& path, Color color, int thickness)
  1810. {
  1811. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1812. if (thickness <= 0)
  1813. return;
  1814. FloatPoint cursor;
  1815. for (auto& segment : path.segments()) {
  1816. switch (segment.type()) {
  1817. case Segment::Type::Invalid:
  1818. VERIFY_NOT_REACHED();
  1819. break;
  1820. case Segment::Type::MoveTo:
  1821. cursor = segment.point();
  1822. break;
  1823. case Segment::Type::LineTo:
  1824. draw_line(cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  1825. cursor = segment.point();
  1826. break;
  1827. case Segment::Type::QuadraticBezierCurveTo: {
  1828. auto& through = static_cast<QuadraticBezierCurveSegment const&>(segment).through();
  1829. draw_quadratic_bezier_curve(through.to_type<int>(), cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  1830. cursor = segment.point();
  1831. break;
  1832. }
  1833. case Segment::Type::CubicBezierCurveTo: {
  1834. auto& curve = static_cast<CubicBezierCurveSegment const&>(segment);
  1835. auto& through_0 = curve.through_0();
  1836. auto& through_1 = curve.through_1();
  1837. draw_cubic_bezier_curve(through_0.to_type<int>(), through_1.to_type<int>(), cursor.to_type<int>(), segment.point().to_type<int>(), color, thickness);
  1838. cursor = segment.point();
  1839. break;
  1840. }
  1841. case Segment::Type::EllipticalArcTo:
  1842. auto& arc = static_cast<EllipticalArcSegment const&>(segment);
  1843. draw_elliptical_arc(cursor.to_type<int>(), segment.point().to_type<int>(), arc.center().to_type<int>(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness);
  1844. cursor = segment.point();
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  1850. {
  1851. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1852. Detail::fill_path<Detail::FillPathMode::PlaceOnIntGrid>(*this, path, color, winding_rule);
  1853. }
  1854. void Painter::blit_disabled(IntPoint const& location, Gfx::Bitmap const& bitmap, IntRect const& rect, Palette const& palette)
  1855. {
  1856. auto bright_color = palette.threed_highlight();
  1857. auto dark_color = palette.threed_shadow1();
  1858. blit_filtered(location.translated(1, 1), bitmap, rect, [&](auto) {
  1859. return bright_color;
  1860. });
  1861. blit_filtered(location, bitmap, rect, [&](Color src) {
  1862. int gray = src.to_grayscale().red();
  1863. if (gray > 160)
  1864. return bright_color;
  1865. return dark_color;
  1866. });
  1867. }
  1868. void Painter::blit_tiled(IntRect const& dst_rect, Gfx::Bitmap const& bitmap, IntRect const& rect)
  1869. {
  1870. auto tile_width = rect.width();
  1871. auto tile_height = rect.height();
  1872. auto dst_right = dst_rect.right();
  1873. auto dst_bottom = dst_rect.bottom();
  1874. for (int tile_y = dst_rect.top(); tile_y < dst_bottom; tile_y += tile_height) {
  1875. for (int tile_x = dst_rect.left(); tile_x < dst_right; tile_x += tile_width) {
  1876. IntRect tile_src_rect = rect;
  1877. auto tile_x_overflow = tile_x + tile_width - dst_right;
  1878. if (tile_x_overflow > 0) {
  1879. tile_src_rect.set_width(tile_width - tile_x_overflow);
  1880. }
  1881. auto tile_y_overflow = tile_y + tile_height - dst_bottom;
  1882. if (tile_y_overflow > 0) {
  1883. tile_src_rect.set_height(tile_height - tile_y_overflow);
  1884. }
  1885. blit(IntPoint(tile_x, tile_y), bitmap, tile_src_rect);
  1886. }
  1887. }
  1888. }
  1889. String parse_ampersand_string(StringView raw_text, Optional<size_t>* underline_offset)
  1890. {
  1891. if (raw_text.is_empty())
  1892. return String::empty();
  1893. StringBuilder builder;
  1894. for (size_t i = 0; i < raw_text.length(); ++i) {
  1895. if (raw_text[i] == '&') {
  1896. if (i != (raw_text.length() - 1) && raw_text[i + 1] == '&') {
  1897. builder.append(raw_text[i]);
  1898. ++i;
  1899. } else if (underline_offset && !(*underline_offset).has_value()) {
  1900. *underline_offset = i;
  1901. }
  1902. continue;
  1903. }
  1904. builder.append(raw_text[i]);
  1905. }
  1906. return builder.to_string();
  1907. }
  1908. void Gfx::Painter::draw_ui_text(Gfx::IntRect const& rect, StringView text, Gfx::Font const& font, Gfx::TextAlignment text_alignment, Gfx::Color color)
  1909. {
  1910. Optional<size_t> underline_offset;
  1911. auto name_to_draw = parse_ampersand_string(text, &underline_offset);
  1912. Gfx::IntRect text_rect { 0, 0, font.width(name_to_draw), font.glyph_height() };
  1913. text_rect.align_within(rect, text_alignment);
  1914. draw_text(text_rect, name_to_draw, font, text_alignment, color);
  1915. if (underline_offset.has_value()) {
  1916. Utf8View utf8_view { name_to_draw };
  1917. int width = 0;
  1918. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  1919. if (utf8_view.byte_offset_of(it) >= underline_offset.value()) {
  1920. int y = text_rect.bottom() + 1;
  1921. int x1 = text_rect.left() + width;
  1922. int x2 = x1 + font.glyph_or_emoji_width(*it);
  1923. draw_line({ x1, y }, { x2, y }, color);
  1924. break;
  1925. }
  1926. width += font.glyph_or_emoji_width(*it) + font.glyph_spacing();
  1927. }
  1928. }
  1929. }
  1930. }