Painter.cpp 104 KB

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