Painter.cpp 84 KB

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