Painter.cpp 91 KB

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