Painter.cpp 104 KB

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