Painter.cpp 107 KB

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