Painter.cpp 102 KB

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