Painter.cpp 76 KB

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