Painter.cpp 75 KB

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