Painter.cpp 102 KB

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