Painter.cpp 84 KB

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