Painter.cpp 84 KB

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