Painter.cpp 92 KB

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