Painter.cpp 71 KB

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