Painter.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  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. for (auto y = rect.top() + 1; y < rect.bottom(); ++y)
  481. callback(rect.right() - 1, y);
  482. for (auto x = rect.right() - 2; x >= rect.left(); --x)
  483. callback(x, rect.bottom() - 1);
  484. for (auto y = rect.bottom() - 2; y > rect.top(); --y)
  485. callback(rect.left(), y);
  486. }
  487. void Painter::draw_focus_rect(IntRect const& rect, Color color)
  488. {
  489. VERIFY(scale() == 1); // FIXME: Add scaling support.
  490. if (rect.is_empty())
  491. return;
  492. bool state = false;
  493. for_each_pixel_around_rect_clockwise(rect, [&](auto x, auto y) {
  494. if (state)
  495. set_pixel(x, y, color);
  496. state = !state;
  497. });
  498. }
  499. void Painter::draw_rect(IntRect const& a_rect, Color color, bool rough)
  500. {
  501. IntRect rect = a_rect.translated(translation());
  502. auto clipped_rect = rect.intersected(clip_rect());
  503. if (clipped_rect.is_empty())
  504. return;
  505. int min_y = clipped_rect.top();
  506. int max_y = clipped_rect.bottom() - 1;
  507. int scale = this->scale();
  508. if (rect.top() >= clipped_rect.top() && rect.top() < clipped_rect.bottom()) {
  509. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  510. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  511. for (int i = 0; i < scale; ++i)
  512. fill_physical_scanline_with_draw_op(rect.top() * scale + i, start_x * scale, width * scale, color);
  513. ++min_y;
  514. }
  515. if (rect.bottom() > clipped_rect.top() && rect.bottom() <= clipped_rect.bottom()) {
  516. int start_x = rough ? max(rect.x() + 1, clipped_rect.x()) : clipped_rect.x();
  517. int width = rough ? min(rect.width() - 2, clipped_rect.width()) : clipped_rect.width();
  518. for (int i = 0; i < scale; ++i)
  519. fill_physical_scanline_with_draw_op(max_y * scale + i, start_x * scale, width * scale, color);
  520. --max_y;
  521. }
  522. bool draw_left_side = rect.left() >= clipped_rect.left();
  523. bool draw_right_side = rect.right() == clipped_rect.right();
  524. if (draw_left_side && draw_right_side) {
  525. // Specialized loop when drawing both sides.
  526. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  527. auto* bits = m_target->scanline(y);
  528. for (int i = 0; i < scale; ++i)
  529. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  530. for (int i = 0; i < scale; ++i)
  531. set_physical_pixel_with_draw_op(bits[(rect.right() - 1) * scale + i], color);
  532. }
  533. } else {
  534. for (int y = min_y * scale; y <= max_y * scale; ++y) {
  535. auto* bits = m_target->scanline(y);
  536. if (draw_left_side)
  537. for (int i = 0; i < scale; ++i)
  538. set_physical_pixel_with_draw_op(bits[rect.left() * scale + i], color);
  539. if (draw_right_side)
  540. for (int i = 0; i < scale; ++i)
  541. set_physical_pixel_with_draw_op(bits[(rect.right() - 1) * scale + i], color);
  542. }
  543. }
  544. }
  545. void Painter::draw_rect_with_thickness(IntRect const& rect, Color color, int thickness)
  546. {
  547. if (thickness <= 0)
  548. return;
  549. IntPoint p1 = rect.location();
  550. IntPoint p2 = { rect.location().x() + rect.width(), rect.location().y() };
  551. IntPoint p3 = { rect.location().x() + rect.width(), rect.location().y() + rect.height() };
  552. IntPoint p4 = { rect.location().x(), rect.location().y() + rect.height() };
  553. draw_line(p1, p2, color, thickness);
  554. draw_line(p2, p3, color, thickness);
  555. draw_line(p3, p4, color, thickness);
  556. draw_line(p4, p1, color, thickness);
  557. }
  558. void Painter::draw_bitmap(IntPoint p, CharacterBitmap const& bitmap, Color color)
  559. {
  560. VERIFY(scale() == 1); // FIXME: Add scaling support.
  561. auto rect = IntRect(p, bitmap.size()).translated(translation());
  562. auto clipped_rect = rect.intersected(clip_rect());
  563. if (clipped_rect.is_empty())
  564. return;
  565. int const first_row = clipped_rect.top() - rect.top();
  566. int const last_row = clipped_rect.bottom() - rect.top();
  567. int const first_column = clipped_rect.left() - rect.left();
  568. int const last_column = clipped_rect.right() - rect.left();
  569. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  570. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  571. char const* bitmap_row = &bitmap.bits()[first_row * bitmap.width() + first_column];
  572. size_t const bitmap_skip = bitmap.width();
  573. for (int row = first_row; row < last_row; ++row) {
  574. for (int j = 0; j < (last_column - first_column); ++j) {
  575. char fc = bitmap_row[j];
  576. if (fc == '#')
  577. dst[j] = color.value();
  578. }
  579. bitmap_row += bitmap_skip;
  580. dst += dst_skip;
  581. }
  582. }
  583. void Painter::draw_bitmap(IntPoint p, GlyphBitmap const& bitmap, Color color)
  584. {
  585. auto dst_rect = IntRect(p, bitmap.size()).translated(translation());
  586. auto clipped_rect = dst_rect.intersected(clip_rect());
  587. if (clipped_rect.is_empty())
  588. return;
  589. int const first_row = clipped_rect.top() - dst_rect.top();
  590. int const last_row = clipped_rect.bottom() - dst_rect.top();
  591. int const first_column = clipped_rect.left() - dst_rect.left();
  592. int const last_column = clipped_rect.right() - dst_rect.left();
  593. int scale = this->scale();
  594. ARGB32* dst = m_target->scanline(clipped_rect.y() * scale) + clipped_rect.x() * scale;
  595. auto dst_format = target()->format();
  596. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  597. if (scale == 1) {
  598. for (int row = first_row; row < last_row; ++row) {
  599. for (int j = 0; j < (last_column - first_column); ++j) {
  600. if (bitmap.bit_at(j + first_column, row))
  601. dst[j] = color_for_format(dst_format, dst[j]).blend(color).value();
  602. }
  603. dst += dst_skip;
  604. }
  605. } else {
  606. for (int row = first_row; row < last_row; ++row) {
  607. for (int j = 0; j < (last_column - first_column); ++j) {
  608. if (bitmap.bit_at((j + first_column), row)) {
  609. for (int iy = 0; iy < scale; ++iy)
  610. for (int ix = 0; ix < scale; ++ix) {
  611. auto pixel_index = j * scale + ix + iy * dst_skip;
  612. dst[pixel_index] = color_for_format(dst_format, dst[pixel_index]).blend(color).value();
  613. }
  614. }
  615. }
  616. dst += dst_skip * scale;
  617. }
  618. }
  619. }
  620. void Painter::draw_triangle(IntPoint offset, ReadonlySpan<IntPoint> control_points, Color color)
  621. {
  622. VERIFY(control_points.size() == 3);
  623. draw_triangle(control_points[0] + offset, control_points[1] + offset, control_points[2] + offset, color);
  624. }
  625. void Painter::draw_triangle(IntPoint a, IntPoint b, IntPoint c, Color color)
  626. {
  627. IntPoint p0(to_physical(a));
  628. IntPoint p1(to_physical(b));
  629. IntPoint p2(to_physical(c));
  630. // sort points from top to bottom
  631. if (p0.y() > p1.y())
  632. swap(p0, p1);
  633. if (p0.y() > p2.y())
  634. swap(p0, p2);
  635. if (p1.y() > p2.y())
  636. swap(p1, p2);
  637. // return if top and bottom points are on same line
  638. if (p0.y() == p2.y())
  639. return;
  640. // return if all points are on the same line vertically
  641. if (p0.x() == p1.x() && p1.x() == p2.x())
  642. return;
  643. // return if top is below clip rect or bottom is above clip rect
  644. auto clip = clip_rect();
  645. if (p0.y() >= clip.bottom() - 1)
  646. return;
  647. if (p2.y() < clip.top())
  648. return;
  649. class BoundaryLine {
  650. private:
  651. IntPoint m_base {};
  652. IntPoint m_path {};
  653. public:
  654. BoundaryLine(IntPoint a, IntPoint b)
  655. {
  656. VERIFY(a.y() <= b.y());
  657. m_base = a;
  658. m_path = b - a;
  659. }
  660. int top_y() const { return m_base.y(); }
  661. int bottom_y() const { return m_base.y() + m_path.y(); }
  662. bool is_vertical() const { return m_path.x() == 0; }
  663. bool is_horizontal() const { return m_path.y() == 0; }
  664. bool in_y_range(int y) const { return y >= top_y() && y <= bottom_y(); }
  665. Optional<int> intersection_on_x(int y) const
  666. {
  667. if (!in_y_range(y))
  668. return {};
  669. if (is_horizontal())
  670. return {};
  671. if (is_vertical())
  672. return m_base.x();
  673. int y_diff = y - top_y();
  674. int x_d = m_path.x() * y_diff, y_d = m_path.y();
  675. return (x_d / y_d) + m_base.x();
  676. }
  677. };
  678. BoundaryLine l0(p0, p1), l1(p0, p2), l2(p1, p2);
  679. int rgba = color.value();
  680. for (int y = max(p0.y(), clip.top()); y < min(p2.y() + 1, clip.bottom()); y++) {
  681. Optional<int>
  682. x0 = l0.intersection_on_x(y),
  683. x1 = l1.intersection_on_x(y),
  684. x2 = l2.intersection_on_x(y);
  685. int result_a = 0, result_b = 0;
  686. if (x0.has_value()) {
  687. result_a = x0.value();
  688. if (x1.has_value() && ((!x2.has_value()) || (result_a != x1.value()))) {
  689. result_b = x1.value();
  690. } else {
  691. result_b = x2.value();
  692. }
  693. } else if (x1.has_value()) {
  694. result_a = x1.value();
  695. result_b = x2.value();
  696. }
  697. if (result_a > result_b)
  698. swap(result_a, result_b);
  699. int left_bound = result_a, right_bound = result_b;
  700. ARGB32* scanline = m_target->scanline(y);
  701. for (int x = max(left_bound, clip.left()); x <= min(right_bound, clip.right() - 1); x++)
  702. scanline[x] = rgba;
  703. }
  704. }
  705. struct BlitState {
  706. enum AlphaState {
  707. NoAlpha = 0,
  708. SrcAlpha = 1,
  709. DstAlpha = 2,
  710. BothAlpha = SrcAlpha | DstAlpha
  711. };
  712. ARGB32 const* src;
  713. ARGB32* dst;
  714. size_t src_pitch;
  715. size_t dst_pitch;
  716. int row_count;
  717. int column_count;
  718. float opacity;
  719. BitmapFormat src_format;
  720. };
  721. // FIXME: This is a hack to support blit_with_opacity() with RGBA8888 source.
  722. // Ideally we'd have a more generic solution that allows any source format.
  723. static void swap_red_and_blue_channels(Color& color)
  724. {
  725. u32 rgba = color.value();
  726. u32 bgra = (rgba & 0xff00ff00)
  727. | ((rgba & 0x000000ff) << 16)
  728. | ((rgba & 0x00ff0000) >> 16);
  729. color = Color::from_argb(bgra);
  730. }
  731. // FIXME: This function is very unoptimized.
  732. template<BlitState::AlphaState has_alpha>
  733. static void do_blit_with_opacity(BlitState& state)
  734. {
  735. for (int row = 0; row < state.row_count; ++row) {
  736. for (int x = 0; x < state.column_count; ++x) {
  737. Color dest_color = (has_alpha & BlitState::DstAlpha) ? Color::from_argb(state.dst[x]) : Color::from_rgb(state.dst[x]);
  738. if constexpr (has_alpha & BlitState::SrcAlpha) {
  739. Color src_color_with_alpha = Color::from_argb(state.src[x]);
  740. if (state.src_format == BitmapFormat::RGBA8888)
  741. swap_red_and_blue_channels(src_color_with_alpha);
  742. float pixel_opacity = src_color_with_alpha.alpha() / 255.0;
  743. src_color_with_alpha.set_alpha(255 * (state.opacity * pixel_opacity));
  744. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  745. } else {
  746. Color src_color_with_alpha = Color::from_rgb(state.src[x]);
  747. if (state.src_format == BitmapFormat::RGBA8888)
  748. swap_red_and_blue_channels(src_color_with_alpha);
  749. src_color_with_alpha.set_alpha(state.opacity * 255);
  750. state.dst[x] = dest_color.blend(src_color_with_alpha).value();
  751. }
  752. }
  753. state.dst += state.dst_pitch;
  754. state.src += state.src_pitch;
  755. }
  756. }
  757. void Painter::blit_with_opacity(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  758. {
  759. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  760. if (opacity >= 1.0f && !(source.has_alpha_channel() && apply_alpha))
  761. return blit(position, source, a_src_rect);
  762. IntRect safe_src_rect = IntRect::intersection(a_src_rect, source.rect());
  763. if (scale() != source.scale())
  764. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  765. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  766. auto clipped_rect = dst_rect.intersected(clip_rect());
  767. if (clipped_rect.is_empty())
  768. return;
  769. int scale = this->scale();
  770. auto src_rect = a_src_rect * scale;
  771. clipped_rect *= scale;
  772. dst_rect *= scale;
  773. int const first_row = clipped_rect.top() - dst_rect.top();
  774. int const last_row = clipped_rect.bottom() - dst_rect.top();
  775. int const first_column = clipped_rect.left() - dst_rect.left();
  776. int const last_column = clipped_rect.right() - dst_rect.left();
  777. BlitState blit_state {
  778. .src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column,
  779. .dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x(),
  780. .src_pitch = source.pitch() / sizeof(ARGB32),
  781. .dst_pitch = m_target->pitch() / sizeof(ARGB32),
  782. .row_count = last_row - first_row,
  783. .column_count = last_column - first_column,
  784. .opacity = opacity,
  785. .src_format = source.format(),
  786. };
  787. if (source.has_alpha_channel() && apply_alpha) {
  788. if (m_target->has_alpha_channel())
  789. do_blit_with_opacity<BlitState::BothAlpha>(blit_state);
  790. else
  791. do_blit_with_opacity<BlitState::SrcAlpha>(blit_state);
  792. } else {
  793. if (m_target->has_alpha_channel())
  794. do_blit_with_opacity<BlitState::DstAlpha>(blit_state);
  795. else
  796. do_blit_with_opacity<BlitState::NoAlpha>(blit_state);
  797. }
  798. }
  799. void Painter::blit_filtered(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect, Function<Color(Color)> const& filter)
  800. {
  801. VERIFY((source.scale() == 1 || source.scale() == scale()) && "blit_filtered only supports integer upsampling");
  802. IntRect safe_src_rect = src_rect.intersected(source.rect());
  803. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  804. auto clipped_rect = dst_rect.intersected(clip_rect());
  805. if (clipped_rect.is_empty())
  806. return;
  807. int scale = this->scale();
  808. clipped_rect *= scale;
  809. dst_rect *= scale;
  810. safe_src_rect *= source.scale();
  811. int const first_row = clipped_rect.top() - dst_rect.top();
  812. int const last_row = clipped_rect.bottom() - dst_rect.top();
  813. int const first_column = clipped_rect.left() - dst_rect.left();
  814. int const last_column = clipped_rect.right() - dst_rect.left();
  815. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  816. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  817. auto dst_format = target()->format();
  818. auto src_format = source.format();
  819. int s = scale / source.scale();
  820. if (s == 1) {
  821. ARGB32 const* src = source.scanline(safe_src_rect.top() + first_row) + safe_src_rect.left() + first_column;
  822. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  823. for (int row = first_row; row < last_row; ++row) {
  824. for (int x = 0; x < (last_column - first_column); ++x) {
  825. auto source_color = color_for_format(src_format, src[x]);
  826. if (source_color.alpha() == 0)
  827. continue;
  828. auto filtered_color = filter(source_color);
  829. if (filtered_color.alpha() == 0xff)
  830. dst[x] = filtered_color.value();
  831. else
  832. dst[x] = color_for_format(dst_format, dst[x]).blend(filtered_color).value();
  833. }
  834. dst += dst_skip;
  835. src += src_skip;
  836. }
  837. } else {
  838. for (int row = first_row; row < last_row; ++row) {
  839. ARGB32 const* src = source.scanline(safe_src_rect.top() + row / s) + safe_src_rect.left() + first_column / s;
  840. for (int x = 0; x < (last_column - first_column); ++x) {
  841. auto source_color = color_for_format(src_format, src[x / s]);
  842. if (source_color.alpha() == 0)
  843. continue;
  844. auto filtered_color = filter(source_color);
  845. if (filtered_color.alpha() == 0xff)
  846. dst[x] = filtered_color.value();
  847. else
  848. dst[x] = color_for_format(dst_format, dst[x]).blend(filtered_color).value();
  849. }
  850. dst += dst_skip;
  851. }
  852. }
  853. }
  854. void Painter::blit_brightened(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  855. {
  856. return blit_filtered(position, source, src_rect, [](Color src) {
  857. return src.lightened();
  858. });
  859. }
  860. void Painter::blit_dimmed(IntPoint position, Gfx::Bitmap const& source, IntRect const& src_rect)
  861. {
  862. return blit_filtered(position, source, src_rect, [](Color src) {
  863. return src.to_grayscale().lightened();
  864. });
  865. }
  866. void Painter::draw_tiled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source)
  867. {
  868. VERIFY((source.scale() == 1 || source.scale() == scale()) && "draw_tiled_bitmap only supports integer upsampling");
  869. auto dst_rect = a_dst_rect.translated(translation());
  870. auto clipped_rect = dst_rect.intersected(clip_rect());
  871. if (clipped_rect.is_empty())
  872. return;
  873. int scale = this->scale();
  874. clipped_rect *= scale;
  875. dst_rect *= scale;
  876. int const first_row = clipped_rect.top() - dst_rect.top();
  877. int const last_row = clipped_rect.bottom() - dst_rect.top();
  878. int const first_column = clipped_rect.left() - dst_rect.left();
  879. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  880. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  881. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  882. int s = scale / source.scale();
  883. if (s == 1) {
  884. int x_start = first_column + a_dst_rect.left() * scale;
  885. for (int row = first_row; row < last_row; ++row) {
  886. ARGB32 const* sl = source.scanline((row + a_dst_rect.top() * scale) % source.physical_height());
  887. for (int x = x_start; x < clipped_rect.width() + x_start; ++x)
  888. dst[x - x_start] = sl[x % source.physical_width()];
  889. dst += dst_skip;
  890. }
  891. } else {
  892. int x_start = first_column + a_dst_rect.left() * scale;
  893. for (int row = first_row; row < last_row; ++row) {
  894. ARGB32 const* sl = source.scanline(((row + a_dst_rect.top() * scale) / s) % source.physical_height());
  895. for (int x = x_start; x < clipped_rect.width() + x_start; ++x)
  896. dst[x - x_start] = sl[(x / s) % source.physical_width()];
  897. dst += dst_skip;
  898. }
  899. }
  900. return;
  901. }
  902. VERIFY_NOT_REACHED();
  903. }
  904. void Painter::blit_offset(IntPoint a_position, Gfx::Bitmap const& source, IntRect const& a_src_rect, IntPoint offset)
  905. {
  906. auto src_rect = IntRect { a_src_rect.location() - offset, a_src_rect.size() };
  907. auto position = a_position;
  908. if (src_rect.x() < 0) {
  909. position.set_x(position.x() - src_rect.x());
  910. src_rect.set_x(0);
  911. }
  912. if (src_rect.y() < 0) {
  913. position.set_y(position.y() - src_rect.y());
  914. src_rect.set_y(0);
  915. }
  916. blit(position, source, src_rect);
  917. }
  918. void Painter::blit(IntPoint position, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, bool apply_alpha)
  919. {
  920. VERIFY(scale() >= source.scale() && "painter doesn't support downsampling scale factors");
  921. if (opacity < 1.0f || (source.has_alpha_channel() && apply_alpha))
  922. return blit_with_opacity(position, source, a_src_rect, opacity, apply_alpha);
  923. auto safe_src_rect = a_src_rect.intersected(source.rect());
  924. if (scale() != source.scale())
  925. return draw_scaled_bitmap({ position, safe_src_rect.size() }, source, safe_src_rect, opacity);
  926. // If we get here, the Painter might have a scale factor, but the source bitmap has the same scale factor.
  927. // We need to transform from logical to physical coordinates, but we can just copy pixels without resampling.
  928. auto dst_rect = IntRect(position, safe_src_rect.size()).translated(translation());
  929. auto clipped_rect = dst_rect.intersected(clip_rect());
  930. if (clipped_rect.is_empty())
  931. return;
  932. // All computations below are in physical coordinates.
  933. int scale = this->scale();
  934. auto src_rect = a_src_rect * scale;
  935. clipped_rect *= scale;
  936. dst_rect *= scale;
  937. int const first_row = clipped_rect.top() - dst_rect.top();
  938. int const last_row = clipped_rect.bottom() - dst_rect.top();
  939. int const first_column = clipped_rect.left() - dst_rect.left();
  940. ARGB32* dst = m_target->scanline(clipped_rect.y()) + clipped_rect.x();
  941. size_t const dst_skip = m_target->pitch() / sizeof(ARGB32);
  942. if (source.format() == BitmapFormat::BGRx8888 || source.format() == BitmapFormat::BGRA8888) {
  943. ARGB32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  944. size_t const src_skip = source.pitch() / sizeof(ARGB32);
  945. for (int row = first_row; row < last_row; ++row) {
  946. memcpy(dst, src, sizeof(ARGB32) * clipped_rect.width());
  947. dst += dst_skip;
  948. src += src_skip;
  949. }
  950. return;
  951. }
  952. if (source.format() == BitmapFormat::RGBA8888) {
  953. u32 const* src = source.scanline(src_rect.top() + first_row) + src_rect.left() + first_column;
  954. size_t const src_skip = source.pitch() / sizeof(u32);
  955. for (int row = first_row; row < last_row; ++row) {
  956. for (int i = 0; i < clipped_rect.width(); ++i) {
  957. u32 rgba = src[i];
  958. u32 bgra = (rgba & 0xff00ff00)
  959. | ((rgba & 0x000000ff) << 16)
  960. | ((rgba & 0x00ff0000) >> 16);
  961. dst[i] = bgra;
  962. }
  963. dst += dst_skip;
  964. src += src_skip;
  965. }
  966. return;
  967. }
  968. if (Bitmap::is_indexed(source.format())) {
  969. u8 const* src = source.scanline_u8(src_rect.top() + first_row) + src_rect.left() + first_column;
  970. size_t const src_skip = source.pitch();
  971. for (int row = first_row; row <= last_row; ++row) {
  972. for (int i = 0; i < clipped_rect.width(); ++i)
  973. dst[i] = source.palette_color(src[i]).value();
  974. dst += dst_skip;
  975. src += src_skip;
  976. }
  977. return;
  978. }
  979. VERIFY_NOT_REACHED();
  980. }
  981. template<bool has_alpha_channel, typename GetPixel>
  982. 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)
  983. {
  984. bool has_opacity = opacity != 1.0f;
  985. for (int y = 0; y < src_rect.height(); ++y) {
  986. int dst_y = dst_rect.y() + y * vfactor;
  987. for (int x = 0; x < src_rect.width(); ++x) {
  988. auto src_pixel = get_pixel(source, x + src_rect.left(), y + src_rect.top());
  989. if (has_opacity)
  990. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  991. for (int yo = 0; yo < vfactor; ++yo) {
  992. auto* scanline = (Color*)target.scanline(dst_y + yo);
  993. int dst_x = dst_rect.x() + x * hfactor;
  994. for (int xo = 0; xo < hfactor; ++xo) {
  995. if constexpr (has_alpha_channel)
  996. scanline[dst_x + xo] = scanline[dst_x + xo].blend(src_pixel);
  997. else
  998. scanline[dst_x + xo] = src_pixel;
  999. }
  1000. }
  1001. }
  1002. }
  1003. }
  1004. template<bool has_alpha_channel, typename GetPixel>
  1005. ALWAYS_INLINE static void do_draw_box_sampled_scaled_bitmap(Gfx::Bitmap& target, IntRect const& dst_rect, IntRect const& clipped_rect, Gfx::Bitmap const& source, FloatRect const& src_rect, GetPixel get_pixel, float opacity)
  1006. {
  1007. float source_pixel_width = src_rect.width() / dst_rect.width();
  1008. float source_pixel_height = src_rect.height() / dst_rect.height();
  1009. float source_pixel_area = source_pixel_width * source_pixel_height;
  1010. FloatRect const pixel_box = { 0.f, 0.f, 1.f, 1.f };
  1011. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  1012. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  1013. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  1014. // Project the destination pixel in the source image
  1015. FloatRect const source_box = {
  1016. src_rect.left() + (x - dst_rect.x()) * source_pixel_width,
  1017. src_rect.top() + (y - dst_rect.y()) * source_pixel_height,
  1018. source_pixel_width,
  1019. source_pixel_height,
  1020. };
  1021. IntRect enclosing_source_box = enclosing_int_rect(source_box).intersected(source.rect());
  1022. // Sum the contribution of all source pixels inside the projected pixel
  1023. float red_accumulator = 0.f;
  1024. float green_accumulator = 0.f;
  1025. float blue_accumulator = 0.f;
  1026. float total_area = 0.f;
  1027. for (int sy = enclosing_source_box.y(); sy < enclosing_source_box.bottom(); ++sy) {
  1028. for (int sx = enclosing_source_box.x(); sx < enclosing_source_box.right(); ++sx) {
  1029. float area = source_box.intersected(pixel_box.translated(sx, sy)).size().area();
  1030. auto pixel = get_pixel(source, sx, sy);
  1031. area *= pixel.alpha() / 255.f;
  1032. red_accumulator += pixel.red() * area;
  1033. green_accumulator += pixel.green() * area;
  1034. blue_accumulator += pixel.blue() * area;
  1035. total_area += area;
  1036. }
  1037. }
  1038. Color src_pixel = {
  1039. round_to<u8>(min(red_accumulator / total_area, 255.f)),
  1040. round_to<u8>(min(green_accumulator / total_area, 255.f)),
  1041. round_to<u8>(min(blue_accumulator / total_area, 255.f)),
  1042. round_to<u8>(min(total_area * 255.f / source_pixel_area * opacity, 255.f)),
  1043. };
  1044. if constexpr (has_alpha_channel)
  1045. scanline[x] = scanline[x].blend(src_pixel);
  1046. else
  1047. scanline[x] = src_pixel;
  1048. }
  1049. }
  1050. }
  1051. template<bool has_alpha_channel, Painter::ScalingMode scaling_mode, typename GetPixel>
  1052. 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)
  1053. {
  1054. auto int_src_rect = enclosing_int_rect(src_rect);
  1055. auto clipped_src_rect = int_src_rect.intersected(source.rect());
  1056. if (clipped_src_rect.is_empty())
  1057. return;
  1058. if constexpr (scaling_mode == Painter::ScalingMode::NearestNeighbor || scaling_mode == Painter::ScalingMode::SmoothPixels) {
  1059. if (dst_rect == clipped_rect && int_src_rect == src_rect && !(dst_rect.width() % int_src_rect.width()) && !(dst_rect.height() % int_src_rect.height())) {
  1060. int hfactor = dst_rect.width() / int_src_rect.width();
  1061. int vfactor = dst_rect.height() / int_src_rect.height();
  1062. if (hfactor == 2 && vfactor == 2)
  1063. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 2, 2, get_pixel, opacity);
  1064. if (hfactor == 3 && vfactor == 3)
  1065. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 3, 3, get_pixel, opacity);
  1066. if (hfactor == 4 && vfactor == 4)
  1067. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, 4, 4, get_pixel, opacity);
  1068. return do_draw_integer_scaled_bitmap<has_alpha_channel>(target, dst_rect, int_src_rect, source, hfactor, vfactor, get_pixel, opacity);
  1069. }
  1070. }
  1071. if constexpr (scaling_mode == Painter::ScalingMode::BoxSampling)
  1072. return do_draw_box_sampled_scaled_bitmap<has_alpha_channel>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1073. bool has_opacity = opacity != 1.f;
  1074. i64 shift = 1ll << 32;
  1075. i64 fractional_mask = shift - 1;
  1076. i64 bilinear_offset_x = (1ll << 31) * (src_rect.width() / dst_rect.width() - 1);
  1077. i64 bilinear_offset_y = (1ll << 31) * (src_rect.height() / dst_rect.height() - 1);
  1078. i64 hscale = src_rect.width() * shift / dst_rect.width();
  1079. i64 vscale = src_rect.height() * shift / dst_rect.height();
  1080. i64 src_left = src_rect.left() * shift;
  1081. i64 src_top = src_rect.top() * shift;
  1082. for (int y = clipped_rect.top(); y < clipped_rect.bottom(); ++y) {
  1083. auto* scanline = reinterpret_cast<Color*>(target.scanline(y));
  1084. auto desired_y = (y - dst_rect.y()) * vscale + src_top;
  1085. for (int x = clipped_rect.left(); x < clipped_rect.right(); ++x) {
  1086. auto desired_x = (x - dst_rect.x()) * hscale + src_left;
  1087. Color src_pixel;
  1088. if constexpr (scaling_mode == Painter::ScalingMode::BilinearBlend) {
  1089. auto shifted_x = desired_x + bilinear_offset_x;
  1090. auto shifted_y = desired_y + bilinear_offset_y;
  1091. auto scaled_x0 = clamp(shifted_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1092. auto scaled_x1 = clamp((shifted_x >> 32) + 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1093. auto scaled_y0 = clamp(shifted_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1094. auto scaled_y1 = clamp((shifted_y >> 32) + 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1095. float x_ratio = (shifted_x & fractional_mask) / static_cast<float>(shift);
  1096. float y_ratio = (shifted_y & fractional_mask) / static_cast<float>(shift);
  1097. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1098. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1099. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1100. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1101. auto top = top_left.mixed_with(top_right, x_ratio);
  1102. auto bottom = bottom_left.mixed_with(bottom_right, x_ratio);
  1103. src_pixel = top.mixed_with(bottom, y_ratio);
  1104. } else if constexpr (scaling_mode == Painter::ScalingMode::SmoothPixels) {
  1105. auto scaled_x1 = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1106. auto scaled_x0 = clamp(scaled_x1 - 1, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1107. auto scaled_y1 = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1108. auto scaled_y0 = clamp(scaled_y1 - 1, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1109. float x_ratio = (desired_x & fractional_mask) / (float)shift;
  1110. float y_ratio = (desired_y & fractional_mask) / (float)shift;
  1111. float scaled_x_ratio = clamp(x_ratio * dst_rect.width() / (float)src_rect.width(), 0.f, 1.f);
  1112. float scaled_y_ratio = clamp(y_ratio * dst_rect.height() / (float)src_rect.height(), 0.f, 1.f);
  1113. auto top_left = get_pixel(source, scaled_x0, scaled_y0);
  1114. auto top_right = get_pixel(source, scaled_x1, scaled_y0);
  1115. auto bottom_left = get_pixel(source, scaled_x0, scaled_y1);
  1116. auto bottom_right = get_pixel(source, scaled_x1, scaled_y1);
  1117. auto top = top_left.mixed_with(top_right, scaled_x_ratio);
  1118. auto bottom = bottom_left.mixed_with(bottom_right, scaled_x_ratio);
  1119. src_pixel = top.mixed_with(bottom, scaled_y_ratio);
  1120. } else {
  1121. auto scaled_x = clamp(desired_x >> 32, clipped_src_rect.left(), clipped_src_rect.right() - 1);
  1122. auto scaled_y = clamp(desired_y >> 32, clipped_src_rect.top(), clipped_src_rect.bottom() - 1);
  1123. src_pixel = get_pixel(source, scaled_x, scaled_y);
  1124. }
  1125. if (has_opacity)
  1126. src_pixel.set_alpha(src_pixel.alpha() * opacity);
  1127. if constexpr (has_alpha_channel)
  1128. scanline[x] = scanline[x].blend(src_pixel);
  1129. else
  1130. scanline[x] = src_pixel;
  1131. }
  1132. }
  1133. }
  1134. template<bool has_alpha_channel, typename GetPixel>
  1135. 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)
  1136. {
  1137. switch (scaling_mode) {
  1138. case Painter::ScalingMode::NearestNeighbor:
  1139. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::NearestNeighbor>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1140. break;
  1141. case Painter::ScalingMode::SmoothPixels:
  1142. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::SmoothPixels>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1143. break;
  1144. case Painter::ScalingMode::BilinearBlend:
  1145. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::BilinearBlend>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1146. break;
  1147. case Painter::ScalingMode::BoxSampling:
  1148. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::BoxSampling>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1149. break;
  1150. case Painter::ScalingMode::None:
  1151. do_draw_scaled_bitmap<has_alpha_channel, Painter::ScalingMode::None>(target, dst_rect, clipped_rect, source, src_rect, get_pixel, opacity);
  1152. break;
  1153. }
  1154. }
  1155. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, IntRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1156. {
  1157. draw_scaled_bitmap(a_dst_rect, source, FloatRect { a_src_rect }, opacity, scaling_mode);
  1158. }
  1159. void Painter::draw_scaled_bitmap(IntRect const& a_dst_rect, Gfx::Bitmap const& source, FloatRect const& a_src_rect, float opacity, ScalingMode scaling_mode)
  1160. {
  1161. IntRect int_src_rect = enclosing_int_rect(a_src_rect);
  1162. if (scale() == source.scale() && a_src_rect == int_src_rect && a_dst_rect.size() == int_src_rect.size())
  1163. return blit(a_dst_rect.location(), source, int_src_rect, opacity);
  1164. if (scaling_mode == ScalingMode::None) {
  1165. 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() };
  1166. return blit(a_dst_rect.location(), source, clipped_draw_rect, opacity);
  1167. }
  1168. auto dst_rect = to_physical(a_dst_rect);
  1169. auto src_rect = a_src_rect * source.scale();
  1170. auto clipped_rect = dst_rect.intersected(clip_rect() * scale());
  1171. if (clipped_rect.is_empty())
  1172. return;
  1173. if (source.has_alpha_channel() || opacity != 1.0f) {
  1174. switch (source.format()) {
  1175. case BitmapFormat::BGRx8888:
  1176. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1177. break;
  1178. case BitmapFormat::BGRA8888:
  1179. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRA8888>, opacity, scaling_mode);
  1180. break;
  1181. case BitmapFormat::Indexed8:
  1182. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1183. break;
  1184. case BitmapFormat::Indexed4:
  1185. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed4>, opacity, scaling_mode);
  1186. break;
  1187. case BitmapFormat::Indexed2:
  1188. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed2>, opacity, scaling_mode);
  1189. break;
  1190. case BitmapFormat::Indexed1:
  1191. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed1>, opacity, scaling_mode);
  1192. break;
  1193. default:
  1194. do_draw_scaled_bitmap<true>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1195. break;
  1196. }
  1197. } else {
  1198. switch (source.format()) {
  1199. case BitmapFormat::BGRx8888:
  1200. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::BGRx8888>, opacity, scaling_mode);
  1201. break;
  1202. case BitmapFormat::Indexed8:
  1203. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Indexed8>, opacity, scaling_mode);
  1204. break;
  1205. default:
  1206. do_draw_scaled_bitmap<false>(*m_target, dst_rect, clipped_rect, source, src_rect, Gfx::get_pixel<BitmapFormat::Invalid>, opacity, scaling_mode);
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Color color)
  1212. {
  1213. draw_glyph(point, code_point, font(), color);
  1214. }
  1215. FLATTEN void Painter::draw_glyph(FloatPoint point, u32 code_point, Font const& font, Color color)
  1216. {
  1217. auto top_left = point + FloatPoint(font.glyph_left_bearing(code_point), 0);
  1218. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  1219. auto glyph = font.glyph(code_point, glyph_position.subpixel_offset);
  1220. if (glyph.is_glyph_bitmap()) {
  1221. draw_bitmap(top_left.to_type<int>(), glyph.glyph_bitmap(), color);
  1222. } else if (glyph.is_color_bitmap()) {
  1223. float scaled_width = glyph.advance();
  1224. float ratio = static_cast<float>(glyph.bitmap()->height()) / static_cast<float>(glyph.bitmap()->width());
  1225. float scaled_height = scaled_width * ratio;
  1226. FloatRect rect(point.x(), point.y(), scaled_width, scaled_height);
  1227. draw_scaled_bitmap(rect.to_rounded<int>(), *glyph.bitmap(), glyph.bitmap()->rect(), 1.0f, ScalingMode::BilinearBlend);
  1228. } else if (color.alpha() != 255) {
  1229. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1230. return pixel.multiply(color);
  1231. });
  1232. } else {
  1233. blit_filtered(glyph_position.blit_position, *glyph.bitmap(), glyph.bitmap()->rect(), [color](Color pixel) -> Color {
  1234. return color.with_alpha(pixel.alpha());
  1235. });
  1236. }
  1237. }
  1238. void Painter::draw_emoji(IntPoint point, Gfx::Bitmap const& emoji, Font const& font)
  1239. {
  1240. IntRect dst_rect {
  1241. point.x(),
  1242. point.y(),
  1243. font.pixel_size_rounded_up() * emoji.width() / emoji.height(),
  1244. font.pixel_size_rounded_up(),
  1245. };
  1246. draw_scaled_bitmap(dst_rect, emoji, emoji.rect());
  1247. }
  1248. void Painter::draw_glyph_or_emoji(FloatPoint point, u32 code_point, Font const& font, Color color)
  1249. {
  1250. StringBuilder builder;
  1251. builder.append_code_point(code_point);
  1252. auto it = Utf8View { builder.string_view() }.begin();
  1253. return draw_glyph_or_emoji(point, it, font, color);
  1254. }
  1255. void Painter::draw_glyph_or_emoji(FloatPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1256. {
  1257. u32 code_point = *it;
  1258. auto next_code_point = it.peek(1);
  1259. ScopeGuard consume_variation_selector = [&, initial_it = it] {
  1260. static auto const variation_selector = Unicode::property_from_string("Variation_Selector"sv);
  1261. if (!variation_selector.has_value())
  1262. return;
  1263. // If we advanced the iterator to consume an emoji sequence, don't look for another variation selector.
  1264. if (initial_it != it)
  1265. return;
  1266. // Otherwise, discard one code point if it's a variation selector.
  1267. if (next_code_point.has_value() && Unicode::code_point_has_property(*next_code_point, *variation_selector))
  1268. ++it;
  1269. };
  1270. // NOTE: We don't check for emoji
  1271. auto font_contains_glyph = font.contains_glyph(code_point);
  1272. 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);
  1273. // If the font contains the glyph, and we know it's not the start of an emoji, draw a text glyph.
  1274. if (font_contains_glyph && !check_for_emoji) {
  1275. draw_glyph(point, code_point, font, color);
  1276. return;
  1277. }
  1278. // If we didn't find a text glyph, or have an emoji variation selector or regional indicator, try to draw an emoji glyph.
  1279. if (auto const* emoji = Emoji::emoji_for_code_point_iterator(it)) {
  1280. draw_emoji(point.to_type<int>(), *emoji, font);
  1281. return;
  1282. }
  1283. // If that failed, but we have a text glyph fallback, draw that.
  1284. if (font_contains_glyph) {
  1285. draw_glyph(point, code_point, font, color);
  1286. return;
  1287. }
  1288. // No suitable glyph found, draw a replacement character.
  1289. dbgln_if(EMOJI_DEBUG, "Failed to find a glyph or emoji for code_point {}", code_point);
  1290. draw_glyph(point, 0xFFFD, font, color);
  1291. }
  1292. void Painter::draw_glyph(IntPoint point, u32 code_point, Color color)
  1293. {
  1294. draw_glyph(point.to_type<float>(), code_point, font(), color);
  1295. }
  1296. void Painter::draw_glyph(IntPoint point, u32 code_point, Font const& font, Color color)
  1297. {
  1298. draw_glyph(point.to_type<float>(), code_point, font, color);
  1299. }
  1300. void Painter::draw_glyph_or_emoji(IntPoint point, u32 code_point, Font const& font, Color color)
  1301. {
  1302. draw_glyph_or_emoji(point.to_type<float>(), code_point, font, color);
  1303. }
  1304. void Painter::draw_glyph_or_emoji(IntPoint point, Utf8CodePointIterator& it, Font const& font, Color color)
  1305. {
  1306. draw_glyph_or_emoji(point.to_type<float>(), it, font, color);
  1307. }
  1308. template<typename DrawGlyphFunction>
  1309. void draw_text_line(FloatRect const& a_rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextDirection direction, DrawGlyphFunction draw_glyph)
  1310. {
  1311. auto rect = a_rect;
  1312. switch (alignment) {
  1313. case TextAlignment::TopLeft:
  1314. case TextAlignment::CenterLeft:
  1315. case TextAlignment::BottomLeft:
  1316. break;
  1317. case TextAlignment::TopRight:
  1318. case TextAlignment::CenterRight:
  1319. case TextAlignment::BottomRight:
  1320. rect.set_x(rect.right() - 1 - font.width(text));
  1321. break;
  1322. case TextAlignment::TopCenter:
  1323. case TextAlignment::BottomCenter:
  1324. case TextAlignment::Center: {
  1325. auto shrunken_rect = rect;
  1326. shrunken_rect.set_width(font.width(text));
  1327. shrunken_rect.center_within(rect);
  1328. rect = shrunken_rect;
  1329. break;
  1330. }
  1331. default:
  1332. VERIFY_NOT_REACHED();
  1333. }
  1334. auto point = rect.location();
  1335. auto space_width = font.glyph_width(' ') + font.glyph_spacing();
  1336. if (direction == TextDirection::RTL) {
  1337. point.translate_by(rect.width(), 0); // Start drawing from the end
  1338. space_width = -space_width; // Draw spaces backwards
  1339. }
  1340. u32 last_code_point { 0 };
  1341. for (auto it = text.begin(); it != text.end(); ++it) {
  1342. auto code_point = *it;
  1343. if (should_paint_as_space(code_point)) {
  1344. point.translate_by(space_width, 0);
  1345. last_code_point = code_point;
  1346. continue;
  1347. }
  1348. auto kerning = font.glyphs_horizontal_kerning(last_code_point, code_point);
  1349. if (kerning != 0.0f)
  1350. point.translate_by(direction == TextDirection::LTR ? kerning : -kerning, 0);
  1351. auto it_copy = it; // The callback function will advance the iterator, so create a copy for this lookup.
  1352. FloatSize glyph_size(font.glyph_or_emoji_width(it_copy) + font.glyph_spacing(), font.pixel_size());
  1353. if (direction == TextDirection::RTL)
  1354. point.translate_by(-glyph_size.width(), 0); // If we are drawing right to left, we have to move backwards before drawing the glyph
  1355. draw_glyph({ point, glyph_size }, it);
  1356. if (direction == TextDirection::LTR)
  1357. point.translate_by(glyph_size.width(), 0);
  1358. // The callback function might have exhausted the iterator.
  1359. if (it == text.end())
  1360. break;
  1361. last_code_point = code_point;
  1362. }
  1363. }
  1364. static inline size_t draw_text_get_length(Utf8View const& text)
  1365. {
  1366. return text.byte_length();
  1367. }
  1368. Vector<DirectionalRun> Painter::split_text_into_directional_runs(Utf8View const& text, TextDirection initial_direction)
  1369. {
  1370. // FIXME: This is a *very* simplified version of the UNICODE BIDIRECTIONAL ALGORITHM (https://www.unicode.org/reports/tr9/), that can render most bidirectional text
  1371. // 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.
  1372. // FIXME: Support HTML "dir" attribute (how?)
  1373. u8 paragraph_embedding_level = initial_direction == TextDirection::LTR ? 0 : 1;
  1374. Vector<u8> embedding_levels;
  1375. embedding_levels.ensure_capacity(text.length());
  1376. for (size_t i = 0; i < text.length(); i++)
  1377. embedding_levels.unchecked_append(paragraph_embedding_level);
  1378. // FIXME: Support Explicit Directional Formatting Characters
  1379. Vector<BidirectionalClass> character_classes;
  1380. character_classes.ensure_capacity(text.length());
  1381. for (u32 code_point : text)
  1382. character_classes.unchecked_append(get_char_bidi_class(code_point));
  1383. // resolving weak types
  1384. BidirectionalClass paragraph_class = initial_direction == TextDirection::LTR ? BidirectionalClass::STRONG_LTR : BidirectionalClass::STRONG_RTL;
  1385. for (size_t i = 0; i < character_classes.size(); i++) {
  1386. if (character_classes[i] != BidirectionalClass::WEAK_SEPARATORS)
  1387. continue;
  1388. for (ssize_t j = i - 1; j >= 0; j--) {
  1389. auto character_class = character_classes[j];
  1390. if (character_class != BidirectionalClass::STRONG_RTL && character_class != BidirectionalClass::STRONG_LTR)
  1391. continue;
  1392. character_classes[i] = character_class;
  1393. break;
  1394. }
  1395. if (character_classes[i] == BidirectionalClass::WEAK_SEPARATORS)
  1396. character_classes[i] = paragraph_class;
  1397. }
  1398. // resolving neutral types
  1399. auto left_side = BidirectionalClass::NEUTRAL;
  1400. auto sequence_length = 0;
  1401. for (size_t i = 0; i < character_classes.size(); i++) {
  1402. auto character_class = character_classes[i];
  1403. if (left_side == BidirectionalClass::NEUTRAL) {
  1404. if (character_class != BidirectionalClass::NEUTRAL)
  1405. left_side = character_class;
  1406. else
  1407. character_classes[i] = paragraph_class;
  1408. continue;
  1409. }
  1410. if (character_class != BidirectionalClass::NEUTRAL) {
  1411. BidirectionalClass sequence_class;
  1412. if (bidi_class_to_direction(left_side) == bidi_class_to_direction(character_class)) {
  1413. sequence_class = left_side == BidirectionalClass::STRONG_RTL ? BidirectionalClass::STRONG_RTL : BidirectionalClass::STRONG_LTR;
  1414. } else {
  1415. sequence_class = paragraph_class;
  1416. }
  1417. for (auto j = 0; j < sequence_length; j++) {
  1418. character_classes[i - j - 1] = sequence_class;
  1419. }
  1420. sequence_length = 0;
  1421. left_side = character_class;
  1422. } else {
  1423. sequence_length++;
  1424. }
  1425. }
  1426. for (auto i = 0; i < sequence_length; i++)
  1427. character_classes[character_classes.size() - i - 1] = paragraph_class;
  1428. // resolving implicit levels
  1429. for (size_t i = 0; i < character_classes.size(); i++) {
  1430. auto character_class = character_classes[i];
  1431. if ((embedding_levels[i] % 2) == 0) {
  1432. if (character_class == BidirectionalClass::STRONG_RTL)
  1433. embedding_levels[i] += 1;
  1434. else if (character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1435. embedding_levels[i] += 2;
  1436. } else {
  1437. if (character_class == BidirectionalClass::STRONG_LTR || character_class == BidirectionalClass::WEAK_NUMBERS || character_class == BidirectionalClass::WEAK_SEPARATORS)
  1438. embedding_levels[i] += 1;
  1439. }
  1440. }
  1441. // splitting into runs
  1442. auto run_code_points_start = text.begin();
  1443. auto next_code_points_slice = [&](auto length) {
  1444. Vector<u32> run_code_points;
  1445. run_code_points.ensure_capacity(length);
  1446. for (size_t j = 0; j < length; ++j, ++run_code_points_start)
  1447. run_code_points.unchecked_append(*run_code_points_start);
  1448. return run_code_points;
  1449. };
  1450. Vector<DirectionalRun> runs;
  1451. size_t start = 0;
  1452. u8 level = embedding_levels[0];
  1453. for (size_t i = 1; i < embedding_levels.size(); ++i) {
  1454. if (embedding_levels[i] == level)
  1455. continue;
  1456. auto code_points_slice = next_code_points_slice(i - start);
  1457. runs.append({ move(code_points_slice), level });
  1458. start = i;
  1459. level = embedding_levels[i];
  1460. }
  1461. auto code_points_slice = next_code_points_slice(embedding_levels.size() - start);
  1462. runs.append({ move(code_points_slice), level });
  1463. // reordering resolved levels
  1464. // FIXME: missing special cases for trailing whitespace characters
  1465. u8 minimum_level = 128;
  1466. u8 maximum_level = 0;
  1467. for (auto& run : runs) {
  1468. minimum_level = min(minimum_level, run.embedding_level());
  1469. maximum_level = max(minimum_level, run.embedding_level());
  1470. }
  1471. if ((minimum_level % 2) == 0)
  1472. minimum_level++;
  1473. auto runs_count = runs.size() - 1;
  1474. while (maximum_level <= minimum_level) {
  1475. size_t run_index = 0;
  1476. while (run_index < runs_count) {
  1477. while (run_index < runs_count && runs[run_index].embedding_level() < maximum_level)
  1478. run_index++;
  1479. auto reverse_start = run_index;
  1480. while (run_index <= runs_count && runs[run_index].embedding_level() >= maximum_level)
  1481. run_index++;
  1482. auto reverse_end = run_index - 1;
  1483. while (reverse_start < reverse_end) {
  1484. swap(runs[reverse_start], runs[reverse_end]);
  1485. reverse_start++;
  1486. reverse_end--;
  1487. }
  1488. }
  1489. maximum_level--;
  1490. }
  1491. // mirroring RTL mirror characters
  1492. for (auto& run : runs) {
  1493. if (run.direction() == TextDirection::LTR)
  1494. continue;
  1495. for (auto& code_point : run.code_points()) {
  1496. code_point = get_mirror_char(code_point);
  1497. }
  1498. }
  1499. return runs;
  1500. }
  1501. bool Painter::text_contains_bidirectional_text(Utf8View const& text, TextDirection initial_direction)
  1502. {
  1503. for (u32 code_point : text) {
  1504. auto char_class = get_char_bidi_class(code_point);
  1505. if (char_class == BidirectionalClass::NEUTRAL)
  1506. continue;
  1507. if (bidi_class_to_direction(char_class) != initial_direction)
  1508. return true;
  1509. }
  1510. return false;
  1511. }
  1512. template<typename DrawGlyphFunction>
  1513. void Painter::do_draw_text(FloatRect const& rect, Utf8View const& text, Font const& font, TextAlignment alignment, TextElision elision, TextWrapping wrapping, DrawGlyphFunction draw_glyph)
  1514. {
  1515. if (draw_text_get_length(text) == 0)
  1516. return;
  1517. TextLayout layout(font, text, rect);
  1518. auto line_height = font.preferred_line_height();
  1519. auto lines = layout.lines(elision, wrapping);
  1520. auto bounding_rect = layout.bounding_rect(wrapping);
  1521. bounding_rect.align_within(rect, alignment);
  1522. for (size_t i = 0; i < lines.size(); ++i) {
  1523. auto line = Utf8View { lines[i] };
  1524. FloatRect line_rect { bounding_rect.x(), bounding_rect.y() + i * line_height, bounding_rect.width(), line_height };
  1525. TextDirection line_direction = get_text_direction(line);
  1526. if (text_contains_bidirectional_text(line, line_direction)) { // Slow Path: The line contains mixed BiDi classes
  1527. auto directional_runs = split_text_into_directional_runs(line, line_direction);
  1528. auto current_dx = line_direction == TextDirection::LTR ? 0 : line_rect.width();
  1529. for (auto& directional_run : directional_runs) {
  1530. auto run_width = font.width(directional_run.text());
  1531. if (line_direction == TextDirection::RTL)
  1532. current_dx -= run_width;
  1533. auto run_rect = line_rect.translated(current_dx, 0);
  1534. run_rect.set_width(run_width);
  1535. // NOTE: DirectionalRun returns Utf32View which isn't
  1536. // compatible with draw_text_line.
  1537. StringBuilder builder;
  1538. builder.append(directional_run.text());
  1539. auto line_text = Utf8View { builder.string_view() };
  1540. draw_text_line(run_rect, line_text, font, alignment, directional_run.direction(), draw_glyph);
  1541. if (line_direction == TextDirection::LTR)
  1542. current_dx += run_width;
  1543. }
  1544. } else {
  1545. draw_text_line(line_rect, line, font, alignment, line_direction, draw_glyph);
  1546. }
  1547. }
  1548. }
  1549. void Painter::draw_text(FloatRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1550. {
  1551. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1552. }
  1553. void Painter::draw_text(FloatRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1554. {
  1555. draw_text(rect, text, font(), alignment, color, elision, wrapping);
  1556. }
  1557. void Painter::draw_text(FloatRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1558. {
  1559. Utf8View text { raw_text };
  1560. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1561. draw_glyph_or_emoji(r.location(), it, font, color);
  1562. });
  1563. }
  1564. void Painter::draw_text(FloatRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1565. {
  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_glyph_or_emoji(r.location(), it, font, color);
  1573. });
  1574. }
  1575. 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)
  1576. {
  1577. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1578. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1579. draw_one_glyph(r, it);
  1580. });
  1581. }
  1582. 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)
  1583. {
  1584. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1585. Utf8View text { raw_text };
  1586. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1587. draw_one_glyph(r, it);
  1588. });
  1589. }
  1590. 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)
  1591. {
  1592. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1593. // FIXME: UTF-32 should eventually be completely removed, but for the time
  1594. // being some places might depend on it, so we do some internal conversion.
  1595. StringBuilder builder;
  1596. builder.append(raw_text);
  1597. auto text = Utf8View { builder.string_view() };
  1598. do_draw_text(rect, text, font, alignment, elision, wrapping, [&](FloatRect const& r, Utf8CodePointIterator& it) {
  1599. draw_one_glyph(r, it);
  1600. });
  1601. }
  1602. void Painter::draw_text(IntRect const& rect, StringView text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1603. {
  1604. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1605. }
  1606. void Painter::draw_text(IntRect const& rect, Utf32View const& text, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1607. {
  1608. draw_text(rect.to_type<float>(), text, font(), alignment, color, elision, wrapping);
  1609. }
  1610. void Painter::draw_text(IntRect const& rect, StringView raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1611. {
  1612. draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1613. }
  1614. void Painter::draw_text(IntRect const& rect, Utf32View const& raw_text, Font const& font, TextAlignment alignment, Color color, TextElision elision, TextWrapping wrapping)
  1615. {
  1616. return draw_text(rect.to_type<float>(), raw_text, font, alignment, color, elision, wrapping);
  1617. }
  1618. 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)
  1619. {
  1620. return draw_text(move(draw_one_glyph), rect.to_type<float>(), text, font, alignment, elision, wrapping);
  1621. }
  1622. 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)
  1623. {
  1624. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1625. }
  1626. 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)
  1627. {
  1628. return draw_text(move(draw_one_glyph), rect.to_type<float>(), raw_text, font, alignment, elision, wrapping);
  1629. }
  1630. void Painter::set_pixel(IntPoint p, Color color, bool blend)
  1631. {
  1632. auto point = p;
  1633. point.translate_by(state().translation);
  1634. // Use the scale only to avoid clipping pixels set in drawing functions that handle
  1635. // scaling and call set_pixel() -- do not scale the pixel.
  1636. if (!clip_rect().contains(point / scale()))
  1637. return;
  1638. set_physical_pixel(point, color, blend);
  1639. }
  1640. void Painter::set_physical_pixel(IntPoint physical_point, Color color, bool blend)
  1641. {
  1642. // This function should only be called after translation, clipping, etc has been handled elsewhere
  1643. // if not use set_pixel().
  1644. auto& dst = m_target->scanline(physical_point.y())[physical_point.x()];
  1645. if (!blend || color.alpha() == 255)
  1646. dst = color.value();
  1647. else if (color.alpha())
  1648. dst = color_for_format(target()->format(), dst).blend(color).value();
  1649. }
  1650. Optional<Color> Painter::get_pixel(IntPoint p)
  1651. {
  1652. auto point = p;
  1653. point.translate_by(state().translation);
  1654. if (!clip_rect().contains(point / scale()))
  1655. return {};
  1656. return m_target->get_pixel(point);
  1657. }
  1658. ErrorOr<NonnullRefPtr<Bitmap>> Painter::get_region_bitmap(IntRect const& region, BitmapFormat format, Optional<IntRect&> actual_region)
  1659. {
  1660. VERIFY(scale() == 1);
  1661. auto bitmap_region = region.translated(state().translation).intersected(m_target->rect());
  1662. if (actual_region.has_value())
  1663. actual_region.value() = bitmap_region.translated(-state().translation);
  1664. return m_target->cropped(bitmap_region, format);
  1665. }
  1666. ALWAYS_INLINE void Painter::set_physical_pixel_with_draw_op(u32& pixel, Color color)
  1667. {
  1668. // This always sets a single physical pixel, independent of scale().
  1669. // This should only be called by routines that already handle scale.
  1670. switch (draw_op()) {
  1671. case DrawOp::Copy:
  1672. pixel = color.value();
  1673. break;
  1674. case DrawOp::Xor:
  1675. pixel = color.xored(Color::from_argb(pixel)).value();
  1676. break;
  1677. case DrawOp::Invert:
  1678. pixel = Color::from_argb(pixel).inverted().value();
  1679. break;
  1680. }
  1681. }
  1682. ALWAYS_INLINE void Painter::fill_physical_scanline_with_draw_op(int y, int x, int width, Color color)
  1683. {
  1684. // This always draws a single physical scanline, independent of scale().
  1685. // This should only be called by routines that already handle scale.
  1686. auto dst_format = m_target->format();
  1687. switch (draw_op()) {
  1688. case DrawOp::Copy:
  1689. fast_u32_fill(m_target->scanline(y) + x, color.value(), width);
  1690. break;
  1691. case DrawOp::Xor: {
  1692. auto* pixel = m_target->scanline(y) + x;
  1693. auto* end = pixel + width;
  1694. while (pixel < end) {
  1695. *pixel = color_for_format(dst_format, *pixel).xored(color).value();
  1696. pixel++;
  1697. }
  1698. break;
  1699. }
  1700. case DrawOp::Invert: {
  1701. auto* pixel = m_target->scanline(y) + x;
  1702. auto* end = pixel + width;
  1703. while (pixel < end) {
  1704. *pixel = color_for_format(dst_format, *pixel).inverted().value();
  1705. pixel++;
  1706. }
  1707. break;
  1708. }
  1709. }
  1710. }
  1711. void Painter::draw_physical_pixel(IntPoint physical_position, Color color, int thickness)
  1712. {
  1713. // This always draws a single physical pixel, independent of scale().
  1714. // This should only be called by routines that already handle scale
  1715. // (including scaling thickness).
  1716. VERIFY(draw_op() == DrawOp::Copy);
  1717. if (thickness <= 0)
  1718. return;
  1719. if (thickness == 1) { // Implies scale() == 1.
  1720. auto& pixel = m_target->scanline(physical_position.y())[physical_position.x()];
  1721. return set_physical_pixel_with_draw_op(pixel, color_for_format(m_target->format(), pixel).blend(color));
  1722. }
  1723. IntRect rect { physical_position, { thickness, thickness } };
  1724. rect.intersect(clip_rect() * scale());
  1725. fill_physical_rect(rect, color);
  1726. }
  1727. void Painter::draw_line(IntPoint a_p1, IntPoint a_p2, Color color, int thickness, LineStyle style, Color alternate_color)
  1728. {
  1729. if (clip_rect().is_empty())
  1730. return;
  1731. if (thickness <= 0)
  1732. return;
  1733. if (color.alpha() == 0)
  1734. return;
  1735. auto clip_rect = this->clip_rect() * scale();
  1736. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1737. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1738. auto point1 = to_physical(p1);
  1739. auto point2 = to_physical(p2);
  1740. thickness *= scale();
  1741. auto alternate_color_is_transparent = alternate_color == Color::Transparent;
  1742. // Special case: vertical line.
  1743. if (point1.x() == point2.x()) {
  1744. int const x = point1.x();
  1745. if (x < clip_rect.left() || x >= clip_rect.right())
  1746. return;
  1747. if (point1.y() > point2.y())
  1748. swap(point1, point2);
  1749. if (point1.y() >= clip_rect.bottom())
  1750. return;
  1751. if (point2.y() < clip_rect.top())
  1752. return;
  1753. int min_y = max(point1.y(), clip_rect.top());
  1754. int max_y = min(point2.y(), clip_rect.bottom() - 1);
  1755. if (style == LineStyle::Dotted) {
  1756. for (int y = min_y; y <= max_y; y += thickness * 2)
  1757. draw_physical_pixel({ x, y }, color, thickness);
  1758. } else if (style == LineStyle::Dashed) {
  1759. for (int y = min_y; y <= max_y; y += thickness * 6) {
  1760. draw_physical_pixel({ x, y }, color, thickness);
  1761. draw_physical_pixel({ x, min(y + thickness, max_y) }, color, thickness);
  1762. draw_physical_pixel({ x, min(y + thickness * 2, max_y) }, color, thickness);
  1763. if (!alternate_color_is_transparent) {
  1764. draw_physical_pixel({ x, min(y + thickness * 3, max_y) }, alternate_color, thickness);
  1765. draw_physical_pixel({ x, min(y + thickness * 4, max_y) }, alternate_color, thickness);
  1766. draw_physical_pixel({ x, min(y + thickness * 5, max_y) }, alternate_color, thickness);
  1767. }
  1768. }
  1769. } else {
  1770. for (int y = min_y; y <= max_y; y += thickness)
  1771. draw_physical_pixel({ x, y }, color, thickness);
  1772. draw_physical_pixel({ x, max_y }, color, thickness);
  1773. }
  1774. return;
  1775. }
  1776. // Special case: horizontal line.
  1777. if (point1.y() == point2.y()) {
  1778. int const y = point1.y();
  1779. if (y < clip_rect.top() || y >= clip_rect.bottom())
  1780. return;
  1781. if (point1.x() > point2.x())
  1782. swap(point1, point2);
  1783. if (point1.x() >= clip_rect.right())
  1784. return;
  1785. if (point2.x() < clip_rect.left())
  1786. return;
  1787. int min_x = max(point1.x(), clip_rect.left());
  1788. int max_x = min(point2.x(), clip_rect.right() - 1);
  1789. if (style == LineStyle::Dotted) {
  1790. for (int x = min_x; x <= max_x; x += thickness * 2)
  1791. draw_physical_pixel({ x, y }, color, thickness);
  1792. } else if (style == LineStyle::Dashed) {
  1793. for (int x = min_x; x <= max_x; x += thickness * 6) {
  1794. draw_physical_pixel({ x, y }, color, thickness);
  1795. draw_physical_pixel({ min(x + thickness, max_x), y }, color, thickness);
  1796. draw_physical_pixel({ min(x + thickness * 2, max_x), y }, color, thickness);
  1797. if (!alternate_color_is_transparent) {
  1798. draw_physical_pixel({ min(x + thickness * 3, max_x), y }, alternate_color, thickness);
  1799. draw_physical_pixel({ min(x + thickness * 4, max_x), y }, alternate_color, thickness);
  1800. draw_physical_pixel({ min(x + thickness * 5, max_x), y }, alternate_color, thickness);
  1801. }
  1802. }
  1803. } else {
  1804. for (int x = min_x; x <= max_x; x += thickness)
  1805. draw_physical_pixel({ x, y }, color, thickness);
  1806. draw_physical_pixel({ max_x, y }, color, thickness);
  1807. }
  1808. return;
  1809. }
  1810. int const adx = abs(point2.x() - point1.x());
  1811. int const ady = abs(point2.y() - point1.y());
  1812. if (adx > ady) {
  1813. if (point1.x() > point2.x())
  1814. swap(point1, point2);
  1815. } else {
  1816. if (point1.y() > point2.y())
  1817. swap(point1, point2);
  1818. }
  1819. int const dx = point2.x() - point1.x();
  1820. int const dy = point2.y() - point1.y();
  1821. int error = 0;
  1822. size_t number_of_pixels_drawn = 0;
  1823. auto draw_pixel_in_line = [&](int x, int y) {
  1824. bool should_draw_line = true;
  1825. if (style == LineStyle::Dotted && number_of_pixels_drawn % 2 == 1)
  1826. should_draw_line = false;
  1827. else if (style == LineStyle::Dashed && number_of_pixels_drawn % 6 >= 3)
  1828. should_draw_line = false;
  1829. if (should_draw_line)
  1830. draw_physical_pixel({ x, y }, color, thickness);
  1831. else if (!alternate_color_is_transparent)
  1832. draw_physical_pixel({ x, y }, alternate_color, thickness);
  1833. number_of_pixels_drawn++;
  1834. };
  1835. if (dx > dy) {
  1836. int const y_step = dy == 0 ? 0 : (dy > 0 ? 1 : -1);
  1837. int const delta_error = 2 * abs(dy);
  1838. int y = point1.y();
  1839. for (int x = point1.x(); x <= point2.x(); ++x) {
  1840. if (clip_rect.contains(x, y))
  1841. draw_pixel_in_line(x, y);
  1842. error += delta_error;
  1843. if (error >= dx) {
  1844. y += y_step;
  1845. error -= 2 * dx;
  1846. }
  1847. }
  1848. } else {
  1849. int const x_step = dx == 0 ? 0 : (dx > 0 ? 1 : -1);
  1850. int const delta_error = 2 * abs(dx);
  1851. int x = point1.x();
  1852. for (int y = point1.y(); y <= point2.y(); ++y) {
  1853. if (clip_rect.contains(x, y))
  1854. draw_pixel_in_line(x, y);
  1855. error += delta_error;
  1856. if (error >= dy) {
  1857. x += x_step;
  1858. error -= 2 * dy;
  1859. }
  1860. }
  1861. }
  1862. }
  1863. void Painter::draw_triangle_wave(IntPoint a_p1, IntPoint a_p2, Color color, int amplitude, int thickness)
  1864. {
  1865. // FIXME: Support more than horizontal waves
  1866. VERIFY(a_p1.y() == a_p2.y());
  1867. auto const p1 = thickness > 1 ? a_p1.translated(-(thickness / 2), -(thickness / 2)) : a_p1;
  1868. auto const p2 = thickness > 1 ? a_p2.translated(-(thickness / 2), -(thickness / 2)) : a_p2;
  1869. auto point1 = to_physical(p1);
  1870. auto point2 = to_physical(p2);
  1871. auto y = point1.y();
  1872. for (int x = 0; x <= point2.x() - point1.x(); ++x) {
  1873. auto y_offset = abs(x % (2 * amplitude) - amplitude) - amplitude;
  1874. draw_physical_pixel({ point1.x() + x, y + y_offset }, color, thickness);
  1875. }
  1876. }
  1877. static bool can_approximate_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control)
  1878. {
  1879. constexpr float tolerance = 0.015f;
  1880. auto p1x = 3 * control.x() - 2 * p1.x() - p2.x();
  1881. auto p1y = 3 * control.y() - 2 * p1.y() - p2.y();
  1882. auto p2x = 3 * control.x() - 2 * p2.x() - p1.x();
  1883. auto p2y = 3 * control.y() - 2 * p2.y() - p1.y();
  1884. p1x = p1x * p1x;
  1885. p1y = p1y * p1y;
  1886. p2x = p2x * p2x;
  1887. p2y = p2y * p2y;
  1888. auto error = max(p1x, p2x) + max(p1y, p2y);
  1889. VERIFY(isfinite(error));
  1890. return error <= tolerance;
  1891. }
  1892. // static
  1893. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>& callback)
  1894. {
  1895. struct SegmentDescriptor {
  1896. FloatPoint control_point;
  1897. FloatPoint p1;
  1898. FloatPoint p2;
  1899. };
  1900. static constexpr auto split_quadratic_bezier_curve = [](FloatPoint original_control, FloatPoint p1, FloatPoint p2, auto& segments) {
  1901. auto po1_midpoint = original_control + p1;
  1902. po1_midpoint /= 2;
  1903. auto po2_midpoint = original_control + p2;
  1904. po2_midpoint /= 2;
  1905. auto new_segment = po1_midpoint + po2_midpoint;
  1906. new_segment /= 2;
  1907. segments.enqueue({ po1_midpoint, p1, new_segment });
  1908. segments.enqueue({ po2_midpoint, new_segment, p2 });
  1909. };
  1910. Queue<SegmentDescriptor> segments;
  1911. segments.enqueue({ control_point, p1, p2 });
  1912. while (!segments.is_empty()) {
  1913. auto segment = segments.dequeue();
  1914. if (can_approximate_bezier_curve(segment.p1, segment.p2, segment.control_point))
  1915. callback(segment.p1, segment.p2);
  1916. else
  1917. split_quadratic_bezier_curve(segment.control_point, segment.p1, segment.p2, segments);
  1918. }
  1919. }
  1920. void Painter::for_each_line_segment_on_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Function<void(FloatPoint, FloatPoint)>&& callback)
  1921. {
  1922. for_each_line_segment_on_bezier_curve(control_point, p1, p2, callback);
  1923. }
  1924. void Painter::draw_quadratic_bezier_curve(IntPoint control_point, IntPoint p1, IntPoint p2, Color color, int thickness, LineStyle style)
  1925. {
  1926. VERIFY(scale() == 1); // FIXME: Add scaling support.
  1927. if (thickness <= 0)
  1928. return;
  1929. for_each_line_segment_on_bezier_curve(FloatPoint(control_point), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1930. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1931. });
  1932. }
  1933. 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)
  1934. {
  1935. for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, callback);
  1936. }
  1937. static bool can_approximate_cubic_bezier_curve(FloatPoint p1, FloatPoint p2, FloatPoint control_0, FloatPoint control_1)
  1938. {
  1939. constexpr float tolerance = 0.015f;
  1940. auto ax = 3 * control_0.x() - 2 * p1.x() - p2.x();
  1941. auto ay = 3 * control_0.y() - 2 * p1.y() - p2.y();
  1942. auto bx = 3 * control_1.x() - p1.x() - 2 * p2.x();
  1943. auto by = 3 * control_1.y() - p1.y() - 2 * p2.y();
  1944. ax *= ax;
  1945. ay *= ay;
  1946. bx *= bx;
  1947. by *= by;
  1948. auto error = max(ax, bx) + max(ay, by);
  1949. VERIFY(isfinite(error));
  1950. return error <= tolerance;
  1951. }
  1952. // static
  1953. 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)
  1954. {
  1955. struct ControlPair {
  1956. FloatPoint control_point_0;
  1957. FloatPoint control_point_1;
  1958. };
  1959. struct SegmentDescriptor {
  1960. ControlPair control_points;
  1961. FloatPoint p1;
  1962. FloatPoint p2;
  1963. };
  1964. static constexpr auto split_cubic_bezier_curve = [](ControlPair const& original_controls, FloatPoint p1, FloatPoint p2, auto& segments) {
  1965. Array level_1_midpoints {
  1966. (p1 + original_controls.control_point_0) / 2,
  1967. (original_controls.control_point_0 + original_controls.control_point_1) / 2,
  1968. (original_controls.control_point_1 + p2) / 2,
  1969. };
  1970. Array level_2_midpoints {
  1971. (level_1_midpoints[0] + level_1_midpoints[1]) / 2,
  1972. (level_1_midpoints[1] + level_1_midpoints[2]) / 2,
  1973. };
  1974. auto level_3_midpoint = (level_2_midpoints[0] + level_2_midpoints[1]) / 2;
  1975. segments.enqueue({ { level_1_midpoints[0], level_2_midpoints[0] }, p1, level_3_midpoint });
  1976. segments.enqueue({ { level_2_midpoints[1], level_1_midpoints[2] }, level_3_midpoint, p2 });
  1977. };
  1978. Queue<SegmentDescriptor> segments;
  1979. segments.enqueue({ { control_point_0, control_point_1 }, p1, p2 });
  1980. while (!segments.is_empty()) {
  1981. auto segment = segments.dequeue();
  1982. if (can_approximate_cubic_bezier_curve(segment.p1, segment.p2, segment.control_points.control_point_0, segment.control_points.control_point_1))
  1983. callback(segment.p1, segment.p2);
  1984. else
  1985. split_cubic_bezier_curve(segment.control_points, segment.p1, segment.p2, segments);
  1986. }
  1987. }
  1988. 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)
  1989. {
  1990. for_each_line_segment_on_cubic_bezier_curve(FloatPoint(control_point_0), FloatPoint(control_point_1), FloatPoint(p1), FloatPoint(p2), [&](FloatPoint fp1, FloatPoint fp2) {
  1991. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  1992. });
  1993. }
  1994. // static
  1995. 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)
  1996. {
  1997. if (radii.width() <= 0 || radii.height() <= 0)
  1998. return;
  1999. auto start = p1;
  2000. auto end = p2;
  2001. bool start_swapped = false;
  2002. if (theta_delta < 0) {
  2003. swap(start, end);
  2004. theta_1 = theta_1 + theta_delta;
  2005. theta_delta = fabsf(theta_delta);
  2006. start_swapped = true;
  2007. }
  2008. auto relative_start = start - center;
  2009. auto a = radii.width();
  2010. auto b = radii.height();
  2011. // The segments are at most 1 long
  2012. auto largest_radius = max(a, b);
  2013. float theta_step = AK::atan2(1.f, (float)largest_radius);
  2014. FloatPoint current_point = relative_start;
  2015. FloatPoint next_point = { 0, 0 };
  2016. float sin_x_axis, cos_x_axis;
  2017. AK::sincos(x_axis_rotation, sin_x_axis, cos_x_axis);
  2018. auto rotate_point = [sin_x_axis, cos_x_axis](FloatPoint& p) {
  2019. auto original_x = p.x();
  2020. auto original_y = p.y();
  2021. p.set_x(original_x * cos_x_axis - original_y * sin_x_axis);
  2022. p.set_y(original_x * sin_x_axis + original_y * cos_x_axis);
  2023. };
  2024. auto emit_point = [&](auto p0, auto p1) {
  2025. // NOTE: If we swap the start/end we must swap the emitted points, so correct winding orders can be calculated.
  2026. if (start_swapped)
  2027. swap(p0, p1);
  2028. callback(p0, p1);
  2029. };
  2030. for (float theta = theta_1; theta <= theta_1 + theta_delta; theta += theta_step) {
  2031. float s, c;
  2032. AK::sincos(theta, s, c);
  2033. next_point.set_x(a * c);
  2034. next_point.set_y(b * s);
  2035. rotate_point(next_point);
  2036. emit_point(current_point + center, next_point + center);
  2037. current_point = next_point;
  2038. }
  2039. emit_point(current_point + center, end);
  2040. }
  2041. // static
  2042. 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)
  2043. {
  2044. for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, callback);
  2045. }
  2046. 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)
  2047. {
  2048. VERIFY(scale() == 1); // FIXME: Add scaling support.
  2049. if (thickness <= 0)
  2050. return;
  2051. 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) {
  2052. draw_line(IntPoint(fp1.x(), fp1.y()), IntPoint(fp2.x(), fp2.y()), color, thickness, style);
  2053. });
  2054. }
  2055. void Painter::add_clip_rect(IntRect const& rect)
  2056. {
  2057. state().clip_rect.intersect(rect.translated(translation()));
  2058. state().clip_rect.intersect(m_target->rect()); // FIXME: This shouldn't be necessary?
  2059. }
  2060. void Painter::clear_clip_rect()
  2061. {
  2062. state().clip_rect = m_clip_origin;
  2063. }
  2064. PainterStateSaver::PainterStateSaver(Painter& painter)
  2065. : m_painter(painter)
  2066. {
  2067. m_painter.save();
  2068. }
  2069. PainterStateSaver::~PainterStateSaver()
  2070. {
  2071. m_painter.restore();
  2072. }
  2073. void Painter::stroke_path(Path const& path, Color color, int thickness)
  2074. {
  2075. if (thickness <= 0)
  2076. return;
  2077. fill_path(path.stroke_to_fill(thickness), color);
  2078. }
  2079. void Painter::blit_disabled(IntPoint location, Gfx::Bitmap const& bitmap, IntRect const& rect, Palette const& palette)
  2080. {
  2081. auto bright_color = palette.threed_highlight();
  2082. auto dark_color = palette.threed_shadow1();
  2083. blit_filtered(location.translated(1, 1), bitmap, rect, [&](auto) {
  2084. return bright_color;
  2085. });
  2086. blit_filtered(location, bitmap, rect, [&](Color src) {
  2087. int gray = src.to_grayscale().red();
  2088. if (gray > 160)
  2089. return bright_color;
  2090. return dark_color;
  2091. });
  2092. }
  2093. void Painter::blit_tiled(IntRect const& dst_rect, Gfx::Bitmap const& bitmap, IntRect const& rect)
  2094. {
  2095. auto tile_width = rect.width();
  2096. auto tile_height = rect.height();
  2097. auto dst_right = dst_rect.right() - 1;
  2098. auto dst_bottom = dst_rect.bottom() - 1;
  2099. for (int tile_y = dst_rect.top(); tile_y < dst_bottom; tile_y += tile_height) {
  2100. for (int tile_x = dst_rect.left(); tile_x < dst_right; tile_x += tile_width) {
  2101. IntRect tile_src_rect = rect;
  2102. auto tile_x_overflow = tile_x + tile_width - dst_right;
  2103. if (tile_x_overflow > 0)
  2104. tile_src_rect.set_width(tile_width - tile_x_overflow);
  2105. auto tile_y_overflow = tile_y + tile_height - dst_bottom;
  2106. if (tile_y_overflow > 0)
  2107. tile_src_rect.set_height(tile_height - tile_y_overflow);
  2108. blit(IntPoint(tile_x, tile_y), bitmap, tile_src_rect);
  2109. }
  2110. }
  2111. }
  2112. DeprecatedString parse_ampersand_string(StringView raw_text, Optional<size_t>* underline_offset)
  2113. {
  2114. if (raw_text.is_empty())
  2115. return DeprecatedString::empty();
  2116. StringBuilder builder;
  2117. for (size_t i = 0; i < raw_text.length(); ++i) {
  2118. if (raw_text[i] == '&') {
  2119. if (i != (raw_text.length() - 1) && raw_text[i + 1] == '&') {
  2120. builder.append(raw_text[i]);
  2121. ++i;
  2122. } else if (underline_offset && !(*underline_offset).has_value()) {
  2123. *underline_offset = i;
  2124. }
  2125. continue;
  2126. }
  2127. builder.append(raw_text[i]);
  2128. }
  2129. return builder.to_deprecated_string();
  2130. }
  2131. void Gfx::Painter::draw_ui_text(Gfx::IntRect const& rect, StringView text, Gfx::Font const& font, Gfx::TextAlignment text_alignment, Gfx::Color color)
  2132. {
  2133. Optional<size_t> underline_offset;
  2134. auto name_to_draw = parse_ampersand_string(text, &underline_offset);
  2135. Gfx::IntRect text_rect { 0, 0, font.width_rounded_up(name_to_draw), font.pixel_size_rounded_up() };
  2136. text_rect.align_within(rect, text_alignment);
  2137. draw_text(text_rect, name_to_draw, font, text_alignment, color);
  2138. if (underline_offset.has_value()) {
  2139. Utf8View utf8_view { name_to_draw };
  2140. float width = 0;
  2141. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  2142. if (utf8_view.byte_offset_of(it) >= underline_offset.value()) {
  2143. int y = text_rect.bottom();
  2144. int x1 = text_rect.left() + width;
  2145. int x2 = x1 + font.glyph_or_emoji_width(it);
  2146. draw_line({ x1, y }, { x2, y }, color);
  2147. break;
  2148. }
  2149. width += font.glyph_or_emoji_width(it) + font.glyph_spacing();
  2150. }
  2151. }
  2152. }
  2153. void Painter::draw_text_run(IntPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2154. {
  2155. draw_text_run(baseline_start.to_type<float>(), string, font, color);
  2156. }
  2157. void Painter::draw_text_run(FloatPoint baseline_start, Utf8View const& string, Font const& font, Color color)
  2158. {
  2159. float space_width = font.glyph_width(' ') + font.glyph_spacing();
  2160. u32 last_code_point = 0;
  2161. auto point = baseline_start;
  2162. point.translate_by(0, -font.pixel_metrics().ascent);
  2163. for (auto code_point_iterator = string.begin(); code_point_iterator != string.end(); ++code_point_iterator) {
  2164. auto code_point = *code_point_iterator;
  2165. if (should_paint_as_space(code_point)) {
  2166. point.translate_by(space_width, 0);
  2167. last_code_point = code_point;
  2168. continue;
  2169. }
  2170. auto kerning = font.glyphs_horizontal_kerning(last_code_point, code_point);
  2171. if (kerning != 0.0f)
  2172. point.translate_by(kerning, 0);
  2173. auto it = code_point_iterator; // The callback function will advance the iterator, so create a copy for this lookup.
  2174. auto glyph_width = font.glyph_or_emoji_width(it) + font.glyph_spacing();
  2175. draw_glyph_or_emoji(point, code_point_iterator, font, color);
  2176. point.translate_by(glyph_width, 0);
  2177. last_code_point = code_point;
  2178. }
  2179. }
  2180. 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)
  2181. {
  2182. if (transform.is_identity_or_translation()) {
  2183. translate(transform.e(), transform.f());
  2184. draw_scaled_bitmap(dst_rect, bitmap, src_rect, opacity, scaling_mode);
  2185. translate(-transform.e(), -transform.f());
  2186. } else {
  2187. // The painter has an affine transform, we have to draw through it!
  2188. // FIXME: This is kinda inefficient.
  2189. // What we currently do, roughly:
  2190. // - Map the destination rect through the context's transform.
  2191. // - Compute the bounding rect of the destination quad.
  2192. // - For each point in the clipped bounding rect, reverse-map it to a point in the source image.
  2193. // - Sample the source image at the computed point.
  2194. // - Set or blend (depending on alpha values) one pixel in the canvas.
  2195. // - Loop.
  2196. // FIXME: Painter should have an affine transform as part of its state and handle all of this instead.
  2197. if (opacity == 0.0f)
  2198. return;
  2199. auto inverse_transform = transform.inverse();
  2200. if (!inverse_transform.has_value())
  2201. return;
  2202. auto destination_quad = transform.map_to_quad(dst_rect.to_type<float>());
  2203. auto destination_bounding_rect = destination_quad.bounding_rect().to_rounded<int>();
  2204. auto source_rect = enclosing_int_rect(src_rect).intersected(bitmap.rect());
  2205. Gfx::AffineTransform source_transform;
  2206. source_transform.translate(src_rect.x(), src_rect.y());
  2207. source_transform.scale(src_rect.width() / dst_rect.width(), src_rect.height() / dst_rect.height());
  2208. source_transform.translate(-dst_rect.x(), -dst_rect.y());
  2209. auto translated_dest_rect = destination_bounding_rect.translated(translation());
  2210. auto clipped_bounding_rect = translated_dest_rect.intersected(clip_rect());
  2211. if (clipped_bounding_rect.is_empty())
  2212. return;
  2213. auto sample_transform = source_transform.multiply(*inverse_transform);
  2214. auto start_offset = destination_bounding_rect.location() + (clipped_bounding_rect.location() - translated_dest_rect.location());
  2215. for (int y = 0; y < clipped_bounding_rect.height(); ++y) {
  2216. for (int x = 0; x < clipped_bounding_rect.width(); ++x) {
  2217. auto point = Gfx::IntPoint { x, y };
  2218. auto sample_point = point + start_offset;
  2219. auto source_point = sample_transform.map(sample_point).to_rounded<int>();
  2220. if (!source_rect.contains(source_point))
  2221. continue;
  2222. auto source_color = bitmap.get_pixel(source_point);
  2223. if (source_color.alpha() == 0)
  2224. continue;
  2225. if (opacity != 1.0f)
  2226. source_color = source_color.with_opacity(opacity);
  2227. set_physical_pixel(point + clipped_bounding_rect.location(), source_color, true);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. void Painter::draw_signed_distance_field(IntRect const& dst_rect, Color color, Gfx::GrayscaleBitmap const& sdf, float smoothing)
  2233. {
  2234. auto target_rect = dst_rect.translated(translation());
  2235. auto clipped_rect = target_rect.intersected(clip_rect());
  2236. if (clipped_rect.is_empty())
  2237. return;
  2238. target_rect *= scale();
  2239. clipped_rect *= scale();
  2240. auto start_offset = clipped_rect.location() - target_rect.location();
  2241. auto x_ratio = static_cast<float>(sdf.width() - 1) / (dst_rect.width() - 1);
  2242. auto y_ratio = static_cast<float>(sdf.height() - 1) / (dst_rect.height() - 1);
  2243. auto smooth_step = [](auto edge0, auto edge1, auto x) {
  2244. x = clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
  2245. return x * x * (3 - 2 * x);
  2246. };
  2247. auto pixel_at = [&](unsigned x, unsigned y) -> u8 {
  2248. // Returning 255 means this pixel is outside the shape.
  2249. if (x >= sdf.width() || y >= sdf.height())
  2250. return 255;
  2251. return sdf.pixel_at(x, y);
  2252. };
  2253. for (int i = 0; i < clipped_rect.height(); ++i) {
  2254. for (int j = 0; j < clipped_rect.width(); ++j) {
  2255. auto point = IntPoint { j, i };
  2256. auto sample_point = point + start_offset;
  2257. auto target_x = static_cast<int>(x_ratio * sample_point.x());
  2258. auto target_y = static_cast<int>(y_ratio * sample_point.y());
  2259. auto target_fraction_x = (x_ratio * sample_point.x()) - target_x;
  2260. auto target_fraction_y = (y_ratio * sample_point.y()) - target_y;
  2261. auto a = pixel_at(target_x, target_y);
  2262. auto b = pixel_at(target_x + 1, target_y);
  2263. auto c = pixel_at(target_x, target_y + 1);
  2264. auto d = pixel_at(target_x + 1, target_y + 1);
  2265. float distance = (a * (1 - target_fraction_x) * (1 - target_fraction_y)
  2266. + b * target_fraction_x * (1 - target_fraction_y)
  2267. + c * (1 - target_fraction_x) * target_fraction_y
  2268. + d * target_fraction_x * target_fraction_y)
  2269. / 255.0f;
  2270. u8 alpha = (1 - clamp(smooth_step(0.5f - smoothing, 0.5f + smoothing, distance), 0.0f, 1.0f)) * 255;
  2271. set_physical_pixel(point + clipped_rect.location(), color.with_alpha(alpha), true);
  2272. }
  2273. }
  2274. }
  2275. }