Painter.cpp 101 KB

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