Painter.cpp 101 KB

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