Painter.cpp 98 KB

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