Painter.cpp 85 KB

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