Painter.cpp 66 KB

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