aboutsummaryrefslogtreecommitdiff
path: root/gcc/text-art
diff options
context:
space:
mode:
Diffstat (limited to 'gcc/text-art')
-rw-r--r--gcc/text-art/box-drawing-chars.inc18
-rw-r--r--gcc/text-art/box-drawing.cc73
-rw-r--r--gcc/text-art/box-drawing.h32
-rw-r--r--gcc/text-art/canvas.cc438
-rw-r--r--gcc/text-art/canvas.h74
-rw-r--r--gcc/text-art/ruler.cc724
-rw-r--r--gcc/text-art/ruler.h125
-rw-r--r--gcc/text-art/selftests.cc78
-rw-r--r--gcc/text-art/selftests.h62
-rw-r--r--gcc/text-art/style.cc633
-rw-r--r--gcc/text-art/styled-string.cc1108
-rw-r--r--gcc/text-art/table.cc1273
-rw-r--r--gcc/text-art/table.h261
-rw-r--r--gcc/text-art/theme.cc184
-rw-r--r--gcc/text-art/theme.h123
-rw-r--r--gcc/text-art/types.h510
-rw-r--r--gcc/text-art/widget.cc276
-rw-r--r--gcc/text-art/widget.h245
18 files changed, 6237 insertions, 0 deletions
diff --git a/gcc/text-art/box-drawing-chars.inc b/gcc/text-art/box-drawing-chars.inc
new file mode 100644
index 0000000..a370255
--- /dev/null
+++ b/gcc/text-art/box-drawing-chars.inc
@@ -0,0 +1,18 @@
+/* Generated by contrib/unicode/gen-box-drawing-chars.py. */
+
+0x0020, /* " ": U+0020: SPACE */
+0x2576, /* "╶": U+2576: BOX DRAWINGS LIGHT RIGHT */
+0x2574, /* "╴": U+2574: BOX DRAWINGS LIGHT LEFT */
+0x2500, /* "─": U+2500: BOX DRAWINGS LIGHT HORIZONTAL */
+0x2577, /* "╷": U+2577: BOX DRAWINGS LIGHT DOWN */
+0x250C, /* "┌": U+250C: BOX DRAWINGS LIGHT DOWN AND RIGHT */
+0x2510, /* "┐": U+2510: BOX DRAWINGS LIGHT DOWN AND LEFT */
+0x252C, /* "┬": U+252C: BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */
+0x2575, /* "╵": U+2575: BOX DRAWINGS LIGHT UP */
+0x2514, /* "└": U+2514: BOX DRAWINGS LIGHT UP AND RIGHT */
+0x2518, /* "┘": U+2518: BOX DRAWINGS LIGHT UP AND LEFT */
+0x2534, /* "┴": U+2534: BOX DRAWINGS LIGHT UP AND HORIZONTAL */
+0x2502, /* "│": U+2502: BOX DRAWINGS LIGHT VERTICAL */
+0x251C, /* "├": U+251C: BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
+0x2524, /* "┤": U+2524: BOX DRAWINGS LIGHT VERTICAL AND LEFT */
+0x253C /* "┼": U+253C: BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */
diff --git a/gcc/text-art/box-drawing.cc b/gcc/text-art/box-drawing.cc
new file mode 100644
index 0000000..7d49921
--- /dev/null
+++ b/gcc/text-art/box-drawing.cc
@@ -0,0 +1,73 @@
+/* Procedural lookup of box drawing characters.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "text-art/box-drawing.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+
+
+/* According to
+ https://en.wikipedia.org/wiki/Box-drawing_character#Character_code
+ "DOS line- and box-drawing characters are not ordered in any programmatic
+ manner, so calculating a particular character shape needs to use a look-up
+ table. "
+ Hence this array. */
+static const cppchar_t box_drawing_chars[] = {
+#include "text-art/box-drawing-chars.inc"
+};
+
+cppchar_t
+text_art::get_box_drawing_char (directions line_dirs)
+{
+ const size_t idx = line_dirs.as_index ();
+ gcc_assert (idx < 16);
+ return box_drawing_chars[idx];
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+/* Run all selftests in this file. */
+
+void
+text_art_box_drawing_cc_tests ()
+{
+ ASSERT_EQ (text_art::get_box_drawing_char
+ (text_art::directions (false, false, false, false)),
+ ' ');
+ ASSERT_EQ (text_art::get_box_drawing_char
+ (text_art::directions (false, false, true, true)),
+ 0x2500); /* BOX DRAWINGS LIGHT HORIZONTAL */
+ ASSERT_EQ (text_art::get_box_drawing_char
+ (text_art::directions (true, true, false, false)),
+ 0x2502); /* BOX DRAWINGS LIGHT VERTICAL */
+ ASSERT_EQ (text_art::get_box_drawing_char
+ (text_art::directions (true, false, true, false)),
+ 0x2518); /* BOX DRAWINGS LIGHT UP AND LEFT */
+}
+
+} // namespace selftest
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/box-drawing.h b/gcc/text-art/box-drawing.h
new file mode 100644
index 0000000..29f4d99
--- /dev/null
+++ b/gcc/text-art/box-drawing.h
@@ -0,0 +1,32 @@
+/* Procedural lookup of box drawing characters.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_BOX_DRAWING_H
+#define GCC_TEXT_ART_BOX_DRAWING_H
+
+#include "text-art/types.h"
+
+namespace text_art {
+
+extern cppchar_t get_box_drawing_char (directions line_dirs);
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_BOX_DRAWING_H */
diff --git a/gcc/text-art/canvas.cc b/gcc/text-art/canvas.cc
new file mode 100644
index 0000000..26ea051
--- /dev/null
+++ b/gcc/text-art/canvas.cc
@@ -0,0 +1,438 @@
+/* Canvas for random-access procedural text art.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "pretty-print.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/canvas.h"
+
+using namespace text_art;
+
+canvas::canvas (size_t size, const style_manager &style_mgr)
+: m_cells (size_t (size.w, size.h)),
+ m_style_mgr (style_mgr)
+{
+ m_cells.fill (cell_t (' '));
+}
+
+void
+canvas::paint (coord_t coord, styled_unichar ch)
+{
+ m_cells.set (coord, std::move (ch));
+}
+
+void
+canvas::paint_text (coord_t coord, const styled_string &text)
+{
+ for (auto ch : text)
+ {
+ paint (coord, ch);
+ if (ch.double_width_p ())
+ coord.x += 2;
+ else
+ coord.x++;
+ }
+}
+
+void
+canvas::fill (rect_t rect, cell_t c)
+{
+ for (int y = rect.get_min_y (); y < rect.get_next_y (); y++)
+ for (int x = rect.get_min_x (); x < rect.get_next_x (); x++)
+ paint(coord_t (x, y), c);
+}
+
+void
+canvas::debug_fill ()
+{
+ fill (rect_t (coord_t (0, 0), get_size ()), cell_t ('*'));
+}
+
+void
+canvas::print_to_pp (pretty_printer *pp,
+ const char *per_line_prefix) const
+{
+ for (int y = 0; y < m_cells.get_size ().h; y++)
+ {
+ style::id_t curr_style_id = 0;
+ if (per_line_prefix)
+ pp_string (pp, per_line_prefix);
+
+ pretty_printer line_pp;
+ line_pp.show_color = pp->show_color;
+ line_pp.url_format = pp->url_format;
+ const int final_x_in_row = get_final_x_in_row (y);
+ for (int x = 0; x <= final_x_in_row; x++)
+ {
+ if (x > 0)
+ {
+ const cell_t prev_cell = m_cells.get (coord_t (x - 1, y));
+ if (prev_cell.double_width_p ())
+ /* This cell is just a placeholder for the
+ 2nd column of a double width cell; skip it. */
+ continue;
+ }
+ const cell_t cell = m_cells.get (coord_t (x, y));
+ if (cell.get_style_id () != curr_style_id)
+ {
+ m_style_mgr.print_any_style_changes (&line_pp,
+ curr_style_id,
+ cell.get_style_id ());
+ curr_style_id = cell.get_style_id ();
+ }
+ pp_unicode_character (&line_pp, cell.get_code ());
+ if (cell.emoji_variant_p ())
+ /* Append U+FE0F VARIATION SELECTOR-16 to select the emoji
+ variation of the char. */
+ pp_unicode_character (&line_pp, 0xFE0F);
+ }
+ /* Reset the style at the end of each line. */
+ m_style_mgr.print_any_style_changes (&line_pp, curr_style_id, 0);
+
+ /* Print from line_pp to pp, stripping trailing whitespace from
+ the line. */
+ const char *line_buf = pp_formatted_text (&line_pp);
+ ::size_t len = strlen (line_buf);
+ while (len > 0)
+ {
+ if (line_buf[len - 1] == ' ')
+ len--;
+ else
+ break;
+ }
+ pp_append_text (pp, line_buf, line_buf + len);
+ pp_newline (pp);
+ }
+}
+
+DEBUG_FUNCTION void
+canvas::debug (bool styled) const
+{
+ pretty_printer pp;
+ if (styled)
+ {
+ pp_show_color (&pp) = true;
+ pp.url_format = determine_url_format (DIAGNOSTICS_URL_AUTO);
+ }
+ print_to_pp (&pp);
+ fprintf (stderr, "%s\n", pp_formatted_text (&pp));
+}
+
+/* Find right-most non-default cell in this row,
+ or -1 if all are default. */
+
+int
+canvas::get_final_x_in_row (int y) const
+{
+ for (int x = m_cells.get_size ().w - 1; x >= 0; x--)
+ {
+ cell_t cell = m_cells.get (coord_t (x, y));
+ if (cell.get_code () != ' '
+ || cell.get_style_id () != style::id_plain)
+ return x;
+ }
+ return -1;
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+static void
+test_blank ()
+{
+ style_manager sm;
+ canvas c (canvas::size_t (5, 5), sm);
+ ASSERT_CANVAS_STREQ (c, false,
+ ("\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"));
+}
+
+static void
+test_abc ()
+{
+ style_manager sm;
+ canvas c (canvas::size_t (3, 3), sm);
+ c.paint (canvas::coord_t (0, 0), styled_unichar ('A'));
+ c.paint (canvas::coord_t (1, 1), styled_unichar ('B'));
+ c.paint (canvas::coord_t (2, 2), styled_unichar ('C'));
+
+ ASSERT_CANVAS_STREQ (c, false,
+ "A\n B\n C\n");
+}
+
+static void
+test_debug_fill ()
+{
+ style_manager sm;
+ canvas c (canvas::size_t (5, 3), sm);
+ c.debug_fill();
+ ASSERT_CANVAS_STREQ (c, false,
+ ("*****\n"
+ "*****\n"
+ "*****\n"));
+}
+
+static void
+test_text ()
+{
+ style_manager sm;
+ canvas c (canvas::size_t (6, 1), sm);
+ c.paint_text (canvas::coord_t (0, 0), styled_string (sm, "012345"));
+ ASSERT_CANVAS_STREQ (c, false,
+ ("012345\n"));
+
+ /* Paint an emoji character that should occupy two canvas columns when
+ printed. */
+ c.paint_text (canvas::coord_t (2, 0), styled_string ((cppchar_t)0x1f642));
+ ASSERT_CANVAS_STREQ (c, false,
+ ("01🙂45\n"));
+}
+
+static void
+test_circle ()
+{
+ canvas::size_t sz (30, 30);
+ style_manager sm;
+ canvas canvas (sz, sm);
+ canvas::coord_t center (sz.w / 2, sz.h / 2);
+ const int radius = 12;
+ const int radius_squared = radius * radius;
+ for (int x = 0; x < sz.w; x++)
+ for (int y = 0; y < sz.h; y++)
+ {
+ int dx = x - center.x;
+ int dy = y - center.y;
+ char ch = "AB"[(x + y) % 2];
+ if (dx * dx + dy * dy < radius_squared)
+ canvas.paint (canvas::coord_t (x, y), styled_unichar (ch));
+ }
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("\n"
+ "\n"
+ "\n"
+ "\n"
+ " BABABABAB\n"
+ " ABABABABABABA\n"
+ " ABABABABABABABA\n"
+ " ABABABABABABABABA\n"
+ " ABABABABABABABABABA\n"
+ " ABABABABABABABABABABA\n"
+ " BABABABABABABABABABAB\n"
+ " BABABABABABABABABABABAB\n"
+ " ABABABABABABABABABABABA\n"
+ " BABABABABABABABABABABAB\n"
+ " ABABABABABABABABABABABA\n"
+ " BABABABABABABABABABABAB\n"
+ " ABABABABABABABABABABABA\n"
+ " BABABABABABABABABABABAB\n"
+ " ABABABABABABABABABABABA\n"
+ " BABABABABABABABABABABAB\n"
+ " BABABABABABABABABABAB\n"
+ " ABABABABABABABABABABA\n"
+ " ABABABABABABABABABA\n"
+ " ABABABABABABABABA\n"
+ " ABABABABABABABA\n"
+ " ABABABABABABA\n"
+ " BABABABAB\n"
+ "\n"
+ "\n"
+ "\n"));
+}
+
+static void
+test_color_circle ()
+{
+ const canvas::size_t sz (10, 10);
+ const canvas::coord_t center (sz.w / 2, sz.h / 2);
+ const int outer_r2 = 25;
+ const int inner_r2 = 10;
+ style_manager sm;
+ canvas c (sz, sm);
+ for (int x = 0; x < sz.w; x++)
+ for (int y = 0; y < sz.h; y++)
+ {
+ const int dist_from_center_squared
+ = ((x - center.x) * (x - center.x) + (y - center.y) * (y - center.y));
+ if (dist_from_center_squared < outer_r2)
+ {
+ style s;
+ if (dist_from_center_squared < inner_r2)
+ s.m_fg_color = style::named_color::RED;
+ else
+ s.m_fg_color = style::named_color::GREEN;
+ c.paint (canvas::coord_t (x, y),
+ styled_unichar ('*', false, sm.get_or_create_id (s)));
+ }
+ }
+ ASSERT_EQ (sm.get_num_styles (), 3);
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("\n"
+ " *****\n"
+ " *******\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *******\n"
+ " *****\n"));
+ ASSERT_CANVAS_STREQ
+ (c, true,
+ ("\n"
+ " *****\n"
+ " *******\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *********\n"
+ " *******\n"
+ " *****\n"));
+}
+
+static void
+test_bold ()
+{
+ auto_fix_quotes fix_quotes;
+ style_manager sm;
+ styled_string s (styled_string::from_fmt (sm, nullptr,
+ "before %qs after", "foo"));
+ canvas c (canvas::size_t (s.calc_canvas_width (), 1), sm);
+ c.paint_text (canvas::coord_t (0, 0), s);
+ ASSERT_CANVAS_STREQ (c, false,
+ "before `foo' after\n");
+ ASSERT_CANVAS_STREQ (c, true,
+ "before `foo' after\n");
+}
+
+static void
+test_emoji ()
+{
+ style_manager sm;
+ styled_string s (0x26A0, /* U+26A0 WARNING SIGN. */
+ true);
+ canvas c (canvas::size_t (s.calc_canvas_width (), 1), sm);
+ c.paint_text (canvas::coord_t (0, 0), s);
+ ASSERT_CANVAS_STREQ (c, false, "⚠️\n");
+ ASSERT_CANVAS_STREQ (c, true, "⚠️\n");
+}
+
+static void
+test_emoji_2 ()
+{
+ style_manager sm;
+ styled_string s;
+ s.append (styled_string (0x26A0, /* U+26A0 WARNING SIGN. */
+ true));
+ s.append (styled_string (sm, "test"));
+ ASSERT_EQ (s.size (), 5);
+ ASSERT_EQ (s.calc_canvas_width (), 5);
+ canvas c (canvas::size_t (s.calc_canvas_width (), 1), sm);
+ c.paint_text (canvas::coord_t (0, 0), s);
+ ASSERT_CANVAS_STREQ (c, false,
+ /* U+26A0 WARNING SIGN, as UTF-8: 0xE2 0x9A 0xA0. */
+ "\xE2\x9A\xA0"
+ /* U+FE0F VARIATION SELECTOR-16, as UTF-8: 0xEF 0xB8 0x8F. */
+ "\xEF\xB8\x8F"
+ "test\n");
+}
+
+static void
+test_canvas_urls ()
+{
+ style_manager sm;
+ canvas canvas (canvas::size_t (9, 3), sm);
+ styled_string foo_ss (sm, "foo");
+ foo_ss.set_url (sm, "https://www.example.com/foo");
+ styled_string bar_ss (sm, "bar");
+ bar_ss.set_url (sm, "https://www.example.com/bar");
+ canvas.paint_text(canvas::coord_t (1, 1), foo_ss);
+ canvas.paint_text(canvas::coord_t (5, 1), bar_ss);
+
+ ASSERT_CANVAS_STREQ (canvas, false,
+ ("\n"
+ " foo bar\n"
+ "\n"));
+ {
+ pretty_printer pp;
+ pp_show_color (&pp) = true;
+ pp.url_format = URL_FORMAT_ST;
+ assert_canvas_streq (SELFTEST_LOCATION, canvas, &pp,
+ (/* Line 1. */
+ "\n"
+ /* Line 2. */
+ " "
+ "\33]8;;https://www.example.com/foo\33\\foo\33]8;;\33\\"
+ " "
+ "\33]8;;https://www.example.com/bar\33\\bar\33]8;;\33\\"
+ "\n"
+ /* Line 3. */
+ "\n"));
+ }
+
+ {
+ pretty_printer pp;
+ pp_show_color (&pp) = true;
+ pp.url_format = URL_FORMAT_BEL;
+ assert_canvas_streq (SELFTEST_LOCATION, canvas, &pp,
+ (/* Line 1. */
+ "\n"
+ /* Line 2. */
+ " "
+ "\33]8;;https://www.example.com/foo\afoo\33]8;;\a"
+ " "
+ "\33]8;;https://www.example.com/bar\abar\33]8;;\a"
+ "\n"
+ /* Line 3. */
+ "\n"));
+ }
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_canvas_cc_tests ()
+{
+ test_blank ();
+ test_abc ();
+ test_debug_fill ();
+ test_text ();
+ test_circle ();
+ test_color_circle ();
+ test_bold ();
+ test_emoji ();
+ test_emoji_2 ();
+ test_canvas_urls ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/canvas.h b/gcc/text-art/canvas.h
new file mode 100644
index 0000000..4954977
--- /dev/null
+++ b/gcc/text-art/canvas.h
@@ -0,0 +1,74 @@
+/* Canvas for random-access procedural text art.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_CANVAS_H
+#define GCC_TEXT_ART_CANVAS_H
+
+#include "text-art/types.h"
+
+namespace text_art {
+
+class canvas;
+
+/* A 2 dimensional grid of text cells (a "canvas"), which
+ can be written to ("painted") via random access, and then
+ written out to a pretty_printer once the picture is complete.
+
+ Each text cell can be styled independently (colorization,
+ URLs, etc). */
+
+class canvas
+{
+ public:
+ typedef styled_unichar cell_t;
+ typedef size<class canvas> size_t;
+ typedef coord<class canvas> coord_t;
+ typedef range<class canvas> range_t;
+ typedef rect<class canvas> rect_t;
+
+ canvas (size_t size, const style_manager &style_mgr);
+
+ size_t get_size () const { return m_cells.get_size (); }
+
+ void paint (coord_t coord, cell_t c);
+ void paint_text (coord_t coord, const styled_string &text);
+
+ void fill (rect_t rect, cell_t c);
+ void debug_fill ();
+
+ void print_to_pp (pretty_printer *pp,
+ const char *per_line_prefix = NULL) const;
+ void debug (bool styled) const;
+
+ const cell_t &get (coord_t coord) const
+ {
+ return m_cells.get (coord);
+ }
+
+ private:
+ int get_final_x_in_row (int y) const;
+
+ array2<cell_t, size_t, coord_t> m_cells;
+ const style_manager &m_style_mgr;
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_CANVAS_H */
diff --git a/gcc/text-art/ruler.cc b/gcc/text-art/ruler.cc
new file mode 100644
index 0000000..3323a05
--- /dev/null
+++ b/gcc/text-art/ruler.cc
@@ -0,0 +1,724 @@
+/* Classes for printing labelled rulers.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_ALGORITHM
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "pretty-print.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/ruler.h"
+#include "text-art/theme.h"
+
+using namespace text_art;
+
+void
+x_ruler::add_label (const canvas::range_t &r,
+ styled_string text,
+ style::id_t style_id,
+ label_kind kind)
+{
+ m_labels.push_back (label (r, std::move (text), style_id, kind));
+ m_has_layout = false;
+}
+
+int
+x_ruler::get_canvas_y (int rel_y) const
+{
+ gcc_assert (rel_y >= 0);
+ gcc_assert (rel_y < m_size.h);
+ switch (m_label_dir)
+ {
+ default:
+ gcc_unreachable ();
+ case label_dir::ABOVE:
+ return m_size.h - (rel_y + 1);
+ case label_dir::BELOW:
+ return rel_y;
+ }
+}
+
+void
+x_ruler::paint_to_canvas (canvas &canvas,
+ canvas::coord_t offset,
+ const theme &theme)
+{
+ ensure_layout ();
+
+ if (0)
+ canvas.fill (canvas::rect_t (offset, m_size),
+ canvas::cell_t ('*'));
+
+ for (size_t idx = 0; idx < m_labels.size (); idx++)
+ {
+ const label &iter_label = m_labels[idx];
+
+ /* Paint the ruler itself. */
+ const int ruler_rel_y = get_canvas_y (0);
+ for (int rel_x = iter_label.m_range.start;
+ rel_x < iter_label.m_range.next;
+ rel_x++)
+ {
+ enum theme::cell_kind kind = theme::cell_kind::X_RULER_MIDDLE;
+
+ if (rel_x == iter_label.m_range.start)
+ {
+ kind = theme::cell_kind::X_RULER_LEFT_EDGE;
+ if (idx > 0)
+ {
+ const label &prev_label = m_labels[idx - 1];
+ if (prev_label.m_range.get_max () == iter_label.m_range.start)
+ kind = theme::cell_kind::X_RULER_INTERNAL_EDGE;
+ }
+ }
+ else if (rel_x == iter_label.m_range.get_max ())
+ kind = theme::cell_kind::X_RULER_RIGHT_EDGE;
+ else if (rel_x == iter_label.m_connector_x)
+ {
+ switch (m_label_dir)
+ {
+ default:
+ gcc_unreachable ();
+ case label_dir::ABOVE:
+ kind = theme::cell_kind::X_RULER_CONNECTOR_TO_LABEL_ABOVE;
+ break;
+ case label_dir::BELOW:
+ kind = theme::cell_kind::X_RULER_CONNECTOR_TO_LABEL_BELOW;
+ break;
+ }
+ }
+ canvas.paint (canvas::coord_t (rel_x, ruler_rel_y) + offset,
+ theme.get_cell (kind, iter_label.m_style_id));
+ }
+
+ /* Paint the connector to the text. */
+ for (int connector_rel_y = 1;
+ connector_rel_y < iter_label.m_text_rect.get_min_y ();
+ connector_rel_y++)
+ {
+ canvas.paint
+ ((canvas::coord_t (iter_label.m_connector_x,
+ get_canvas_y (connector_rel_y))
+ + offset),
+ theme.get_cell (theme::cell_kind::X_RULER_VERTICAL_CONNECTOR,
+ iter_label.m_style_id));
+ }
+
+ /* Paint the text. */
+ switch (iter_label.m_kind)
+ {
+ default:
+ gcc_unreachable ();
+ case x_ruler::label_kind::TEXT:
+ canvas.paint_text
+ ((canvas::coord_t (iter_label.m_text_rect.get_min_x (),
+ get_canvas_y (iter_label.m_text_rect.get_min_y ()))
+ + offset),
+ iter_label.m_text);
+ break;
+
+ case x_ruler::label_kind::TEXT_WITH_BORDER:
+ {
+ const canvas::range_t rel_x_range
+ (iter_label.m_text_rect.get_x_range ());
+
+ enum theme::cell_kind inner_left_kind;
+ enum theme::cell_kind inner_connector_kind;
+ enum theme::cell_kind inner_right_kind;
+ enum theme::cell_kind outer_left_kind;
+ enum theme::cell_kind outer_right_kind;
+
+ switch (m_label_dir)
+ {
+ default:
+ gcc_unreachable ();
+ case label_dir::ABOVE:
+ outer_left_kind = theme::cell_kind::TEXT_BORDER_TOP_LEFT;
+ outer_right_kind = theme::cell_kind::TEXT_BORDER_TOP_RIGHT;
+ inner_left_kind = theme::cell_kind::TEXT_BORDER_BOTTOM_LEFT;
+ inner_connector_kind = theme::cell_kind::X_RULER_CONNECTOR_TO_LABEL_BELOW;
+ inner_right_kind = theme::cell_kind::TEXT_BORDER_BOTTOM_RIGHT;
+ break;
+ case label_dir::BELOW:
+ inner_left_kind = theme::cell_kind::TEXT_BORDER_TOP_LEFT;
+ inner_connector_kind = theme::cell_kind::X_RULER_CONNECTOR_TO_LABEL_ABOVE;
+ inner_right_kind = theme::cell_kind::TEXT_BORDER_TOP_RIGHT;
+ outer_left_kind = theme::cell_kind::TEXT_BORDER_BOTTOM_LEFT;
+ outer_right_kind = theme::cell_kind::TEXT_BORDER_BOTTOM_RIGHT;
+ break;
+ }
+ /* Inner border. */
+ {
+ const int rel_canvas_y
+ = get_canvas_y (iter_label.m_text_rect.get_min_y ());
+ /* Left corner. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_min (),
+ rel_canvas_y)
+ + offset),
+ theme.get_cell (inner_left_kind,
+ iter_label.m_style_id));
+ /* Edge. */
+ const canvas::cell_t edge_border_cell
+ = theme.get_cell (theme::cell_kind::TEXT_BORDER_HORIZONTAL,
+ iter_label.m_style_id);
+ const canvas::cell_t connector_border_cell
+ = theme.get_cell (inner_connector_kind,
+ iter_label.m_style_id);
+ for (int rel_x = rel_x_range.get_min () + 1;
+ rel_x < rel_x_range.get_max ();
+ rel_x++)
+ if (rel_x == iter_label.m_connector_x)
+ canvas.paint ((canvas::coord_t (rel_x, rel_canvas_y)
+ + offset),
+ connector_border_cell);
+ else
+ canvas.paint ((canvas::coord_t (rel_x, rel_canvas_y)
+ + offset),
+ edge_border_cell);
+
+ /* Right corner. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_max (),
+ rel_canvas_y)
+ + offset),
+ theme.get_cell (inner_right_kind,
+ iter_label.m_style_id));
+ }
+
+ {
+ const int rel_canvas_y
+ = get_canvas_y (iter_label.m_text_rect.get_min_y () + 1);
+ const canvas::cell_t border_cell
+ = theme.get_cell (theme::cell_kind::TEXT_BORDER_VERTICAL,
+ iter_label.m_style_id);
+
+ /* Left border. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_min (),
+ rel_canvas_y)
+ + offset),
+ border_cell);
+ /* Text. */
+ canvas.paint_text ((canvas::coord_t (rel_x_range.get_min () + 1,
+ rel_canvas_y)
+ + offset),
+ iter_label.m_text);
+ /* Right border. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_max (),
+ rel_canvas_y)
+ + offset),
+ border_cell);
+ }
+
+ /* Outer border. */
+ {
+ const int rel_canvas_y
+ = get_canvas_y (iter_label.m_text_rect.get_max_y ());
+ /* Left corner. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_min (),
+ rel_canvas_y)
+ + offset),
+ theme.get_cell (outer_left_kind,
+ iter_label.m_style_id));
+ /* Edge. */
+ const canvas::cell_t border_cell
+ = theme.get_cell (theme::cell_kind::TEXT_BORDER_HORIZONTAL,
+ iter_label.m_style_id);
+ for (int rel_x = rel_x_range.get_min () + 1;
+ rel_x < rel_x_range.get_max ();
+ rel_x++)
+ canvas.paint ((canvas::coord_t (rel_x, rel_canvas_y)
+ + offset),
+ border_cell);
+
+ /* Right corner. */
+ canvas.paint ((canvas::coord_t (rel_x_range.get_max (),
+ rel_canvas_y)
+ + offset),
+ theme.get_cell (outer_right_kind,
+ iter_label.m_style_id));
+ }
+ }
+ break;
+ }
+ }
+}
+
+DEBUG_FUNCTION void
+x_ruler::debug (const style_manager &sm)
+{
+ canvas c (get_size (), sm);
+ paint_to_canvas (c, canvas::coord_t (0, 0), unicode_theme ());
+ c.debug (true);
+}
+
+x_ruler::label::label (const canvas::range_t &range,
+ styled_string text,
+ style::id_t style_id,
+ label_kind kind)
+: m_range (range),
+ m_text (std::move (text)),
+ m_style_id (style_id),
+ m_kind (kind),
+ m_text_rect (canvas::coord_t (0, 0),
+ canvas::size_t (m_text.calc_canvas_width (), 1)),
+ m_connector_x ((m_range.get_min () + m_range.get_max ()) / 2)
+{
+ if (kind == label_kind::TEXT_WITH_BORDER)
+ {
+ m_text_rect.m_size.w += 2;
+ m_text_rect.m_size.h += 2;
+ }
+}
+
+bool
+x_ruler::label::operator< (const label &other) const
+{
+ int cmp = m_range.start - other.m_range.start;
+ if (cmp)
+ return cmp < 0;
+ return m_range.next < other.m_range.next;
+}
+
+void
+x_ruler::ensure_layout ()
+{
+ if (m_has_layout)
+ return;
+ update_layout ();
+ m_has_layout = true;
+}
+
+void
+x_ruler::update_layout ()
+{
+ if (m_labels.empty ())
+ return;
+
+ std::sort (m_labels.begin (), m_labels.end ());
+
+ /* Place labels. */
+ int ruler_width = m_labels.back ().m_range.get_next ();
+ int width_with_labels = ruler_width;
+
+ /* Get x coordinates of text parts of each label
+ (m_text_rect.m_top_left.x for each label). */
+ for (size_t idx = 0; idx < m_labels.size (); idx++)
+ {
+ label &iter_label = m_labels[idx];
+ /* Attempt to center the text label. */
+ int min_x;
+ if (idx > 0)
+ {
+ /* ...but don't overlap with the connector to the left. */
+ int left_neighbor_connector_x = m_labels[idx - 1].m_connector_x;
+ min_x = left_neighbor_connector_x + 1;
+ }
+ else
+ {
+ /* ...or go beyond the leftmost column. */
+ min_x = 0;
+ }
+ int connector_x = iter_label.m_connector_x;
+ int centered_x
+ = connector_x - ((int)iter_label.m_text_rect.get_width () / 2);
+ int text_x = std::max (min_x, centered_x);
+ iter_label.m_text_rect.m_top_left.x = text_x;
+ }
+
+ /* Now walk backwards trying to place them vertically,
+ setting m_text_rect.m_top_left.y for each label,
+ consolidating the rows where possible.
+ The y cooordinates are stored with respect to label_dir::BELOW. */
+ int label_y = 2;
+ for (int idx = m_labels.size () - 1; idx >= 0; idx--)
+ {
+ label &iter_label = m_labels[idx];
+ /* Does it fit on the same row as the text label to the right? */
+ size_t text_len = iter_label.m_text_rect.get_width ();
+ /* Get the x-coord of immediately beyond iter_label's text. */
+ int next_x = iter_label.m_text_rect.get_min_x () + text_len;
+ if (idx < (int)m_labels.size () - 1)
+ {
+ if (next_x >= m_labels[idx + 1].m_text_rect.get_min_x ())
+ {
+ /* If not, start a new row. */
+ label_y += m_labels[idx + 1].m_text_rect.get_height ();
+ }
+ }
+ iter_label.m_text_rect.m_top_left.y = label_y;
+ width_with_labels = std::max (width_with_labels, next_x);
+ }
+
+ m_size = canvas::size_t (width_with_labels,
+ label_y + m_labels[0].m_text_rect.get_height ());
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+static void
+assert_x_ruler_streq (const location &loc,
+ x_ruler &ruler,
+ const theme &theme,
+ const style_manager &sm,
+ bool styled,
+ const char *expected_str)
+{
+ canvas c (ruler.get_size (), sm);
+ ruler.paint_to_canvas (c, canvas::coord_t (0, 0), theme);
+ if (0)
+ c.debug (styled);
+ assert_canvas_streq (loc, c, styled, expected_str);
+}
+
+#define ASSERT_X_RULER_STREQ(RULER, THEME, SM, STYLED, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ assert_x_ruler_streq ((SELFTEST_LOCATION), \
+ (RULER), \
+ (THEME), \
+ (SM), \
+ (STYLED), \
+ (EXPECTED_STR)); \
+ SELFTEST_END_STMT
+
+static void
+test_single ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "foo"),
+ style::id_plain, x_ruler::label_kind::TEXT);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ ("|~~~~+~~~~|\n"
+ " |\n"
+ " foo\n"));
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┤\n"
+ " │\n"
+ " foo\n"));
+}
+
+static void
+test_single_above ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::ABOVE);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "hello world"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ ("hello world\n"
+ " |\n"
+ "|~~~~+~~~~|\n"));
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("hello world\n"
+ " │\n"
+ "├────┴────┤\n"));
+}
+
+static void
+test_multiple_contiguous ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "foo"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16), styled_string (sm, "bar"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ ("|~~~~+~~~~|~+~~|\n"
+ " | |\n"
+ " foo bar\n"));
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┼─┬──┤\n"
+ " │ │\n"
+ " foo bar\n"));
+}
+
+static void
+test_multiple_contiguous_above ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::ABOVE);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "foo"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16), styled_string (sm, "bar"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ (" foo bar\n"
+ " | |\n"
+ "|~~~~+~~~~|~+~~|\n"));
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ (" foo bar\n"
+ " │ │\n"
+ "├────┴────┼─┴──┤\n"));
+}
+
+static void
+test_multiple_contiguous_abutting_labels ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "12345678"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16), styled_string (sm, "1234678"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┼─┬──┤\n"
+ " │ │\n"
+ " │ 1234678\n"
+ " 12345678\n"));
+}
+
+static void
+test_multiple_contiguous_overlapping_labels ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11), styled_string (sm, "123456789"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16), styled_string (sm, "12346789"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┼─┬──┤\n"
+ " │ │\n"
+ " │ 12346789\n"
+ " 123456789\n"));
+}
+static void
+test_abutting_left_border ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 6),
+ styled_string (sm, "this is a long label"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├─┬──┤\n"
+ " │\n"
+ "this is a long label\n"));
+}
+
+static void
+test_too_long_to_consolidate_vertically ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11),
+ styled_string (sm, "long string A"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16),
+ styled_string (sm, "long string B"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┼─┬──┤\n"
+ " │ │\n"
+ " │long string B\n"
+ "long string A\n"));
+}
+
+static void
+test_abutting_neighbor ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 11),
+ styled_string (sm, "very long string A"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 16),
+ styled_string (sm, "very long string B"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ ("├────┬────┼─┬──┤\n"
+ " │ │\n"
+ " │very long string B\n"
+ "very long string A\n"));
+}
+
+static void
+test_gaps ()
+{
+ style_manager sm;
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 5),
+ styled_string (sm, "foo"),
+ style::id_plain);
+ r.add_label (canvas::range_t (10, 15),
+ styled_string (sm, "bar"),
+ style::id_plain);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ ("|~+~| |~+~|\n"
+ " | |\n"
+ " foo bar\n"));
+}
+
+static void
+test_styled ()
+{
+ style_manager sm;
+ style s1, s2;
+ s1.m_bold = true;
+ s1.m_fg_color = style::named_color::YELLOW;
+ s2.m_bold = true;
+ s2.m_fg_color = style::named_color::BLUE;
+ style::id_t sid1 = sm.get_or_create_id (s1);
+ style::id_t sid2 = sm.get_or_create_id (s2);
+
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 5), styled_string (sm, "foo"), sid1);
+ r.add_label (canvas::range_t (10, 15), styled_string (sm, "bar"), sid2);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ ("|~+~| |~+~|\n"
+ " | |\n"
+ " foo bar\n"));
+}
+
+static void
+test_borders ()
+{
+ style_manager sm;
+ {
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 5),
+ styled_string (sm, "label 1"),
+ style::id_plain,
+ x_ruler::label_kind::TEXT_WITH_BORDER);
+ r.add_label (canvas::range_t (10, 15),
+ styled_string (sm, "label 2"),
+ style::id_plain);
+ r.add_label (canvas::range_t (20, 25),
+ styled_string (sm, "label 3"),
+ style::id_plain,
+ x_ruler::label_kind::TEXT_WITH_BORDER);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ "|~+~| |~+~| |~+~|\n"
+ " | | |\n"
+ " | label 2 +---+---+\n"
+ "+-+-----+ |label 3|\n"
+ "|label 1| +-------+\n"
+ "+-------+\n");
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ "├─┬─┤ ├─┬─┤ ├─┬─┤\n"
+ " │ │ │\n"
+ " │ label 2 ╭───┴───╮\n"
+ "╭─┴─────╮ │label 3│\n"
+ "│label 1│ ╰───────╯\n"
+ "╰───────╯\n");
+ }
+ {
+ x_ruler r (x_ruler::label_dir::ABOVE);
+ r.add_label (canvas::range_t (0, 5),
+ styled_string (sm, "label 1"),
+ style::id_plain,
+ x_ruler::label_kind::TEXT_WITH_BORDER);
+ r.add_label (canvas::range_t (10, 15),
+ styled_string (sm, "label 2"),
+ style::id_plain);
+ r.add_label (canvas::range_t (20, 25),
+ styled_string (sm, "label 3"),
+ style::id_plain,
+ x_ruler::label_kind::TEXT_WITH_BORDER);
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ "+-------+\n"
+ "|label 1| +-------+\n"
+ "+-+-----+ |label 3|\n"
+ " | label 2 +---+---+\n"
+ " | | |\n"
+ "|~+~| |~+~| |~+~|\n");
+ ASSERT_X_RULER_STREQ
+ (r, unicode_theme (), sm, true,
+ "╭───────╮\n"
+ "│label 1│ ╭───────╮\n"
+ "╰─┬─────╯ │label 3│\n"
+ " │ label 2 ╰───┬───╯\n"
+ " │ │ │\n"
+ "├─┴─┤ ├─┴─┤ ├─┴─┤\n");
+ }
+}
+
+static void
+test_emoji ()
+{
+ style_manager sm;
+
+ styled_string s;
+ s.append (styled_string (0x26A0, /* U+26A0 WARNING SIGN. */
+ true));
+ s.append (styled_string (sm, " "));
+ s.append (styled_string (sm, "this is a warning"));
+
+ x_ruler r (x_ruler::label_dir::BELOW);
+ r.add_label (canvas::range_t (0, 5),
+ std::move (s),
+ style::id_plain,
+ x_ruler::label_kind::TEXT_WITH_BORDER);
+
+ ASSERT_X_RULER_STREQ
+ (r, ascii_theme (), sm, true,
+ "|~+~|\n"
+ " |\n"
+ "+-+------------------+\n"
+ "|⚠️ this is a warning|\n"
+ "+--------------------+\n");
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_ruler_cc_tests ()
+{
+ test_single ();
+ test_single_above ();
+ test_multiple_contiguous ();
+ test_multiple_contiguous_above ();
+ test_multiple_contiguous_abutting_labels ();
+ test_multiple_contiguous_overlapping_labels ();
+ test_abutting_left_border ();
+ test_too_long_to_consolidate_vertically ();
+ test_abutting_neighbor ();
+ test_gaps ();
+ test_styled ();
+ test_borders ();
+ test_emoji ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/ruler.h b/gcc/text-art/ruler.h
new file mode 100644
index 0000000..31f5354
--- /dev/null
+++ b/gcc/text-art/ruler.h
@@ -0,0 +1,125 @@
+/* Classes for printing labelled rulers.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_RULER_H
+#define GCC_TEXT_ART_RULER_H
+
+#include "text-art/canvas.h"
+
+namespace text_art {
+
+/* A way to annotate a series of ranges of canvas coordinates
+ with text labels either above or, in this example, below:
+ ├───────┬───────┼───────┬───────┼───────┬───────┤
+ │ │ │
+ label A label B label C
+ with logic to ensure that the text labels don't overlap
+ when printed. */
+
+class x_ruler
+{
+ public:
+ enum class label_dir { ABOVE, BELOW };
+ enum class label_kind
+ {
+ TEXT,
+ TEXT_WITH_BORDER
+ };
+
+ x_ruler (label_dir dir)
+ : m_label_dir (dir),
+ m_size (canvas::size_t (0, 0)),
+ m_has_layout (false)
+ {}
+
+ void add_label (const canvas::range_t &r,
+ styled_string text,
+ style::id_t style_id,
+ label_kind kind = label_kind::TEXT);
+
+ canvas::size_t get_size ()
+ {
+ ensure_layout ();
+ return m_size;
+ }
+
+ void paint_to_canvas (canvas &canvas,
+ canvas::coord_t offset,
+ const theme &theme);
+
+ void debug (const style_manager &sm);
+
+ private:
+ /* A particular label within an x_ruler.
+ Consider e.g.:
+
+ # x: 01234567890123456789012345678901234567890123456789
+ # y: 0: ├───────┬───────┼───────┬───────┼───────┬───────┤
+ # 1: │ │ │
+ # 2: label A label B label C
+ #
+
+ Then "label A" is:
+
+ # m_connector_x == 8
+ # V
+ # x: 0123456789012
+ # y: 0: ┬
+ # 1: │
+ # 2: label A
+ # x: 0123456789012
+ # ^
+ # m_text_coord.x == 6
+
+ and m_text_coord is (2, 6).
+ The y cooordinates are stored with respect to label_dir::BELOW;
+ for label_dir::ABOVE we flip them when painting the ruler. */
+ class label
+ {
+ friend class x_ruler;
+ public:
+ label (const canvas::range_t &range, styled_string text, style::id_t style_id,
+ label_kind kind);
+
+ bool operator< (const label &other) const;
+
+ private:
+ canvas::range_t m_range;
+ styled_string m_text;
+ style::id_t m_style_id;
+ label_kind m_kind;
+ canvas::rect_t m_text_rect; // includes any border
+ int m_connector_x;
+ };
+
+ void ensure_layout ();
+ void update_layout ();
+ int get_canvas_y (int rel_y) const;
+
+ label_dir m_label_dir;
+ std::vector<label> m_labels;
+ canvas::size_t m_size;
+ bool m_has_layout = false;
+
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_RULER_H */
diff --git a/gcc/text-art/selftests.cc b/gcc/text-art/selftests.cc
new file mode 100644
index 0000000..25d81c1
--- /dev/null
+++ b/gcc/text-art/selftests.cc
@@ -0,0 +1,78 @@
+/* Selftests for text art.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "selftest.h"
+#include "pretty-print.h"
+#include "text-art/selftests.h"
+#include "text-art/canvas.h"
+
+#if CHECKING_P
+
+/* Run all tests, aborting if any fail. */
+
+void
+selftest::text_art_tests ()
+{
+ text_art_style_cc_tests ();
+ text_art_styled_string_cc_tests ();
+
+ text_art_box_drawing_cc_tests ();
+ text_art_canvas_cc_tests ();
+ text_art_ruler_cc_tests ();
+ text_art_table_cc_tests ();
+ text_art_widget_cc_tests ();
+}
+
+/* Implementation detail of ASSERT_CANVAS_STREQ. */
+
+void
+selftest::assert_canvas_streq (const location &loc,
+ const text_art::canvas &canvas,
+ pretty_printer *pp,
+ const char *expected_str)
+{
+ canvas.print_to_pp (pp);
+ if (0)
+ fprintf (stderr, "%s\n", pp_formatted_text (pp));
+ ASSERT_STREQ_AT (loc, pp_formatted_text (pp), expected_str);
+}
+
+/* Implementation detail of ASSERT_CANVAS_STREQ. */
+
+void
+selftest::assert_canvas_streq (const location &loc,
+ const text_art::canvas &canvas,
+ bool styled,
+ const char *expected_str)
+{
+ pretty_printer pp;
+ if (styled)
+ {
+ pp_show_color (&pp) = true;
+ pp.url_format = URL_FORMAT_DEFAULT;
+ }
+ assert_canvas_streq (loc, canvas, &pp, expected_str);
+}
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/selftests.h b/gcc/text-art/selftests.h
new file mode 100644
index 0000000..ba29f69
--- /dev/null
+++ b/gcc/text-art/selftests.h
@@ -0,0 +1,62 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_SELFTESTS_H
+#define GCC_TEXT_ART_SELFTESTS_H
+
+#if CHECKING_P
+
+namespace text_art {
+ class canvas;
+} // namespace text_art
+
+namespace selftest {
+
+extern void text_art_box_drawing_cc_tests ();
+extern void text_art_canvas_cc_tests ();
+extern void text_art_ruler_cc_tests ();
+extern void text_art_style_cc_tests ();
+extern void text_art_styled_string_cc_tests ();
+extern void text_art_table_cc_tests ();
+extern void text_art_widget_cc_tests ();
+
+extern void text_art_tests ();
+
+extern void assert_canvas_streq (const location &loc,
+ const text_art::canvas &canvas,
+ pretty_printer *pp,
+ const char *expected_str);
+extern void assert_canvas_streq (const location &loc,
+ const text_art::canvas &canvas,
+ bool styled,
+ const char *expected_str);
+
+#define ASSERT_CANVAS_STREQ(CANVAS, STYLED, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ assert_canvas_streq ((SELFTEST_LOCATION), \
+ (CANVAS), \
+ (STYLED), \
+ (EXPECTED_STR)); \
+ SELFTEST_END_STMT
+
+} /* end of namespace selftest. */
+
+#endif /* #if CHECKING_P */
+
+#endif /* GCC_TEXT_ART_SELFTESTS_H */
diff --git a/gcc/text-art/style.cc b/gcc/text-art/style.cc
new file mode 100644
index 0000000..85ad49e
--- /dev/null
+++ b/gcc/text-art/style.cc
@@ -0,0 +1,633 @@
+/* Classes for styling text cells (color, URLs).
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_ALGORITHM
+#define INCLUDE_MEMORY
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "make-unique.h"
+#include "pretty-print.h"
+#include "intl.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/types.h"
+#include "color-macros.h"
+
+using namespace text_art;
+
+/* class text_art::style. */
+
+style &
+style::set_style_url (const char *url)
+{
+ m_url.clear ();
+ while (*url)
+ m_url.push_back (*(url++));
+ return *this;
+}
+
+/* class text_art::style::color. */
+
+bool
+style::color::operator== (const style::color &other) const
+{
+ if (m_kind != other.m_kind)
+ return false;
+ switch (m_kind)
+ {
+ default:
+ gcc_unreachable ();
+ case kind::NAMED:
+ return (u.m_named.m_name == other.u.m_named.m_name
+ && u.m_named.m_bright == other.u.m_named.m_bright);
+ case kind::BITS_8:
+ return u.m_8bit == other.u.m_8bit;
+ case kind::BITS_24:
+ return (u.m_24bit.r == other.u.m_24bit.r
+ && u.m_24bit.g == other.u.m_24bit.g
+ && u.m_24bit.b == other.u.m_24bit.b);
+ }
+}
+
+static void
+ensure_separator (pretty_printer *pp, bool &need_separator)
+{
+ if (need_separator)
+ pp_string (pp, COLOR_SEPARATOR);
+ need_separator = true;
+}
+
+void
+style::color::print_sgr (pretty_printer *pp,
+ bool fg,
+ bool &need_separator) const
+{
+ switch (m_kind)
+ {
+ default:
+ gcc_unreachable ();
+ case kind::NAMED:
+ {
+ static const char * const fg_normal[] = {"", // reset, for DEFAULT
+ COLOR_FG_BLACK,
+ COLOR_FG_RED,
+ COLOR_FG_GREEN,
+ COLOR_FG_YELLOW,
+ COLOR_FG_BLUE,
+ COLOR_FG_MAGENTA,
+ COLOR_FG_CYAN,
+ COLOR_FG_WHITE};
+ static const char * const fg_bright[] = {"", // reset, for DEFAULT
+ COLOR_FG_BRIGHT_BLACK,
+ COLOR_FG_BRIGHT_RED,
+ COLOR_FG_BRIGHT_GREEN,
+ COLOR_FG_BRIGHT_YELLOW,
+ COLOR_FG_BRIGHT_BLUE,
+ COLOR_FG_BRIGHT_MAGENTA,
+ COLOR_FG_BRIGHT_CYAN,
+ COLOR_FG_BRIGHT_WHITE};
+ static const char * const bg_normal[] = {"", // reset, for DEFAULT
+ COLOR_BG_BLACK,
+ COLOR_BG_RED,
+ COLOR_BG_GREEN,
+ COLOR_BG_YELLOW,
+ COLOR_BG_BLUE,
+ COLOR_BG_MAGENTA,
+ COLOR_BG_CYAN,
+ COLOR_BG_WHITE};
+ static const char * const bg_bright[] = {"", // reset, for DEFAULT
+ COLOR_BG_BRIGHT_BLACK,
+ COLOR_BG_BRIGHT_RED,
+ COLOR_BG_BRIGHT_GREEN,
+ COLOR_BG_BRIGHT_YELLOW,
+ COLOR_BG_BRIGHT_BLUE,
+ COLOR_BG_BRIGHT_MAGENTA,
+ COLOR_BG_BRIGHT_CYAN,
+ COLOR_BG_BRIGHT_WHITE};
+ STATIC_ASSERT (ARRAY_SIZE (fg_normal) == ARRAY_SIZE (fg_bright));
+ STATIC_ASSERT (ARRAY_SIZE (fg_normal) == ARRAY_SIZE (bg_normal));
+ STATIC_ASSERT (ARRAY_SIZE (fg_normal) == ARRAY_SIZE (bg_bright));
+ gcc_assert ((size_t)u.m_named.m_name < ARRAY_SIZE (fg_normal));
+ const char *const *arr;
+ if (fg)
+ arr = u.m_named.m_bright ? fg_bright : fg_normal;
+ else
+ arr = u.m_named.m_bright ? bg_bright : bg_normal;
+ const char *str = arr[(size_t)u.m_named.m_name];
+ if (strlen (str) > 0)
+ {
+ ensure_separator (pp, need_separator);
+ pp_string (pp, str);
+ }
+ }
+ break;
+ case kind::BITS_8:
+ {
+ ensure_separator (pp, need_separator);
+ if (fg)
+ pp_string (pp, "38");
+ else
+ pp_string (pp, "48");
+ pp_printf (pp, ";5;%i", (int)u.m_8bit);
+ }
+ break;
+ case kind::BITS_24:
+ {
+ ensure_separator (pp, need_separator);
+ if (fg)
+ pp_string (pp, "38");
+ else
+ pp_string (pp, "48");
+ pp_printf (pp, ";2;%i;%i;%i",
+ (int)u.m_24bit.r,
+ (int)u.m_24bit.g,
+ (int)u.m_24bit.b);
+ }
+ break;
+ }
+}
+
+/* class text_art::style. */
+
+/* See https://www.ecma-international.org/wp-content/uploads/ECMA-48_5th_edition_june_1991.pdf
+ GRCM - GRAPHIC RENDITION COMBINATION MODE can be "REPLACING" or
+ "CUMULATIVE", which affects whether we need to respecify all attributes
+ at each SGR, or can accumulate them. Looks like we can't rely on the value
+ of this, so we have to emit a single SGR for all changes, with a "0" reset
+ at the front, forcing it to be effectively replacing. */
+
+void
+style::print_changes (pretty_printer *pp,
+ const style &old_style,
+ const style &new_style)
+{
+ if (pp_show_color (pp))
+ {
+ bool needs_sgr = ((old_style.m_bold != new_style.m_bold)
+ || (old_style.m_underscore != new_style.m_underscore)
+ || (old_style.m_blink != new_style.m_blink)
+ || (old_style.m_fg_color != new_style.m_fg_color)
+ || (old_style.m_bg_color != new_style.m_bg_color));
+ if (needs_sgr)
+ {
+ bool emit_reset = (old_style.m_bold
+ || new_style.m_bold
+ || old_style.m_underscore
+ || new_style.m_underscore
+ || old_style.m_blink
+ || new_style.m_blink);
+ bool need_separator = false;
+
+ pp_string (pp, SGR_START);
+ if (emit_reset)
+ {
+ pp_string (pp, COLOR_NONE);
+ need_separator = true;
+ }
+ if (new_style.m_bold)
+ {
+ gcc_assert (emit_reset);
+ ensure_separator (pp, need_separator);
+ pp_string (pp, COLOR_BOLD);
+ }
+ if (new_style.m_underscore)
+ {
+ gcc_assert (emit_reset);
+ ensure_separator (pp, need_separator);
+ pp_string (pp, COLOR_UNDERSCORE);
+ }
+ if (new_style.m_blink)
+ {
+ gcc_assert (emit_reset);
+ ensure_separator (pp, need_separator);
+ pp_string (pp, COLOR_BLINK);
+ }
+ new_style.m_fg_color.print_sgr (pp, true, need_separator);
+ new_style.m_bg_color.print_sgr (pp, false, need_separator);
+ pp_string (pp, SGR_END);
+ }
+ }
+
+ if (old_style.m_url != new_style.m_url)
+ {
+ if (!old_style.m_url.empty ())
+ pp_end_url (pp);
+ if (pp->url_format != URL_FORMAT_NONE
+ && !new_style.m_url.empty ())
+ {
+ /* Adapted from pp_begin_url, but encoding the
+ chars to UTF-8 on the fly, rather than converting
+ to a buffer. */
+ pp_string (pp, "\33]8;;");
+ for (auto ch : new_style.m_url)
+ pp_unicode_character (pp, ch);
+ switch (pp->url_format)
+ {
+ default:
+ case URL_FORMAT_NONE:
+ gcc_unreachable ();
+ case URL_FORMAT_ST:
+ pp_string (pp, "\33\\");
+ break;
+ case URL_FORMAT_BEL:
+ pp_string (pp, "\a");
+ break;
+ }
+ }
+ }
+}
+
+/* class text_art::style_manager. */
+
+style_manager::style_manager ()
+{
+ // index 0 will be the default style
+ m_styles.push_back (style ());
+}
+
+style::id_t
+style_manager::get_or_create_id (const style &s)
+{
+ // For now, linear search
+ std::vector<style>::iterator existing
+ (std::find (m_styles.begin (), m_styles.end (), s));
+
+ /* If found, return index of slot. */
+ if (existing != m_styles.end ())
+ return std::distance (m_styles.begin (), existing);
+
+ /* Not found. */
+
+ /* styled_str uses 7 bits for style information, so we can only support
+ up to 128 different style combinations.
+ Gracefully fail by turning off styling when this limit is reached. */
+ if (m_styles.size () >= 127)
+ return 0;
+
+ m_styles.push_back (s);
+ return m_styles.size () - 1;
+}
+
+void
+style_manager::print_any_style_changes (pretty_printer *pp,
+ style::id_t old_id,
+ style::id_t new_id) const
+{
+ gcc_assert (pp);
+ if (old_id == new_id)
+ return;
+
+ const style &old_style = m_styles[old_id];
+ const style &new_style = m_styles[new_id];
+ gcc_assert (!(old_style == new_style));
+ style::print_changes (pp, old_style, new_style);
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+void
+assert_style_change_streq (const location &loc,
+ const style &old_style,
+ const style &new_style,
+ const char *expected_str)
+{
+ pretty_printer pp;
+ pp_show_color (&pp) = true;
+ style::print_changes (&pp, old_style, new_style);
+ ASSERT_STREQ_AT (loc, pp_formatted_text (&pp), expected_str);
+}
+
+#define ASSERT_STYLE_CHANGE_STREQ(OLD_STYLE, NEW_STYLE, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ assert_style_change_streq ((SELFTEST_LOCATION), \
+ (OLD_STYLE), \
+ (NEW_STYLE), \
+ (EXPECTED_STR)); \
+ SELFTEST_END_STMT
+
+static void
+test_bold ()
+{
+ style_manager sm;
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style plain;
+ ASSERT_EQ (sm.get_or_create_id (plain), 0);
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style bold;
+ bold.m_bold = true;
+
+ ASSERT_EQ (sm.get_or_create_id (bold), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ ASSERT_EQ (sm.get_or_create_id (bold), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+
+ ASSERT_STYLE_CHANGE_STREQ (plain, bold, "\33[00;01m\33[K");
+ ASSERT_STYLE_CHANGE_STREQ (bold, plain, "\33[00m\33[K");
+}
+
+static void
+test_underscore ()
+{
+ style_manager sm;
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style plain;
+ ASSERT_EQ (sm.get_or_create_id (plain), 0);
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style underscore;
+ underscore.m_underscore = true;
+
+ ASSERT_EQ (sm.get_or_create_id (underscore), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ ASSERT_EQ (sm.get_or_create_id (underscore), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+
+ ASSERT_STYLE_CHANGE_STREQ (plain, underscore, "\33[00;04m\33[K");
+ ASSERT_STYLE_CHANGE_STREQ (underscore, plain, "\33[00m\33[K");
+}
+
+static void
+test_blink ()
+{
+ style_manager sm;
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style plain;
+ ASSERT_EQ (sm.get_or_create_id (plain), 0);
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style blink;
+ blink.m_blink = true;
+
+ ASSERT_EQ (sm.get_or_create_id (blink), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ ASSERT_EQ (sm.get_or_create_id (blink), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+
+ ASSERT_STYLE_CHANGE_STREQ (plain, blink, "\33[00;05m\33[K");
+ ASSERT_STYLE_CHANGE_STREQ (blink, plain, "\33[00m\33[K");
+}
+
+#define ASSERT_NAMED_COL_STREQ(NAMED_COLOR, FG, BRIGHT, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ { \
+ style plain; \
+ style s; \
+ if (FG) \
+ s.m_fg_color = style::color ((NAMED_COLOR), (BRIGHT)); \
+ else \
+ s.m_bg_color = style::color ((NAMED_COLOR), (BRIGHT)); \
+ assert_style_change_streq ((SELFTEST_LOCATION), \
+ plain, \
+ s, \
+ (EXPECTED_STR)); \
+ } \
+ SELFTEST_END_STMT
+
+static void
+test_named_colors ()
+{
+ /* Foreground colors. */
+ {
+ const bool fg = true;
+ {
+ const bool bright = false;
+ ASSERT_NAMED_COL_STREQ (style::named_color::DEFAULT, fg, bright, "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLACK, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::RED, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::GREEN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::YELLOW, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLUE, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::MAGENTA, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::CYAN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::WHITE, fg, bright,
+ "");
+ }
+ {
+ const bool bright = true;
+ ASSERT_NAMED_COL_STREQ (style::named_color::DEFAULT, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLACK, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::RED, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::GREEN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::YELLOW, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLUE, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::MAGENTA, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::CYAN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::WHITE, fg, bright,
+ "");
+ }
+ }
+
+ /* Background colors. */
+ {
+ const bool fg = false;
+ {
+ const bool bright = false;
+ ASSERT_NAMED_COL_STREQ (style::named_color::DEFAULT, fg, bright, "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLACK, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::RED, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::GREEN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::YELLOW, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLUE, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::MAGENTA, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::CYAN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::WHITE, fg, bright,
+ "");
+ }
+ {
+ const bool bright = true;
+ ASSERT_NAMED_COL_STREQ (style::named_color::DEFAULT, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLACK, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::RED, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::GREEN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::YELLOW, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::BLUE, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::MAGENTA, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::CYAN, fg, bright,
+ "");
+ ASSERT_NAMED_COL_STREQ (style::named_color::WHITE, fg, bright,
+ "");
+ }
+ }
+}
+
+#define ASSERT_8_BIT_COL_STREQ(COL_VAL, FG, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ { \
+ style plain; \
+ style s; \
+ if (FG) \
+ s.m_fg_color = style::color (COL_VAL); \
+ else \
+ s.m_bg_color = style::color (COL_VAL); \
+ assert_style_change_streq ((SELFTEST_LOCATION), \
+ plain, \
+ s, \
+ (EXPECTED_STR)); \
+ } \
+ SELFTEST_END_STMT
+
+static void
+test_8_bit_colors ()
+{
+ /* Foreground colors. */
+ {
+ const bool fg = true;
+ /* 0-15: standard and high-intensity standard colors. */
+ ASSERT_8_BIT_COL_STREQ (0, fg, "");
+ ASSERT_8_BIT_COL_STREQ (15, fg, "");
+ /* 16-231: 6x6x6 color cube. */
+ ASSERT_8_BIT_COL_STREQ (16, fg, "");
+ ASSERT_8_BIT_COL_STREQ (231, fg, "");
+ /* 232-255: grayscale. */
+ ASSERT_8_BIT_COL_STREQ (232, fg, "");
+ ASSERT_8_BIT_COL_STREQ (255, fg, "");
+ }
+ /* Background colors. */
+ {
+ const bool fg = false;
+ /* 0-15: standard and high-intensity standard colors. */
+ ASSERT_8_BIT_COL_STREQ (0, fg, "");
+ ASSERT_8_BIT_COL_STREQ (15, fg, "");
+ /* 16-231: 6x6x6 color cube. */
+ ASSERT_8_BIT_COL_STREQ (16, fg, "");
+ ASSERT_8_BIT_COL_STREQ (231, fg, "");
+ /* 232-255: grayscale. */
+ ASSERT_8_BIT_COL_STREQ (232, fg, "");
+ ASSERT_8_BIT_COL_STREQ (255, fg, "");
+ }
+}
+
+#define ASSERT_24_BIT_COL_STREQ(R, G, B, FG, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ { \
+ style plain; \
+ style s; \
+ if (FG) \
+ s.m_fg_color = style::color ((R), (G), (B)); \
+ else \
+ s.m_bg_color = style::color ((R), (G), (B)); \
+ assert_style_change_streq ((SELFTEST_LOCATION), \
+ plain, \
+ s, \
+ (EXPECTED_STR)); \
+ } \
+ SELFTEST_END_STMT
+
+static void
+test_24_bit_colors ()
+{
+ /* Foreground colors. */
+ {
+ const bool fg = true;
+ // #F3FAF2:
+ ASSERT_24_BIT_COL_STREQ (0xf3, 0xfa, 0xf2, fg,
+ "");
+ }
+ /* Background colors. */
+ {
+ const bool fg = false;
+ // #FDF7E7
+ ASSERT_24_BIT_COL_STREQ (0xfd, 0xf7, 0xe7, fg,
+ "");
+ }
+}
+
+static void
+test_style_combinations ()
+{
+ style_manager sm;
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style plain;
+ ASSERT_EQ (sm.get_or_create_id (plain), 0);
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ style bold;
+ bold.m_bold = true;
+
+ ASSERT_EQ (sm.get_or_create_id (bold), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ ASSERT_EQ (sm.get_or_create_id (bold), 1);
+ ASSERT_EQ (sm.get_num_styles (), 2);
+
+ style magenta_on_blue;
+ magenta_on_blue.m_fg_color = style::named_color::MAGENTA;
+ magenta_on_blue.m_bg_color = style::named_color::BLUE;
+ ASSERT_EQ (sm.get_or_create_id (magenta_on_blue), 2);
+ ASSERT_EQ (sm.get_num_styles (), 3);
+ ASSERT_EQ (sm.get_or_create_id (magenta_on_blue), 2);
+ ASSERT_EQ (sm.get_num_styles (), 3);
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_style_cc_tests ()
+{
+ test_bold ();
+ test_underscore ();
+ test_blink ();
+ test_named_colors ();
+ test_8_bit_colors ();
+ test_24_bit_colors ();
+ test_style_combinations ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/styled-string.cc b/gcc/text-art/styled-string.cc
new file mode 100644
index 0000000..a0cc187
--- /dev/null
+++ b/gcc/text-art/styled-string.cc
@@ -0,0 +1,1108 @@
+/* Implementation of text_art::styled_string.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_MEMORY
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "make-unique.h"
+#include "pretty-print.h"
+#include "intl.h"
+#include "diagnostic.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/types.h"
+#include "color-macros.h"
+
+using namespace text_art;
+
+namespace {
+
+/* Support class for parsing text containing escape codes.
+ See e.g. https://en.wikipedia.org/wiki/ANSI_escape_code
+ We only support the codes that pretty-print.cc can generate. */
+
+class escape_code_parser
+{
+public:
+ escape_code_parser (style_manager &sm,
+ std::vector<styled_unichar> &out)
+ : m_sm (sm),
+ m_out (out),
+ m_cur_style_obj (),
+ m_cur_style_id (style::id_plain),
+ m_state (state::START)
+ {
+ }
+
+ void on_char (cppchar_t ch)
+ {
+ switch (m_state)
+ {
+ default:
+ gcc_unreachable ();
+ case state::START:
+ if (ch == '\033')
+ {
+ /* The start of an escape sequence. */
+ m_state = state::AFTER_ESC;
+ return;
+ }
+ break;
+ case state::AFTER_ESC:
+ if (ch == '[')
+ {
+ /* ESC [ is a Control Sequence Introducer. */
+ m_state = state::CS_PARAMETER_BYTES;
+ return;
+ }
+ else if (ch == ']')
+ {
+ /* ESC ] is an Operating System Command. */
+ m_state = state::WITHIN_OSC;
+ return;
+ }
+ break;
+ case state::CS_PARAMETER_BYTES:
+ if (parameter_byte_p (ch))
+ {
+ m_parameter_bytes.push_back ((char)ch);
+ return;
+ }
+ else if (intermediate_byte_p (ch))
+ {
+ m_intermediate_bytes.push_back ((char)ch);
+ m_state = state::CS_INTERMEDIATE_BYTES;
+ return;
+ }
+ else if (final_byte_p (ch))
+ {
+ on_final_csi_char (ch);
+ return;
+ }
+ break;
+ case state::CS_INTERMEDIATE_BYTES:
+ /* Expect zero or more intermediate bytes. */
+ if (intermediate_byte_p (ch))
+ {
+ m_intermediate_bytes.push_back ((char)ch);
+ return;
+ }
+ else if (final_byte_p (ch))
+ {
+ on_final_csi_char (ch);
+ return;
+ }
+ break;
+ case state::WITHIN_OSC:
+ /* Accumulate chars into m_osc_string, until we see an ST or a BEL. */
+ {
+ /* Check for ESC \, the String Terminator (aka "ST"). */
+ if (ch == '\\'
+ && m_osc_string.size () > 0
+ && m_osc_string.back () == '\033')
+ {
+ m_osc_string.pop_back ();
+ on_final_osc_char ();
+ return;
+ }
+ else if (ch == '\a')
+ {
+ // BEL
+ on_final_osc_char ();
+ return;
+ }
+ m_osc_string.push_back (ch);
+ return;
+ }
+ break;
+ }
+
+ /* Test of handling U+FE0F VARIATION SELECTOR-16 to select the emoji
+ variation for the previous character. */
+ if (ch == 0xFE0F)
+ {
+ if (m_out.size () > 0)
+ m_out.back ().set_emoji_variant ();
+ return;
+ }
+
+ if (cpp_is_combining_char (ch))
+ {
+ if (m_out.size () > 0)
+ {
+ m_out.back ().add_combining_char (ch);
+ return;
+ }
+ }
+ /* By default, add the char. */
+ m_out.push_back (styled_unichar (ch, false, m_cur_style_id));
+ }
+
+private:
+ void on_final_csi_char (cppchar_t ch)
+ {
+ switch (ch)
+ {
+ default:
+ /* Unrecognized. */
+ break;
+ case 'm':
+ {
+ /* SGR control sequence. */
+ if (m_parameter_bytes.empty ())
+ reset_style ();
+ std::vector<int> params (params_from_decimal ());
+ for (auto iter = params.begin (); iter != params.end (); )
+ {
+ const int param = *iter;
+ switch (param)
+ {
+ default:
+ /* Unrecognized SGR parameter. */
+ break;
+ case 0:
+ reset_style ();
+ break;
+ case 1:
+ set_style_bold ();
+ break;
+ case 4:
+ set_style_underscore ();
+ break;
+ case 5:
+ set_style_blink ();
+ break;
+
+ /* Named foreground colors. */
+ case 30:
+ set_style_fg_color (style::named_color::BLACK);
+ break;
+ case 31:
+ set_style_fg_color (style::named_color::RED);
+ break;
+ case 32:
+ set_style_fg_color (style::named_color::GREEN);
+ break;
+ case 33:
+ set_style_fg_color (style::named_color::YELLOW);
+ break;
+ case 34:
+ set_style_fg_color (style::named_color::BLUE);
+ break;
+ case 35:
+ set_style_fg_color (style::named_color::MAGENTA);
+ break;
+ case 36:
+ set_style_fg_color (style::named_color::CYAN);
+ break;
+ case 37:
+ set_style_fg_color (style::named_color::WHITE);
+ break;
+
+ /* 8-bit and 24-bit color */
+ case 38:
+ case 48:
+ {
+ const bool fg = (param == 38);
+ iter++;
+ if (iter != params.end ())
+ switch (*(iter++))
+ {
+ default:
+ break;
+ case 5:
+ /* 8-bit color. */
+ if (iter != params.end ())
+ {
+ const uint8_t col = *(iter++);
+ if (fg)
+ set_style_fg_color (style::color (col));
+ else
+ set_style_bg_color (style::color (col));
+ }
+ continue;
+ case 2:
+ /* 24-bit color. */
+ if (iter != params.end ())
+ {
+ const uint8_t r = *(iter++);
+ if (iter != params.end ())
+ {
+ const uint8_t g = *(iter++);
+ if (iter != params.end ())
+ {
+ const uint8_t b = *(iter++);
+ if (fg)
+ set_style_fg_color (style::color (r,
+ g,
+ b));
+ else
+ set_style_bg_color (style::color (r,
+ g,
+ b));
+ }
+ }
+ }
+ continue;
+ }
+ continue;
+ }
+ break;
+
+ /* Named background colors. */
+ case 40:
+ set_style_bg_color (style::named_color::BLACK);
+ break;
+ case 41:
+ set_style_bg_color (style::named_color::RED);
+ break;
+ case 42:
+ set_style_bg_color (style::named_color::GREEN);
+ break;
+ case 43:
+ set_style_bg_color (style::named_color::YELLOW);
+ break;
+ case 44:
+ set_style_bg_color (style::named_color::BLUE);
+ break;
+ case 45:
+ set_style_bg_color (style::named_color::MAGENTA);
+ break;
+ case 46:
+ set_style_bg_color (style::named_color::CYAN);
+ break;
+ case 47:
+ set_style_bg_color (style::named_color::WHITE);
+ break;
+
+ /* Named foreground colors, bright. */
+ case 90:
+ set_style_fg_color (style::color (style::named_color::BLACK,
+ true));
+ break;
+ case 91:
+ set_style_fg_color (style::color (style::named_color::RED,
+ true));
+ break;
+ case 92:
+ set_style_fg_color (style::color (style::named_color::GREEN,
+ true));
+ break;
+ case 93:
+ set_style_fg_color (style::color (style::named_color::YELLOW,
+ true));
+ break;
+ case 94:
+ set_style_fg_color (style::color (style::named_color::BLUE,
+ true));
+ break;
+ case 95:
+ set_style_fg_color (style::color (style::named_color::MAGENTA,
+ true));
+ break;
+ case 96:
+ set_style_fg_color (style::color (style::named_color::CYAN,
+ true));
+ break;
+ case 97:
+ set_style_fg_color (style::color (style::named_color::WHITE,
+ true));
+ break;
+
+ /* Named foreground colors, bright. */
+ case 100:
+ set_style_bg_color (style::color (style::named_color::BLACK,
+ true));
+ break;
+ case 101:
+ set_style_bg_color (style::color (style::named_color::RED,
+ true));
+ break;
+ case 102:
+ set_style_bg_color (style::color (style::named_color::GREEN,
+ true));
+ break;
+ case 103:
+ set_style_bg_color (style::color (style::named_color::YELLOW,
+ true));
+ break;
+ case 104:
+ set_style_bg_color (style::color (style::named_color::BLUE,
+ true));
+ break;
+ case 105:
+ set_style_bg_color (style::color (style::named_color::MAGENTA,
+ true));
+ break;
+ case 106:
+ set_style_bg_color (style::color (style::named_color::CYAN,
+ true));
+ break;
+ case 107:
+ set_style_bg_color (style::color (style::named_color::WHITE,
+ true));
+ break;
+ }
+ ++iter;
+ }
+ }
+ break;
+ }
+ m_parameter_bytes.clear ();
+ m_intermediate_bytes.clear ();
+ m_state = state::START;
+ }
+
+ void on_final_osc_char ()
+ {
+ if (!m_osc_string.empty ())
+ {
+ switch (m_osc_string[0])
+ {
+ default:
+ break;
+ case '8':
+ /* Hyperlink support; see:
+ https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
+ We don't support params, so we expect either:
+ (a) "8;;URL" to begin a url (see pp_begin_url), or
+ (b) "8;;" to end a URL (see pp_end_url). */
+ if (m_osc_string.size () >= 3
+ && m_osc_string[1] == ';'
+ && m_osc_string[2] == ';')
+ {
+ set_style_url (m_osc_string.begin () + 3,
+ m_osc_string.end ());
+ }
+ break;
+ }
+ }
+ m_osc_string.clear ();
+ m_state = state::START;
+ }
+
+ std::vector<int> params_from_decimal () const
+ {
+ std::vector<int> result;
+
+ int curr_int = -1;
+ for (auto param_ch : m_parameter_bytes)
+ {
+ if (param_ch >= '0' && param_ch <= '9')
+ {
+ if (curr_int == -1)
+ curr_int = 0;
+ else
+ curr_int *= 10;
+ curr_int += param_ch - '0';
+ }
+ else
+ {
+ if (curr_int != -1)
+ {
+ result.push_back (curr_int);
+ curr_int = -1;
+ }
+ }
+ }
+ if (curr_int != -1)
+ result.push_back (curr_int);
+ return result;
+ }
+
+ void refresh_style_id ()
+ {
+ m_cur_style_id = m_sm.get_or_create_id (m_cur_style_obj);
+ }
+ void reset_style ()
+ {
+ m_cur_style_obj = style ();
+ refresh_style_id ();
+ }
+ void set_style_bold ()
+ {
+ m_cur_style_obj.m_bold = true;
+ refresh_style_id ();
+ }
+ void set_style_underscore ()
+ {
+ m_cur_style_obj.m_underscore = true;
+ refresh_style_id ();
+ }
+ void set_style_blink ()
+ {
+ m_cur_style_obj.m_blink = true;
+ refresh_style_id ();
+ }
+ void set_style_fg_color (style::color color)
+ {
+ m_cur_style_obj.m_fg_color = color;
+ refresh_style_id ();
+ }
+ void set_style_bg_color (style::color color)
+ {
+ m_cur_style_obj.m_bg_color = color;
+ refresh_style_id ();
+ }
+ void set_style_url (std::vector<cppchar_t>::iterator begin,
+ std::vector<cppchar_t>::iterator end)
+ {
+ // The empty string means "no URL"
+ m_cur_style_obj.m_url = std::vector<cppchar_t> (begin, end);
+ refresh_style_id ();
+ }
+
+ static bool parameter_byte_p (cppchar_t ch)
+ {
+ return ch >= 0x30 && ch <= 0x3F;
+ }
+
+ static bool intermediate_byte_p (cppchar_t ch)
+ {
+ return ch >= 0x20 && ch <= 0x2F;
+ }
+
+ static bool final_byte_p (cppchar_t ch)
+ {
+ return ch >= 0x40 && ch <= 0x7E;
+ }
+
+ style_manager &m_sm;
+ std::vector<styled_unichar> &m_out;
+
+ style m_cur_style_obj;
+ style::id_t m_cur_style_id;
+
+ /* Handling of control sequences. */
+ enum class state
+ {
+ START,
+
+ /* After ESC, expecting '['. */
+ AFTER_ESC,
+
+ /* Expecting zero or more parameter bytes, an
+ intermediate byte, or a final byte. */
+ CS_PARAMETER_BYTES,
+
+ /* Expecting zero or more intermediate bytes, or a final byte. */
+ CS_INTERMEDIATE_BYTES,
+
+ /* Within OSC. */
+ WITHIN_OSC
+
+ } m_state;
+ std::vector<char> m_parameter_bytes;
+ std::vector<char> m_intermediate_bytes;
+ std::vector<cppchar_t> m_osc_string;
+};
+
+} // anon namespace
+
+/* class text_art::styled_string. */
+
+/* Construct a styled_string from STR.
+ STR is assumed to be UTF-8 encoded and 0-terminated.
+
+ Parse SGR formatting chars from being in-band (within in the sequence
+ of chars) to being out-of-band, as style elements.
+ We only support parsing the subset of SGR chars that can be emitted
+ by pretty-print.cc */
+
+styled_string::styled_string (style_manager &sm, const char *str)
+: m_chars ()
+{
+ escape_code_parser parser (sm, m_chars);
+
+ /* We don't actually want the display widths here, but
+ it's an easy way to decode UTF-8. */
+ cpp_char_column_policy policy (8, cpp_wcwidth);
+ cpp_display_width_computation dw (str, strlen (str), policy);
+ while (!dw.done ())
+ {
+ cpp_decoded_char decoded_char;
+ dw.process_next_codepoint (&decoded_char);
+
+ if (!decoded_char.m_valid_ch)
+ /* Skip bytes that aren't valid UTF-8. */
+ continue;
+
+ /* Decode SGR formatting. */
+ cppchar_t ch = decoded_char.m_ch;
+ parser.on_char (ch);
+ }
+}
+
+styled_string::styled_string (cppchar_t cppchar, bool emoji)
+{
+ m_chars.push_back (styled_unichar (cppchar, emoji, style::id_plain));
+}
+
+styled_string
+styled_string::from_fmt_va (style_manager &sm,
+ printer_fn format_decoder,
+ const char *fmt,
+ va_list *args)
+{
+ text_info text;
+ text.err_no = errno;
+ text.args_ptr = args;
+ text.format_spec = fmt;
+ pretty_printer pp;
+ pp_show_color (&pp) = true;
+ pp.url_format = URL_FORMAT_DEFAULT;
+ pp_format_decoder (&pp) = format_decoder;
+ pp_format (&pp, &text);
+ pp_output_formatted_text (&pp);
+ styled_string result (sm, pp_formatted_text (&pp));
+ return result;
+}
+
+styled_string
+styled_string::from_fmt (style_manager &sm,
+ printer_fn format_decoder,
+ const char *fmt, ...)
+{
+ va_list ap;
+ va_start (ap, fmt);
+ styled_string result = from_fmt_va (sm, format_decoder, fmt, &ap);
+ va_end (ap);
+ return result;
+}
+
+int
+styled_string::calc_canvas_width () const
+{
+ int result = 0;
+ for (auto ch : m_chars)
+ result += ch.get_canvas_width ();
+ return result;
+}
+
+void
+styled_string::append (const styled_string &suffix)
+{
+ m_chars.insert<std::vector<styled_unichar>::const_iterator> (m_chars.end (),
+ suffix.begin (),
+ suffix.end ());
+}
+
+void
+styled_string::set_url (style_manager &sm, const char *url)
+{
+ for (auto& ch : m_chars)
+ {
+ const style &existing_style = sm.get_style (ch.get_style_id ());
+ style with_url (existing_style);
+ with_url.set_style_url (url);
+ ch.m_style_id = sm.get_or_create_id (with_url);
+ }
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+static void
+test_combining_chars ()
+{
+ /* This really ought to be in libcpp, but we don't have
+ selftests there. */
+ ASSERT_FALSE (cpp_is_combining_char (0));
+ ASSERT_FALSE (cpp_is_combining_char ('a'));
+
+ /* COMBINING BREVE (U+0306). */
+ ASSERT_TRUE (cpp_is_combining_char (0x0306));
+
+ /* U+5B57 CJK UNIFIED IDEOGRAPH-5B57. */
+ ASSERT_FALSE (cpp_is_combining_char (0x5B57));
+
+ /* U+FE0F VARIATION SELECTOR-16. */
+ ASSERT_FALSE (cpp_is_combining_char (0xFE0F));
+}
+
+static void
+test_empty ()
+{
+ style_manager sm;
+ styled_string s (sm, "");
+ ASSERT_EQ (s.size (), 0);
+ ASSERT_EQ (s.calc_canvas_width (), 0);
+}
+
+/* Test of a pure ASCII string with no escape codes. */
+
+static void
+test_simple ()
+{
+ const char *c_str = "hello world!";
+ style_manager sm;
+ styled_string s (sm, c_str);
+ ASSERT_EQ (s.size (), strlen (c_str));
+ ASSERT_EQ (s.calc_canvas_width (), (int)strlen (c_str));
+ for (size_t i = 0; i < strlen (c_str); i++)
+ {
+ ASSERT_EQ (s[i].get_code (), (cppchar_t)c_str[i]);
+ ASSERT_EQ (s[i].get_style_id (), 0);
+ }
+}
+
+/* Test of decoding UTF-8. */
+
+static void
+test_pi_from_utf8 ()
+{
+ /* U+03C0 "GREEK SMALL LETTER PI". */
+ const char * const pi_utf8 = "\xCF\x80";
+
+ style_manager sm;
+ styled_string s (sm, pi_utf8);
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s.calc_canvas_width (), 1);
+ ASSERT_EQ (s[0].get_code (), 0x03c0);
+ ASSERT_EQ (s[0].emoji_variant_p (), false);
+ ASSERT_EQ (s[0].double_width_p (), false);
+ ASSERT_EQ (s[0].get_style_id (), 0);
+}
+
+/* Test of double-width character. */
+
+static void
+test_emoji_from_utf8 ()
+{
+ /* U+1F642 "SLIGHTLY SMILING FACE". */
+ const char * const emoji_utf8 = "\xF0\x9F\x99\x82";
+
+ style_manager sm;
+ styled_string s (sm, emoji_utf8);
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s.calc_canvas_width (), 2);
+ ASSERT_EQ (s[0].get_code (), 0x1f642);
+ ASSERT_EQ (s[0].double_width_p (), true);
+ ASSERT_EQ (s[0].get_style_id (), 0);
+}
+
+/* Test of handling U+FE0F VARIATION SELECTOR-16 to select the emoji
+ variation for the previous character. */
+
+static void
+test_emoji_variant_from_utf8 ()
+{
+ const char * const emoji_utf8
+ = (/* U+26A0 WARNING SIGN. */
+ "\xE2\x9A\xA0"
+ /* U+FE0F VARIATION SELECTOR-16 (emoji variation selector). */
+ "\xEF\xB8\x8F");
+
+ style_manager sm;
+ styled_string s (sm, emoji_utf8);
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s.calc_canvas_width (), 1);
+ ASSERT_EQ (s[0].get_code (), 0x26a0);
+ ASSERT_EQ (s[0].emoji_variant_p (), true);
+ ASSERT_EQ (s[0].double_width_p (), false);
+ ASSERT_EQ (s[0].get_style_id (), 0);
+}
+
+static void
+test_emoji_from_codepoint ()
+{
+ styled_string s ((cppchar_t)0x1f642);
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s.calc_canvas_width (), 2);
+ ASSERT_EQ (s[0].get_code (), 0x1f642);
+ ASSERT_EQ (s[0].double_width_p (), true);
+ ASSERT_EQ (s[0].get_style_id (), 0);
+}
+
+static void
+test_from_mixed_width_utf8 ()
+{
+ /* This UTF-8 string literal is of the form
+ before mojibake after
+ where the Japanese word "mojibake" is written as the following
+ four unicode code points:
+ U+6587 CJK UNIFIED IDEOGRAPH-6587
+ U+5B57 CJK UNIFIED IDEOGRAPH-5B57
+ U+5316 CJK UNIFIED IDEOGRAPH-5316
+ U+3051 HIRAGANA LETTER KE.
+ Each of these is 3 bytes wide when encoded in UTF-8, whereas the
+ "before" and "after" are 1 byte per unicode character. */
+ const char * const mixed_width_utf8
+ = ("before "
+
+ /* U+6587 CJK UNIFIED IDEOGRAPH-6587
+ UTF-8: 0xE6 0x96 0x87
+ C octal escaped UTF-8: \346\226\207. */
+ "\346\226\207"
+
+ /* U+5B57 CJK UNIFIED IDEOGRAPH-5B57
+ UTF-8: 0xE5 0xAD 0x97
+ C octal escaped UTF-8: \345\255\227. */
+ "\345\255\227"
+
+ /* U+5316 CJK UNIFIED IDEOGRAPH-5316
+ UTF-8: 0xE5 0x8C 0x96
+ C octal escaped UTF-8: \345\214\226. */
+ "\345\214\226"
+
+ /* U+3051 HIRAGANA LETTER KE
+ UTF-8: 0xE3 0x81 0x91
+ C octal escaped UTF-8: \343\201\221. */
+ "\343\201\221"
+
+ " after");
+
+ style_manager sm;
+ styled_string s (sm, mixed_width_utf8);
+ ASSERT_EQ (s.size (), 6 + 1 + 4 + 1 + 5);
+ ASSERT_EQ (sm.get_num_styles (), 1);
+
+ // We expect the Japanese characters to be double width.
+ ASSERT_EQ (s.calc_canvas_width (), 6 + 1 + (2 * 4) + 1 + 5);
+
+ ASSERT_EQ (s[0].get_code (), 'b');
+ ASSERT_EQ (s[0].double_width_p (), false);
+ ASSERT_EQ (s[1].get_code (), 'e');
+ ASSERT_EQ (s[2].get_code (), 'f');
+ ASSERT_EQ (s[3].get_code (), 'o');
+ ASSERT_EQ (s[4].get_code (), 'r');
+ ASSERT_EQ (s[5].get_code (), 'e');
+ ASSERT_EQ (s[6].get_code (), ' ');
+ ASSERT_EQ (s[7].get_code (), 0x6587);
+ ASSERT_EQ (s[7].double_width_p (), true);
+ ASSERT_EQ (s[8].get_code (), 0x5B57);
+ ASSERT_EQ (s[9].get_code (), 0x5316);
+ ASSERT_EQ (s[10].get_code (), 0x3051);
+ ASSERT_EQ (s[11].get_code (), ' ');
+ ASSERT_EQ (s[12].get_code (), 'a');
+ ASSERT_EQ (s[13].get_code (), 'f');
+ ASSERT_EQ (s[14].get_code (), 't');
+ ASSERT_EQ (s[15].get_code (), 'e');
+ ASSERT_EQ (s[16].get_code (), 'r');
+
+ ASSERT_EQ (s[0].get_style_id (), 0);
+}
+
+static void
+assert_style_urleq (const location &loc,
+ const style &s,
+ const char *expected_str)
+{
+ ASSERT_EQ_AT (loc, s.m_url.size (), strlen (expected_str));
+ for (size_t i = 0; i < s.m_url.size (); i++)
+ ASSERT_EQ_AT (loc, s.m_url[i], (cppchar_t)expected_str[i]);
+}
+
+#define ASSERT_STYLE_URLEQ(STYLE, EXPECTED_STR) \
+ assert_style_urleq ((SELFTEST_LOCATION), (STYLE), (EXPECTED_STR))
+
+static void
+test_url ()
+{
+ // URL_FORMAT_ST
+ {
+ style_manager sm;
+ styled_string s
+ (sm, "\33]8;;http://example.com\33\\This is a link\33]8;;\33\\");
+ const char *expected = "This is a link";
+ ASSERT_EQ (s.size (), strlen (expected));
+ ASSERT_EQ (s.calc_canvas_width (), (int)strlen (expected));
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ for (size_t i = 0; i < strlen (expected); i++)
+ {
+ ASSERT_EQ (s[i].get_code (), (cppchar_t)expected[i]);
+ ASSERT_EQ (s[i].get_style_id (), 1);
+ }
+ ASSERT_STYLE_URLEQ (sm.get_style (1), "http://example.com");
+ }
+
+ // URL_FORMAT_BEL
+ {
+ style_manager sm;
+ styled_string s
+ (sm, "\33]8;;http://example.com\aThis is a link\33]8;;\a");
+ const char *expected = "This is a link";
+ ASSERT_EQ (s.size (), strlen (expected));
+ ASSERT_EQ (s.calc_canvas_width (), (int)strlen (expected));
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ for (size_t i = 0; i < strlen (expected); i++)
+ {
+ ASSERT_EQ (s[i].get_code (), (cppchar_t)expected[i]);
+ ASSERT_EQ (s[i].get_style_id (), 1);
+ }
+ ASSERT_STYLE_URLEQ (sm.get_style (1), "http://example.com");
+ }
+}
+
+static void
+test_from_fmt ()
+{
+ style_manager sm;
+ styled_string s (styled_string::from_fmt (sm, NULL, "%%i: %i", 42));
+ ASSERT_EQ (s[0].get_code (), '%');
+ ASSERT_EQ (s[1].get_code (), 'i');
+ ASSERT_EQ (s[2].get_code (), ':');
+ ASSERT_EQ (s[3].get_code (), ' ');
+ ASSERT_EQ (s[4].get_code (), '4');
+ ASSERT_EQ (s[5].get_code (), '2');
+ ASSERT_EQ (s.size (), 6);
+ ASSERT_EQ (s.calc_canvas_width (), 6);
+}
+
+static void
+test_from_fmt_qs ()
+{
+ auto_fix_quotes fix_quotes;
+ open_quote = "\xe2\x80\x98";
+ close_quote = "\xe2\x80\x99";
+
+ style_manager sm;
+ styled_string s (styled_string::from_fmt (sm, NULL, "%qs", "msg"));
+ ASSERT_EQ (sm.get_num_styles (), 2);
+ ASSERT_EQ (s[0].get_code (), 0x2018);
+ ASSERT_EQ (s[0].get_style_id (), 0);
+ ASSERT_EQ (s[1].get_code (), 'm');
+ ASSERT_EQ (s[1].get_style_id (), 1);
+ ASSERT_EQ (s[2].get_code (), 's');
+ ASSERT_EQ (s[2].get_style_id (), 1);
+ ASSERT_EQ (s[3].get_code (), 'g');
+ ASSERT_EQ (s[3].get_style_id (), 1);
+ ASSERT_EQ (s[4].get_code (), 0x2019);
+ ASSERT_EQ (s[4].get_style_id (), 0);
+ ASSERT_EQ (s.size (), 5);
+}
+
+// Test of parsing SGR codes.
+
+static void
+test_from_str_with_bold ()
+{
+ style_manager sm;
+ /* This is the result of pp_printf (pp, "%qs", "foo")
+ with auto_fix_quotes. */
+ styled_string s (sm, "`\33[01m\33[Kfoo\33[m\33[K'");
+ ASSERT_EQ (s[0].get_code (), '`');
+ ASSERT_EQ (s[0].get_style_id (), 0);
+ ASSERT_EQ (s[1].get_code (), 'f');
+ ASSERT_EQ (s[1].get_style_id (), 1);
+ ASSERT_EQ (s[2].get_code (), 'o');
+ ASSERT_EQ (s[2].get_style_id (), 1);
+ ASSERT_EQ (s[3].get_code (), 'o');
+ ASSERT_EQ (s[3].get_style_id (), 1);
+ ASSERT_EQ (s[4].get_code (), '\'');
+ ASSERT_EQ (s[4].get_style_id (), 0);
+ ASSERT_EQ (s.size (), 5);
+ ASSERT_TRUE (sm.get_style (1).m_bold);
+}
+
+static void
+test_from_str_with_underscore ()
+{
+ style_manager sm;
+ styled_string s (sm, "\33[04m\33[KA");
+ ASSERT_EQ (s[0].get_code (), 'A');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_TRUE (sm.get_style (1).m_underscore);
+}
+
+static void
+test_from_str_with_blink ()
+{
+ style_manager sm;
+ styled_string s (sm, "\33[05m\33[KA");
+ ASSERT_EQ (s[0].get_code (), 'A');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_TRUE (sm.get_style (1).m_blink);
+}
+
+// Test of parsing SGR codes.
+
+static void
+test_from_str_with_color ()
+{
+ style_manager sm;
+
+ styled_string s (sm,
+ ("0"
+ SGR_SEQ (COLOR_FG_RED)
+ "R"
+ SGR_RESET
+ "2"
+ SGR_SEQ (COLOR_FG_GREEN)
+ "G"
+ SGR_RESET
+ "4"));
+ ASSERT_EQ (s.size (), 5);
+ ASSERT_EQ (sm.get_num_styles (), 3);
+ ASSERT_EQ (s[0].get_code (), '0');
+ ASSERT_EQ (s[0].get_style_id (), 0);
+ ASSERT_EQ (s[1].get_code (), 'R');
+ ASSERT_EQ (s[1].get_style_id (), 1);
+ ASSERT_EQ (s[2].get_code (), '2');
+ ASSERT_EQ (s[2].get_style_id (), 0);
+ ASSERT_EQ (s[3].get_code (), 'G');
+ ASSERT_EQ (s[3].get_style_id (), 2);
+ ASSERT_EQ (s[4].get_code (), '4');
+ ASSERT_EQ (s[4].get_style_id (), 0);
+ ASSERT_EQ (sm.get_style (1).m_fg_color, style::named_color::RED);
+ ASSERT_EQ (sm.get_style (2).m_fg_color, style::named_color::GREEN);
+}
+
+static void
+test_from_str_with_named_color ()
+{
+ style_manager sm;
+ styled_string s (sm,
+ ("F"
+ SGR_SEQ (COLOR_FG_BLACK) "F"
+ SGR_SEQ (COLOR_FG_RED) "F"
+ SGR_SEQ (COLOR_FG_GREEN) "F"
+ SGR_SEQ (COLOR_FG_YELLOW) "F"
+ SGR_SEQ (COLOR_FG_BLUE) "F"
+ SGR_SEQ (COLOR_FG_MAGENTA) "F"
+ SGR_SEQ (COLOR_FG_CYAN) "F"
+ SGR_SEQ (COLOR_FG_WHITE) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_BLACK) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_RED) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_GREEN) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_YELLOW) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_BLUE) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_MAGENTA) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_CYAN) "F"
+ SGR_SEQ (COLOR_FG_BRIGHT_WHITE) "F"
+ SGR_SEQ (COLOR_BG_BLACK) "B"
+ SGR_SEQ (COLOR_BG_RED) "B"
+ SGR_SEQ (COLOR_BG_GREEN) "B"
+ SGR_SEQ (COLOR_BG_YELLOW) "B"
+ SGR_SEQ (COLOR_BG_BLUE) "B"
+ SGR_SEQ (COLOR_BG_MAGENTA) "B"
+ SGR_SEQ (COLOR_BG_CYAN) "B"
+ SGR_SEQ (COLOR_BG_WHITE) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_BLACK) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_RED) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_GREEN) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_YELLOW) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_BLUE) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_MAGENTA) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_CYAN) "B"
+ SGR_SEQ (COLOR_BG_BRIGHT_WHITE) "B"));
+ ASSERT_EQ (s.size (), 33);
+ for (size_t i = 0; i < s.size (); i++)
+ ASSERT_EQ (s[i].get_style_id (), i);
+ for (size_t i = 0; i < 17; i++)
+ ASSERT_EQ (s[i].get_code (), 'F');
+ for (size_t i = 17; i < 33; i++)
+ ASSERT_EQ (s[i].get_code (), 'B');
+}
+
+static void
+test_from_str_with_8_bit_color ()
+{
+ {
+ style_manager sm;
+ styled_string s (sm,
+ ("F"));
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s[0].get_code (), 'F');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_EQ (sm.get_style (1).m_fg_color, style::color (232));
+ }
+ {
+ style_manager sm;
+ styled_string s (sm,
+ ("B"));
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s[0].get_code (), 'B');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_EQ (sm.get_style (1).m_bg_color, style::color (231));
+ }
+}
+
+static void
+test_from_str_with_24_bit_color ()
+{
+ {
+ style_manager sm;
+ styled_string s (sm,
+ ("F"));
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s[0].get_code (), 'F');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_EQ (sm.get_style (1).m_fg_color, style::color (243, 250, 242));
+ }
+ {
+ style_manager sm;
+ styled_string s (sm,
+ ("B"));
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s[0].get_code (), 'B');
+ ASSERT_EQ (s[0].get_style_id (), 1);
+ ASSERT_EQ (sm.get_style (1).m_bg_color, style::color (253, 247, 231));
+ }
+}
+
+static void
+test_from_str_combining_characters ()
+{
+ style_manager sm;
+ styled_string s (sm,
+ /* CYRILLIC CAPITAL LETTER U (U+0423). */
+ "\xD0\xA3"
+ /* COMBINING BREVE (U+0306). */
+ "\xCC\x86");
+ ASSERT_EQ (s.size (), 1);
+ ASSERT_EQ (s[0].get_code (), 0x423);
+ ASSERT_EQ (s[0].get_combining_chars ().size (), 1);
+ ASSERT_EQ (s[0].get_combining_chars ()[0], 0x306);
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_styled_string_cc_tests ()
+{
+ test_combining_chars ();
+ test_empty ();
+ test_simple ();
+ test_pi_from_utf8 ();
+ test_emoji_from_utf8 ();
+ test_emoji_variant_from_utf8 ();
+ test_emoji_from_codepoint ();
+ test_from_mixed_width_utf8 ();
+ test_url ();
+ test_from_fmt ();
+ test_from_fmt_qs ();
+ test_from_str_with_bold ();
+ test_from_str_with_underscore ();
+ test_from_str_with_blink ();
+ test_from_str_with_color ();
+ test_from_str_with_named_color ();
+ test_from_str_with_8_bit_color ();
+ test_from_str_with_24_bit_color ();
+ test_from_str_combining_characters ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/table.cc b/gcc/text-art/table.cc
new file mode 100644
index 0000000..71a1024
--- /dev/null
+++ b/gcc/text-art/table.cc
@@ -0,0 +1,1273 @@
+/* Support for tabular/grid-based content.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_MEMORY
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "make-unique.h"
+#include "pretty-print.h"
+#include "diagnostic.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/table.h"
+
+using namespace text_art;
+
+/* class text_art::table_cell_content. */
+
+table_cell_content::table_cell_content (styled_string &&s)
+: m_str (std::move (s)),
+ /* We assume here that the content occupies a single canvas row. */
+ m_size (m_str.calc_canvas_width (), 1)
+{
+}
+
+void
+table_cell_content::paint_to_canvas (canvas &canvas,
+ canvas::coord_t top_left) const
+{
+ canvas.paint_text (top_left, m_str);
+}
+
+/* struct text_art::table_dimension_sizes. */
+
+table_dimension_sizes::table_dimension_sizes (unsigned num)
+: m_requirements (num, 0)
+{
+}
+
+/* class text_art::table::cell_placement. */
+
+void
+table::cell_placement::paint_cell_contents_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg) const
+{
+ const canvas::size_t req_canvas_size = get_min_canvas_size ();
+ const canvas::size_t alloc_canvas_size = tg.get_canvas_size (m_rect);
+ gcc_assert (req_canvas_size.w <= alloc_canvas_size.w);
+ gcc_assert (req_canvas_size.h <= alloc_canvas_size.h);
+ const int x_padding = alloc_canvas_size.w - req_canvas_size.w;
+ const int y_padding = alloc_canvas_size.h - req_canvas_size.h;
+ const table::coord_t table_top_left = m_rect.m_top_left;
+ const canvas::coord_t canvas_top_left = tg.table_to_canvas (table_top_left);
+
+ gcc_assert (x_padding >= 0);
+ int x_align_offset;
+ switch (m_x_align)
+ {
+ default:
+ gcc_unreachable ();
+ case x_align::LEFT:
+ x_align_offset = 0;
+ break;
+ case x_align::CENTER:
+ x_align_offset = x_padding / 2;
+ break;
+ case x_align::RIGHT:
+ x_align_offset = x_padding;
+ break;
+ }
+
+ gcc_assert (y_padding >= 0);
+ int y_align_offset;
+ switch (m_y_align)
+ {
+ default:
+ gcc_unreachable ();
+ case y_align::TOP:
+ y_align_offset = 0;
+ break;
+ case y_align::CENTER:
+ y_align_offset = y_padding / 2;
+ break;
+ case y_align::BOTTOM:
+ y_align_offset = y_padding;
+ break;
+ }
+ const canvas::coord_t content_rel_coord
+ (canvas_top_left.x + 1 + x_align_offset,
+ canvas_top_left.y + 1 + y_align_offset);
+ m_content.paint_to_canvas (canvas, offset + content_rel_coord);
+}
+
+/* class text_art::table. */
+
+
+table::table (size_t size)
+: m_size (size),
+ m_placements (),
+ m_occupancy (size)
+{
+ m_occupancy.fill (-1);
+}
+
+void
+table::set_cell (coord_t coord,
+ table_cell_content &&content,
+ enum x_align x_align,
+ enum y_align y_align)
+{
+ set_cell_span (rect_t (coord, table::size_t (1, 1)),
+ std::move (content), x_align, y_align);
+}
+
+void
+table::set_cell_span (rect_t span,
+ table_cell_content &&content,
+ enum x_align x_align,
+ enum y_align y_align)
+{
+ gcc_assert (span.m_size.w > 0);
+ gcc_assert (span.m_size.h > 0);
+ int placement_idx = m_placements.size ();
+ m_placements.emplace_back (cell_placement (span, std::move (content),
+ x_align, y_align));
+ for (int y = span.get_min_y (); y < span.get_next_y (); y++)
+ for (int x = span.get_min_x (); x < span.get_next_x (); x++)
+ {
+ gcc_assert (m_occupancy.get (coord_t (x, y)) == -1);
+ m_occupancy.set (coord_t (x, y), placement_idx);
+ }
+}
+
+canvas
+table::to_canvas (const theme &theme, const style_manager &sm) const
+{
+ table_dimension_sizes col_widths (m_size.w);
+ table_dimension_sizes row_heights (m_size.h);
+ table_cell_sizes cell_sizes (col_widths, row_heights);
+ cell_sizes.pass_1 (*this);
+ cell_sizes.pass_2 (*this);
+ table_geometry tg (*this, cell_sizes);
+ canvas canvas (tg.get_canvas_size (), sm);
+ paint_to_canvas (canvas, canvas::coord_t (0, 0), tg, theme);
+ return canvas;
+}
+
+void
+table::paint_to_canvas (canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg,
+ const theme &theme) const
+{
+ canvas.fill (canvas::rect_t (offset, tg.get_canvas_size ()),
+ styled_unichar (' '));
+ paint_cell_borders_to_canvas (canvas, offset, tg, theme);
+ paint_cell_contents_to_canvas (canvas, offset, tg);
+}
+
+/* Print this table to stderr. */
+
+DEBUG_FUNCTION void
+table::debug () const
+{
+ /* Use a temporary style manager.
+ Styles in the table will be meaningless, so
+ print the canvas with styling disabled. */
+ style_manager sm;
+ canvas canvas (to_canvas (unicode_theme (), sm));
+ canvas.debug (false);
+}
+
+const table::cell_placement *
+table::get_placement_at (coord_t coord) const
+{
+ const int placement_idx = m_occupancy.get (coord);
+ if (placement_idx == -1)
+ return nullptr;
+ return &m_placements[placement_idx];
+}
+
+int
+table::get_occupancy_safe (coord_t coord) const
+{
+ if (coord.x < 0)
+ return -1;
+ if (coord.x >= m_size.w)
+ return -1;
+ if (coord.y < 0)
+ return -1;
+ if (coord.y >= m_size.h)
+ return -1;
+ return m_occupancy.get (coord);
+}
+
+/* Determine if the "?" edges need borders for table cell D
+ in the following, for the directions relative to "X", based
+ on whether each of table cell boundaries AB, CD, AC, and BD
+ are boundaries between cell spans:
+
+ # up?
+ # +-----+-----+
+ # | |
+ # | ? |
+ # | A ? B |
+ # | ? |
+ # | |
+ # left?+ ??? X ??? + right?
+ # | |
+ # | ? |
+ # | C ? D |
+ # | ? |
+ # | |
+ # +-----+-----+
+ # down?
+*/
+
+directions
+table::get_connections (int table_x, int table_y) const
+{
+ int cell_a = get_occupancy_safe (coord_t (table_x - 1, table_y - 1));
+ int cell_b = get_occupancy_safe (coord_t (table_x, table_y - 1));
+ int cell_c = get_occupancy_safe (coord_t (table_x - 1, table_y));
+ int cell_d = get_occupancy_safe (coord_t (table_x, table_y));
+ const bool up = (cell_a != cell_b);
+ const bool down = (cell_c != cell_d);
+ const bool left = (cell_a != cell_c);
+ const bool right = (cell_b != cell_d);
+ return directions (up, down, left, right);
+}
+
+/* Paint the grid lines.
+
+ Consider painting
+ - a grid of cells,
+ - plus a right-hand border
+ - and a bottom border
+
+ Then we need to paint to the canvas like this:
+
+ # PER-TABLE-COLUMN R BORDER
+ # +-------------------+ +-----+
+ #
+ # TABLE CELL WIDTH (in canvas units)
+ # +-------------+
+ # . . . . . . .
+ # ...+-----+-----+.+-----+...+-----+ +
+ # | U | |.| | | U | |
+ # | U | |.| | | U | |
+ # |LL+RR|RRRRR|.|RRRRR| |LL+ | |
+ # | D | |.| | | D | |
+ # | D | |.| | | D | |
+ # ...+-----+-----+.+-----+...+-----+ |
+ # ..................... ...... +-- PER-TABLE-ROW
+ # ...+-----+-----+.+-----+...+-----+ | +
+ # | D | |.| | | D | | |
+ # | D | |.| | | D | | |
+ # | D | |.| | | D | | +---- TABLE CELL HEIGHT (in canvas units)
+ # | D | |.| | | D | | |
+ # | D | |.| | | D | | |
+ # ...+-----+-----+.+-----+...+-----+ + +
+ # . . . . . .
+ # ...+-----+-----+.+-----+...+-----+ +
+ # | D | |.| | | U | |
+ # | D | |.| | | U | |
+ # |LL+RR|RRRRR|.|RRRRR| |LL+ | | BOTTOM BORDER
+ # | | |.| | | | |
+ # | | |.| | | | |
+ # ...+-----+-----+.+-----+...+-----+ +
+
+ where each:
+
+ # +-----+
+ # | |
+ # | |
+ # | |
+ # | |
+ # | |
+ # +-----+
+
+ is a canvas cell, and the U, L, R, D express the connections
+ that are present with neighboring table cells. These affect
+ the kinds of borders that we draw for a particular table cell. */
+
+void
+table::paint_cell_borders_to_canvas (canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg,
+ const theme &theme) const
+{
+ /* The per-table-cell left and top borders are either drawn or not,
+ but if they are, they aren't affected by per-table-cell connections. */
+ const canvas::cell_t left_border
+ = theme.get_line_art (directions (true, /* up */
+ true, /* down */
+ false, /* left */
+ false /* right */));
+ const canvas::cell_t top_border
+ = theme.get_line_art (directions (false, /* up */
+ false, /* down */
+ true, /* left */
+ true)); /* right */
+ for (int table_y = 0; table_y < m_size.h; table_y++)
+ {
+ const int canvas_y = tg.table_y_to_canvas_y (table_y);
+ for (int table_x = 0; table_x < m_size.w; table_x++)
+ {
+ canvas::coord_t canvas_top_left
+ = tg.table_to_canvas(table::coord_t (table_x, table_y));
+
+ const directions c (get_connections (table_x, table_y));
+
+ /* Paint top-left corner of border, if any. */
+ canvas.paint (offset + canvas_top_left,
+ theme.get_line_art (c));
+
+ /* Paint remainder of left border of cell, if any.
+ We assume here that the content occupies a single canvas row. */
+ if (c.m_down)
+ canvas.paint (offset + canvas::coord_t (canvas_top_left.x,
+ canvas_y + 1),
+ left_border);
+
+ /* Paint remainder of top border of cell, if any. */
+ if (c.m_right)
+ {
+ const int col_width = tg.get_col_width (table_x);
+ for (int x_offset = 0; x_offset < col_width; x_offset++)
+ {
+ const int canvas_x = canvas_top_left.x + 1 + x_offset;
+ canvas.paint (offset + canvas::coord_t (canvas_x, canvas_y),
+ top_border);
+ }
+ }
+ }
+
+ /* Paint right-hand border of row. */
+ const int table_x = m_size.w;
+ const int canvas_x = tg.table_x_to_canvas_x (table_x);
+ const directions c (get_connections (m_size.w, table_y));
+ canvas.paint(offset + canvas::coord_t (canvas_x, canvas_y),
+ theme.get_line_art (directions (c.m_up,
+ c.m_down,
+ c.m_left,
+ false))); /* right */
+ /* We assume here that the content occupies a single canvas row. */
+ canvas.paint(offset + canvas::coord_t (canvas_x, canvas_y + 1),
+ theme.get_line_art (directions (c.m_down, /* up */
+ c.m_down, /* down */
+ false, /* left */
+ false))); /* right */
+ }
+
+ /* Draw bottom border of table. */
+ {
+ const int canvas_y = tg.get_canvas_size ().h - 1;
+ for (int table_x = 0; table_x < m_size.w; table_x++)
+ {
+ const directions c (get_connections (table_x, m_size.h));
+ const int left_canvas_x = tg.table_x_to_canvas_x (table_x);
+ canvas.paint (offset + canvas::coord_t (left_canvas_x, canvas_y),
+ theme.get_line_art (directions (c.m_up,
+ false, /* down */
+ c.m_left,
+ c.m_right)));
+ const int col_width = tg.get_col_width (table_x);
+ for (int x_offset = 0; x_offset < col_width; x_offset++)
+ {
+ const int canvas_x = left_canvas_x + 1 + x_offset;
+ canvas.paint(offset + canvas::coord_t (canvas_x, canvas_y),
+ theme.get_line_art (directions (false, // up
+ false, // down
+ c.m_right, // left
+ c.m_right))); // right
+ }
+ }
+
+ /* Bottom-right corner of table. */
+ const int table_x = m_size.w;
+ const int canvas_x = tg.table_x_to_canvas_x (table_x);
+ const directions c (get_connections (m_size.w, m_size.h));
+ canvas.paint (offset + canvas::coord_t (canvas_x, canvas_y),
+ theme.get_line_art (directions (c.m_up, // up
+ false, // down
+ c.m_left, // left
+ false))); // right
+ }
+}
+
+void
+table::paint_cell_contents_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg) const
+{
+ for (auto &placement : m_placements)
+ placement.paint_cell_contents_to_canvas (canvas, offset, tg);
+}
+
+/* class table_cell_sizes. */
+
+/* Consider 1x1 cells. */
+
+void
+table_cell_sizes::pass_1 (const table &table)
+{
+ for (auto &placement : table.m_placements)
+ if (placement.one_by_one_p ())
+ {
+ canvas::size_t canvas_size (placement.get_min_canvas_size ());
+ table::coord_t table_coord (placement.m_rect.m_top_left);
+ m_col_widths.require (table_coord.x, canvas_size.w);
+ m_row_heights.require (table_coord.y, canvas_size.h);
+ }
+}
+
+/* Consider cells that span more than one row or column. */
+
+void
+table_cell_sizes::pass_2 (const table &table)
+{
+ for (auto &placement : table.m_placements)
+ if (!placement.one_by_one_p ())
+ {
+ const canvas::size_t req_canvas_size (placement.get_min_canvas_size ());
+ const canvas::size_t current_canvas_size
+ = get_canvas_size (placement.m_rect);
+ /* Grow columns as necessary. */
+ if (req_canvas_size.w > current_canvas_size.w)
+ {
+ /* Spread the deficit amongst the columns. */
+ int deficit = req_canvas_size.w - current_canvas_size.w;
+ const int per_col = deficit / placement.m_rect.m_size.w;
+ for (int table_x = placement.m_rect.get_min_x ();
+ table_x < placement.m_rect.get_next_x ();
+ table_x++)
+ {
+ m_col_widths.m_requirements[table_x] += per_col;
+ deficit -= per_col;
+ }
+ /* Make sure we allocate all of the deficit. */
+ if (deficit > 0)
+ {
+ const int table_x = placement.m_rect.get_max_x ();
+ m_col_widths.m_requirements[table_x] += deficit;
+ }
+ }
+ /* Grow rows as necessary. */
+ if (req_canvas_size.h > current_canvas_size.h)
+ {
+ /* Spread the deficit amongst the rows. */
+ int deficit = req_canvas_size.h - current_canvas_size.h;
+ const int per_row = deficit / placement.m_rect.m_size.h;
+ for (int table_y = placement.m_rect.get_min_y ();
+ table_y < placement.m_rect.get_next_y ();
+ table_y++)
+ {
+ m_row_heights.m_requirements[table_y] += per_row;
+ deficit -= per_row;
+ }
+ /* Make sure we allocate all of the deficit. */
+ if (deficit > 0)
+ {
+ const int table_y = placement.m_rect.get_max_y ();
+ m_row_heights.m_requirements[table_y] += deficit;
+ }
+ }
+ }
+}
+
+canvas::size_t
+table_cell_sizes::get_canvas_size (const table::rect_t &rect) const
+{
+ canvas::size_t result (0, 0);
+ for (int table_x = rect.get_min_x ();
+ table_x < rect.get_next_x ();
+ table_x ++)
+ result.w += m_col_widths.m_requirements[table_x];
+ for (int table_y = rect.get_min_y ();
+ table_y < rect.get_next_y ();
+ table_y ++)
+ result.h += m_row_heights.m_requirements[table_y];
+ /* Allow space for the borders. */
+ result.w += rect.m_size.w - 1;
+ result.h += rect.m_size.h - 1;
+ return result;
+}
+
+/* class text_art::table_geometry. */
+
+table_geometry::table_geometry (const table &table, table_cell_sizes &cell_sizes)
+: m_table (table),
+ m_cell_sizes (cell_sizes),
+ m_canvas_size (canvas::size_t (0, 0)),
+ m_col_start_x (table.get_size ().w),
+ m_row_start_y (table.get_size ().h)
+{
+ recalc_coords ();
+}
+
+void
+table_geometry::recalc_coords ()
+{
+ /* Start canvas column of table cell, including leading border. */
+ m_col_start_x.clear ();
+ int iter_canvas_x = 0;
+ for (auto w : m_cell_sizes.m_col_widths.m_requirements)
+ {
+ m_col_start_x.push_back (iter_canvas_x);
+ iter_canvas_x += w + 1;
+ }
+
+ /* Start canvas row of table cell, including leading border. */
+ m_row_start_y.clear ();
+ int iter_canvas_y = 0;
+ for (auto h : m_cell_sizes.m_row_heights.m_requirements)
+ {
+ m_row_start_y.push_back (iter_canvas_y);
+ iter_canvas_y += h + 1;
+ }
+
+ m_canvas_size = canvas::size_t (iter_canvas_x + 1,
+ iter_canvas_y + 1);
+}
+
+/* Get the TL corner of the table cell at TABLE_COORD
+ in canvas coords (including the border). */
+
+canvas::coord_t
+table_geometry::table_to_canvas (table::coord_t table_coord) const
+{
+ return canvas::coord_t (table_x_to_canvas_x (table_coord.x),
+ table_y_to_canvas_y (table_coord.y));
+}
+
+/* Get the left border of the table cell at column TABLE_X
+ in canvas coords (including the border). */
+
+int
+table_geometry::table_x_to_canvas_x (int table_x) const
+{
+ /* Allow one beyond the end, for the right-hand border of the table. */
+ if (table_x == m_col_start_x.size ())
+ return m_canvas_size.w - 1;
+ return m_col_start_x[table_x];
+}
+
+/* Get the top border of the table cell at column TABLE_Y
+ in canvas coords (including the border). */
+
+int
+table_geometry::table_y_to_canvas_y (int table_y) const
+{
+ /* Allow one beyond the end, for the right-hand border of the table. */
+ if (table_y == m_row_start_y.size ())
+ return m_canvas_size.h - 1;
+ return m_row_start_y[table_y];
+}
+
+/* class text_art::simple_table_geometry. */
+
+simple_table_geometry::simple_table_geometry (const table &table)
+: m_col_widths (table.get_size ().w),
+ m_row_heights (table.get_size ().h),
+ m_cell_sizes (m_col_widths, m_row_heights),
+ m_tg (table, m_cell_sizes)
+{
+ m_cell_sizes.pass_1 (table);
+ m_cell_sizes.pass_2 (table);
+ m_tg.recalc_coords ();
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+static void
+test_tic_tac_toe ()
+{
+ style_manager sm;
+ table t (table::size_t (3, 3));
+ t.set_cell (table::coord_t (0, 0), styled_string (sm, "X"));
+ t.set_cell (table::coord_t (1, 0), styled_string (sm, ""));
+ t.set_cell (table::coord_t (2, 0), styled_string (sm, ""));
+ t.set_cell (table::coord_t (0, 1), styled_string (sm, "O"));
+ t.set_cell (table::coord_t (1, 1), styled_string (sm, "O"));
+ t.set_cell (table::coord_t (2, 1), styled_string (sm, ""));
+ t.set_cell (table::coord_t (0, 2), styled_string (sm, "X"));
+ t.set_cell (table::coord_t (1, 2), styled_string (sm, ""));
+ t.set_cell (table::coord_t (2, 2), styled_string (sm, "O"));
+
+ {
+ canvas canvas (t.to_canvas (ascii_theme (), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+-+-+-+\n"
+ "|X| | |\n"
+ "+-+-+-+\n"
+ "|O|O| |\n"
+ "+-+-+-+\n"
+ "|X| |O|\n"
+ "+-+-+-+\n"));
+ }
+
+ {
+ canvas canvas (t.to_canvas (unicode_theme (), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌─┬─┬─┐\n"
+ "│X│ │ │\n"
+ "├─┼─┼─┤\n"
+ "│O│O│ │\n"
+ "├─┼─┼─┤\n"
+ "│X│ │O│\n"
+ "└─┴─┴─┘\n"));
+ }
+}
+
+static table
+make_text_table ()
+{
+ style_manager sm;
+ table t (table::size_t (3, 3));
+ t.set_cell (table::coord_t (0, 0), styled_string (sm, "top left"));
+ t.set_cell (table::coord_t (1, 0), styled_string (sm, "top middle"));
+ t.set_cell (table::coord_t (2, 0), styled_string (sm, "top right"));
+ t.set_cell (table::coord_t (0, 1), styled_string (sm, "middle left"));
+ t.set_cell (table::coord_t (1, 1), styled_string (sm, "middle middle"));
+ t.set_cell (table::coord_t (2, 1), styled_string (sm, "middle right"));
+ t.set_cell (table::coord_t (0, 2), styled_string (sm, "bottom left"));
+ t.set_cell (table::coord_t (1, 2), styled_string (sm, "bottom middle"));
+ t.set_cell (table::coord_t (2, 2), styled_string (sm, "bottom right"));
+ return t;
+}
+
+static void
+test_text_table ()
+{
+ style_manager sm;
+ table table = make_text_table ();
+ {
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+-----------+-------------+------------+\n"
+ "| top left | top middle | top right |\n"
+ "+-----------+-------------+------------+\n"
+ "|middle left|middle middle|middle right|\n"
+ "+-----------+-------------+------------+\n"
+ "|bottom left|bottom middle|bottom right|\n"
+ "+-----------+-------------+------------+\n"));
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌───────────┬─────────────┬────────────┐\n"
+ "│ top left │ top middle │ top right │\n"
+ "├───────────┼─────────────┼────────────┤\n"
+ "│middle left│middle middle│middle right│\n"
+ "├───────────┼─────────────┼────────────┤\n"
+ "│bottom left│bottom middle│bottom right│\n"
+ "└───────────┴─────────────┴────────────┘\n"));
+ }
+}
+
+static void
+test_offset_table ()
+{
+ style_manager sm;
+ table table = make_text_table ();
+ simple_table_geometry stg (table);
+ const canvas::size_t tcs = stg.m_tg.get_canvas_size();
+ {
+ canvas canvas (canvas::size_t (tcs.w + 5, tcs.h + 5), sm);
+ canvas.debug_fill ();
+ table.paint_to_canvas (canvas, canvas::coord_t (3, 3),
+ stg.m_tg,
+ ascii_theme());
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("*********************************************\n"
+ "*********************************************\n"
+ "*********************************************\n"
+ "***+-----------+-------------+------------+**\n"
+ "***| top left | top middle | top right |**\n"
+ "***+-----------+-------------+------------+**\n"
+ "***|middle left|middle middle|middle right|**\n"
+ "***+-----------+-------------+------------+**\n"
+ "***|bottom left|bottom middle|bottom right|**\n"
+ "***+-----------+-------------+------------+**\n"
+ "*********************************************\n"
+ "*********************************************\n"));
+ }
+ {
+ canvas canvas (canvas::size_t (tcs.w + 5, tcs.h + 5), sm);
+ canvas.debug_fill ();
+ table.paint_to_canvas (canvas, canvas::coord_t (3, 3),
+ stg.m_tg,
+ unicode_theme());
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("*********************************************\n"
+ "*********************************************\n"
+ "*********************************************\n"
+ "***┌───────────┬─────────────┬────────────┐**\n"
+ "***│ top left │ top middle │ top right │**\n"
+ "***├───────────┼─────────────┼────────────┤**\n"
+ "***│middle left│middle middle│middle right│**\n"
+ "***├───────────┼─────────────┼────────────┤**\n"
+ "***│bottom left│bottom middle│bottom right│**\n"
+ "***└───────────┴─────────────┴────────────┘**\n"
+ "*********************************************\n"
+ "*********************************************\n"));
+ }
+}
+
+#define ASSERT_TABLE_CELL_STREQ(TABLE, TABLE_X, TABLE_Y, EXPECTED_STR) \
+ SELFTEST_BEGIN_STMT \
+ table::coord_t coord ((TABLE_X), (TABLE_Y)); \
+ const table::cell_placement *cp = (TABLE).get_placement_at (coord); \
+ ASSERT_NE (cp, nullptr); \
+ ASSERT_EQ (cp->get_content (), styled_string (sm, EXPECTED_STR)); \
+ SELFTEST_END_STMT
+
+#define ASSERT_TABLE_NULL_CELL(TABLE, TABLE_X, TABLE_Y) \
+ SELFTEST_BEGIN_STMT \
+ table::coord_t coord ((TABLE_X), (TABLE_Y)); \
+ const table::cell_placement *cp = (TABLE).get_placement_at (coord); \
+ ASSERT_EQ (cp, nullptr); \
+ SELFTEST_END_STMT
+
+static void
+test_spans ()
+{
+ style_manager sm;
+ table table (table::size_t (3, 3));
+ table.set_cell_span (table::rect_t (table::coord_t (0, 0),
+ table::size_t (3, 1)),
+ styled_string (sm, "ABC"));
+ table.set_cell_span (table::rect_t (table::coord_t (0, 1),
+ table::size_t (2, 1)),
+ styled_string (sm, "DE"));
+ table.set_cell_span (table::rect_t (table::coord_t (2, 1),
+ table::size_t (1, 1)),
+ styled_string (sm, "F"));
+ table.set_cell (table::coord_t (0, 2), styled_string (sm, "G"));
+ table.set_cell (table::coord_t (1, 2), styled_string (sm, "H"));
+ table.set_cell (table::coord_t (2, 2), styled_string (sm, "I"));
+ {
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+-----+\n"
+ "| ABC |\n"
+ "+---+-+\n"
+ "|DE |F|\n"
+ "+-+-+-+\n"
+ "|G|H|I|\n"
+ "+-+-+-+\n"));
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌─────┐\n"
+ "│ ABC │\n"
+ "├───┬─┤\n"
+ "│DE │F│\n"
+ "├─┬─┼─┤\n"
+ "│G│H│I│\n"
+ "└─┴─┴─┘\n"));
+ }
+}
+
+/* Verify building this 5x5 table with spans:
+ |0|1|2|3|4|
+ +-+-+-+-+-+
+ 0|A A A|B|C|0
+ + +-+ +
+ 1|A A A|D|C|1
+ + +-+-+
+ 2|A A A|E|F|2
+ +-+-+-+-+-+
+ 3|G G|H|I I|3
+ | | +-+-+
+ 4|G G|H|J J|4
+ +-+-+-+-+-+
+ |0|1|2|3|4|
+*/
+
+static void
+test_spans_2 ()
+{
+ style_manager sm;
+ table table (table::size_t (5, 5));
+ table.set_cell_span (table::rect_t (table::coord_t (0, 0),
+ table::size_t (3, 3)),
+ styled_string (sm, "A"));
+ table.set_cell_span (table::rect_t (table::coord_t (3, 0),
+ table::size_t (1, 1)),
+ styled_string (sm, "B"));
+ table.set_cell_span (table::rect_t (table::coord_t (4, 0),
+ table::size_t (1, 2)),
+ styled_string (sm, "C"));
+ table.set_cell_span (table::rect_t (table::coord_t (3, 1),
+ table::size_t (1, 1)),
+ styled_string (sm, "D"));
+ table.set_cell_span (table::rect_t (table::coord_t (3, 2),
+ table::size_t (1, 1)),
+ styled_string (sm, "E"));
+ table.set_cell_span (table::rect_t (table::coord_t (4, 2),
+ table::size_t (1, 1)),
+ styled_string (sm, "F"));
+ table.set_cell_span (table::rect_t (table::coord_t (0, 3),
+ table::size_t (2, 2)),
+ styled_string (sm, "G"));
+ table.set_cell_span (table::rect_t (table::coord_t (2, 3),
+ table::size_t (1, 2)),
+ styled_string (sm, "H"));
+ table.set_cell_span (table::rect_t (table::coord_t (3, 3),
+ table::size_t (2, 1)),
+ styled_string (sm, "I"));
+ table.set_cell_span (table::rect_t (table::coord_t (3, 4),
+ table::size_t (2, 1)),
+ styled_string (sm, "J"));
+
+ /* Check occupancy at each table coordinate. */
+ ASSERT_TABLE_CELL_STREQ (table, 0, 0, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 0, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 0, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 3, 0, "B");
+ ASSERT_TABLE_CELL_STREQ (table, 4, 0, "C");
+
+ ASSERT_TABLE_CELL_STREQ (table, 0, 1, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 1, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 1, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 3, 1, "D");
+ ASSERT_TABLE_CELL_STREQ (table, 4, 1, "C");
+
+ ASSERT_TABLE_CELL_STREQ (table, 0, 2, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 2, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 2, "A");
+ ASSERT_TABLE_CELL_STREQ (table, 3, 2, "E");
+ ASSERT_TABLE_CELL_STREQ (table, 4, 2, "F");
+
+ ASSERT_TABLE_CELL_STREQ (table, 0, 3, "G");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 3, "G");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 3, "H");
+ ASSERT_TABLE_CELL_STREQ (table, 3, 3, "I");
+ ASSERT_TABLE_CELL_STREQ (table, 4, 3, "I");
+
+ ASSERT_TABLE_CELL_STREQ (table, 0, 4, "G");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 4, "G");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 4, "H");
+ ASSERT_TABLE_CELL_STREQ (table, 3, 4, "J");
+ ASSERT_TABLE_CELL_STREQ (table, 4, 4, "J");
+
+ {
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+---+-+-+\n"
+ "| |B| |\n"
+ "| +-+C|\n"
+ "| A |D| |\n"
+ "| +-+-+\n"
+ "| |E|F|\n"
+ "+-+-+-+-+\n"
+ "| | | I |\n"
+ "|G|H+---+\n"
+ "| | | J |\n"
+ "+-+-+---+\n"));
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌───┬─┬─┐\n"
+ "│ │B│ │\n"
+ "│ ├─┤C│\n"
+ "│ A │D│ │\n"
+ "│ ├─┼─┤\n"
+ "│ │E│F│\n"
+ "├─┬─┼─┴─┤\n"
+ "│ │ │ I │\n"
+ "│G│H├───┤\n"
+ "│ │ │ J │\n"
+ "└─┴─┴───┘\n"));
+ }
+}
+
+/* Experiment with adding a 1-table-column gap at the boundary between
+ valid vs invalid for visualizing a buffer overflow. */
+static void
+test_spans_3 ()
+{
+ const char * const str = "hello world!";
+ const size_t buf_size = 10;
+ const size_t str_size = strlen (str) + 1;
+
+ style_manager sm;
+ table table (table::size_t (str_size + 1, 3));
+
+ table.set_cell_span (table::rect_t (table::coord_t (0, 0),
+ table::size_t (str_size + 1, 1)),
+ styled_string (sm, "String literal"));
+
+ for (size_t i = 0; i < str_size; i++)
+ {
+ table::coord_t c (i, 1);
+ if (i >= buf_size)
+ c.x++;
+ if (str[i] == '\0')
+ table.set_cell (c, styled_string (sm, "NUL"));
+ else
+ table.set_cell (c, styled_string ((cppchar_t)str[i]));
+ }
+
+ table.set_cell_span (table::rect_t (table::coord_t (0, 2),
+ table::size_t (buf_size, 1)),
+ styled_string::from_fmt (sm,
+ nullptr,
+ "'buf' (char[%i])",
+ (int)buf_size));
+ table.set_cell_span (table::rect_t (table::coord_t (buf_size + 1, 2),
+ table::size_t (str_size - buf_size, 1)),
+ styled_string (sm, "overflow"));
+
+ {
+ canvas canvas (table.to_canvas (ascii_theme (), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ "+-----------------------------+\n"
+ "| String literal |\n"
+ "+-+-+-+-+-+-+-+-+-+-++-+-+----+\n"
+ "|h|e|l|l|o| |w|o|r|l||d|!|NUL |\n"
+ "+-+-+-+-+-+-+-+-+-+-++-+-+----+\n"
+ "| 'buf' (char[10]) ||overflow|\n"
+ "+-------------------++--------+\n");
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme (), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌─────────────────────────────┐\n"
+ "│ String literal │\n"
+ "├─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬┬─┬─┬────┤\n"
+ "│h│e│l│l│o│ │w│o│r│l││d│!│NUL │\n"
+ "├─┴─┴─┴─┴─┴─┴─┴─┴─┴─┤├─┴─┴────┤\n"
+ "│ 'buf' (char[10]) ││overflow│\n"
+ "└───────────────────┘└────────┘\n"));
+ }
+}
+
+static void
+test_double_width_chars ()
+{
+ table_cell_content tcc (styled_string ((cppchar_t)0x1f642));
+ ASSERT_EQ (tcc.get_canvas_size ().w, 2);
+ ASSERT_EQ (tcc.get_canvas_size ().h, 1);
+
+ style_manager sm;
+ table table (table::size_t (1, 1));
+ table.set_cell (table::coord_t (0,0),
+ styled_string ((cppchar_t)0x1f642));
+
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌──┐\n"
+ "│🙂│\n"
+ "└──┘\n"));
+}
+
+static void
+test_ipv4_header ()
+{
+ style_manager sm;
+ table table (table::size_t (34, 10));
+ table.set_cell (table::coord_t (0, 0), styled_string (sm, "Offsets"));
+ table.set_cell (table::coord_t (1, 0), styled_string (sm, "Octet"));
+ table.set_cell (table::coord_t (0, 1), styled_string (sm, "Octet"));
+ for (int octet = 0; octet < 4; octet++)
+ table.set_cell_span (table::rect_t (table::coord_t (2 + (octet * 8), 0),
+ table::size_t (8, 1)),
+ styled_string::from_fmt (sm, nullptr, "%i", octet));
+ table.set_cell (table::coord_t (1, 1), styled_string (sm, "Bit"));
+ for (int bit = 0; bit < 32; bit++)
+ table.set_cell (table::coord_t (bit + 2, 1),
+ styled_string::from_fmt (sm, nullptr, "%i", bit));
+ for (int word = 0; word < 6; word++)
+ {
+ table.set_cell (table::coord_t (0, word + 2),
+ styled_string::from_fmt (sm, nullptr, "%i", word * 4));
+ table.set_cell (table::coord_t (1, word + 2),
+ styled_string::from_fmt (sm, nullptr, "%i", word * 32));
+ }
+
+ table.set_cell (table::coord_t (0, 8), styled_string (sm, "..."));
+ table.set_cell (table::coord_t (1, 8), styled_string (sm, "..."));
+ table.set_cell (table::coord_t (0, 9), styled_string (sm, "56"));
+ table.set_cell (table::coord_t (1, 9), styled_string (sm, "448"));
+
+#define SET_BITS(FIRST, LAST, NAME) \
+ do { \
+ const int first = (FIRST); \
+ const int last = (LAST); \
+ const char *name = (NAME); \
+ const int row = first / 32; \
+ gcc_assert (last / 32 == row); \
+ table::rect_t rect (table::coord_t ((first % 32) + 2, row + 2), \
+ table::size_t (last + 1 - first , 1)); \
+ table.set_cell_span (rect, styled_string (sm, name)); \
+ } while (0)
+
+ SET_BITS (0, 3, "Version");
+ SET_BITS (4, 7, "IHL");
+ SET_BITS (8, 13, "DSCP");
+ SET_BITS (14, 15, "ECN");
+ SET_BITS (16, 31, "Total Length");
+
+ SET_BITS (32 + 0, 32 + 15, "Identification");
+ SET_BITS (32 + 16, 32 + 18, "Flags");
+ SET_BITS (32 + 19, 32 + 31, "Fragment Offset");
+
+ SET_BITS (64 + 0, 64 + 7, "Time To Live");
+ SET_BITS (64 + 8, 64 + 15, "Protocol");
+ SET_BITS (64 + 16, 64 + 31, "Header Checksum");
+
+ SET_BITS (96 + 0, 96 + 31, "Source IP Address");
+ SET_BITS (128 + 0, 128 + 31, "Destination IP Address");
+
+ table.set_cell_span(table::rect_t (table::coord_t (2, 7),
+ table::size_t (32, 3)),
+ styled_string (sm, "Options"));
+ {
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+-------+-----+---------------+---------------------+-----------------------+-----------------------+\n"
+ "|Offsets|Octet| 0 | 1 | 2 | 3 |\n"
+ "+-------+-----+-+-+-+-+-+-+-+-+-+-+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n"
+ "| Octet | Bit |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|\n"
+ "+-------+-----+-+-+-+-+-+-+-+-+-+-+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n"
+ "| 0 | 0 |Version| IHL | DSCP | ECN | Total Length |\n"
+ "+-------+-----+-------+-------+---------------+-----+--------+--------------------------------------+\n"
+ "| 4 | 32 | Identification | Flags | Fragment Offset |\n"
+ "+-------+-----+---------------+---------------------+--------+--------------------------------------+\n"
+ "| 8 | 64 | Time To Live | Protocol | Header Checksum |\n"
+ "+-------+-----+---------------+---------------------+-----------------------------------------------+\n"
+ "| 12 | 96 | Source IP Address |\n"
+ "+-------+-----+-------------------------------------------------------------------------------------+\n"
+ "| 16 | 128 | Destination IP Address |\n"
+ "+-------+-----+-------------------------------------------------------------------------------------+\n"
+ "| 20 | 160 | |\n"
+ "+-------+-----+ |\n"
+ "| ... | ... | Options |\n"
+ "+-------+-----+ |\n"
+ "| 56 | 448 | |\n"
+ "+-------+-----+-------------------------------------------------------------------------------------+\n"));
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ // FIXME: are we allowed unicode chars in string literals in our source?
+ ("┌───────┬─────┬───────────────┬─────────────────────┬───────────────────────┬───────────────────────┐\n"
+ "│Offsets│Octet│ 0 │ 1 │ 2 │ 3 │\n"
+ "├───────┼─────┼─┬─┬─┬─┬─┬─┬─┬─┼─┬─┬──┬──┬──┬──┬──┬──┼──┬──┬──┬──┬──┬──┬──┬──┼──┬──┬──┬──┬──┬──┬──┬──┤\n"
+ "│ Octet │ Bit │0│1│2│3│4│5│6│7│8│9│10│11│12│13│14│15│16│17│18│19│20│21│22│23│24│25│26│27│28│29│30│31│\n"
+ "├───────┼─────┼─┴─┴─┴─┼─┴─┴─┴─┼─┴─┴──┴──┴──┴──┼──┴──┼──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┴──┤\n"
+ "│ 0 │ 0 │Version│ IHL │ DSCP │ ECN │ Total Length │\n"
+ "├───────┼─────┼───────┴───────┴───────────────┴─────┼────────┬──────────────────────────────────────┤\n"
+ "│ 4 │ 32 │ Identification │ Flags │ Fragment Offset │\n"
+ "├───────┼─────┼───────────────┬─────────────────────┼────────┴──────────────────────────────────────┤\n"
+ "│ 8 │ 64 │ Time To Live │ Protocol │ Header Checksum │\n"
+ "├───────┼─────┼───────────────┴─────────────────────┴───────────────────────────────────────────────┤\n"
+ "│ 12 │ 96 │ Source IP Address │\n"
+ "├───────┼─────┼─────────────────────────────────────────────────────────────────────────────────────┤\n"
+ "│ 16 │ 128 │ Destination IP Address │\n"
+ "├───────┼─────┼─────────────────────────────────────────────────────────────────────────────────────┤\n"
+ "│ 20 │ 160 │ │\n"
+ "├───────┼─────┤ │\n"
+ "│ ... │ ... │ Options │\n"
+ "├───────┼─────┤ │\n"
+ "│ 56 │ 448 │ │\n"
+ "└───────┴─────┴─────────────────────────────────────────────────────────────────────────────────────┘\n"));
+ }
+}
+
+static void
+test_missing_cells ()
+{
+ style_manager sm;
+ table table (table::size_t (3, 3));
+ table.set_cell (table::coord_t (1, 0), styled_string (sm, "A"));
+ table.set_cell (table::coord_t (0, 1), styled_string (sm, "B"));
+ table.set_cell (table::coord_t (1, 1), styled_string (sm, "C"));
+ table.set_cell (table::coord_t (2, 1), styled_string (sm, "D"));
+ table.set_cell (table::coord_t (1, 2), styled_string (sm, "E"));
+
+ ASSERT_TABLE_NULL_CELL (table, 0, 0);
+ ASSERT_TABLE_CELL_STREQ (table, 1, 0, "A");
+ ASSERT_TABLE_NULL_CELL (table, 2, 0);
+
+ ASSERT_TABLE_CELL_STREQ (table, 0, 1, "B");
+ ASSERT_TABLE_CELL_STREQ (table, 1, 1, "C");
+ ASSERT_TABLE_CELL_STREQ (table, 2, 1, "D");
+
+ ASSERT_TABLE_NULL_CELL (table, 0, 2);
+ ASSERT_TABLE_CELL_STREQ (table, 1, 2, "E");
+ ASSERT_TABLE_NULL_CELL (table, 2, 2);
+
+ {
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ (" +-+\n"
+ " |A|\n"
+ "+-+-+-+\n"
+ "|B|C|D|\n"
+ "+-+-+-+\n"
+ " |E|\n"
+ " +-+\n"));
+ }
+ {
+ canvas canvas (table.to_canvas (unicode_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ (" ┌─┐\n"
+ " │A│\n"
+ "┌─┼─┼─┐\n"
+ "│B│C│D│\n"
+ "└─┼─┼─┘\n"
+ " │E│\n"
+ " └─┘\n"));
+ }
+}
+
+static void
+test_add_row ()
+{
+ style_manager sm;
+ table table (table::size_t (3, 0));
+ for (int i = 0; i < 5; i++)
+ {
+ const int y = table.add_row ();
+ for (int x = 0; x < 3; x++)
+ table.set_cell (table::coord_t (x, y),
+ styled_string::from_fmt (sm, nullptr,
+ "%i, %i", x, y));
+ }
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+----+----+----+\n"
+ "|0, 0|1, 0|2, 0|\n"
+ "+----+----+----+\n"
+ "|0, 1|1, 1|2, 1|\n"
+ "+----+----+----+\n"
+ "|0, 2|1, 2|2, 2|\n"
+ "+----+----+----+\n"
+ "|0, 3|1, 3|2, 3|\n"
+ "+----+----+----+\n"
+ "|0, 4|1, 4|2, 4|\n"
+ "+----+----+----+\n"));
+}
+
+static void
+test_alignment ()
+{
+ style_manager sm;
+ table table (table::size_t (9, 9));
+ table.set_cell_span (table::rect_t (table::coord_t (0, 0),
+ table::size_t (3, 3)),
+ styled_string (sm, "left top"),
+ x_align::LEFT, y_align::TOP);
+ table.set_cell_span (table::rect_t (table::coord_t (3, 0),
+ table::size_t (3, 3)),
+ styled_string (sm, "center top"),
+ x_align::CENTER, y_align::TOP);
+ table.set_cell_span (table::rect_t (table::coord_t (6, 0),
+ table::size_t (3, 3)),
+ styled_string (sm, "right top"),
+ x_align::RIGHT, y_align::TOP);
+ table.set_cell_span (table::rect_t (table::coord_t (0, 3),
+ table::size_t (3, 3)),
+ styled_string (sm, "left center"),
+ x_align::LEFT, y_align::CENTER);
+ table.set_cell_span (table::rect_t (table::coord_t (3, 3),
+ table::size_t (3, 3)),
+ styled_string (sm, "center center"),
+ x_align::CENTER, y_align::CENTER);
+ table.set_cell_span (table::rect_t (table::coord_t (6, 3),
+ table::size_t (3, 3)),
+ styled_string (sm, "right center"),
+ x_align::RIGHT, y_align::CENTER);
+ table.set_cell_span (table::rect_t (table::coord_t (0, 6),
+ table::size_t (3, 3)),
+ styled_string (sm, "left bottom"),
+ x_align::LEFT, y_align::BOTTOM);
+ table.set_cell_span (table::rect_t (table::coord_t (3, 6),
+ table::size_t (3, 3)),
+ styled_string (sm, "center bottom"),
+ x_align::CENTER, y_align::BOTTOM);
+ table.set_cell_span (table::rect_t (table::coord_t (6, 6),
+ table::size_t (3, 3)),
+ styled_string (sm, "right bottom"),
+ x_align::RIGHT, y_align::BOTTOM);
+
+ canvas canvas (table.to_canvas (ascii_theme(), sm));
+ ASSERT_CANVAS_STREQ
+ (canvas, false,
+ ("+-----------+-------------+------------+\n"
+ "|left top | center top | right top|\n"
+ "| | | |\n"
+ "+-----------+-------------+------------+\n"
+ "|left center|center center|right center|\n"
+ "| | | |\n"
+ "+-----------+-------------+------------+\n"
+ "| | | |\n"
+ "|left bottom|center bottom|right bottom|\n"
+ "+-----------+-------------+------------+\n"));
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_table_cc_tests ()
+{
+ test_tic_tac_toe ();
+ test_text_table ();
+ test_offset_table ();
+ test_spans ();
+ test_spans_2 ();
+ test_spans_3 ();
+ test_double_width_chars ();
+ test_ipv4_header ();
+ test_missing_cells ();
+ test_add_row ();
+ test_alignment ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/table.h b/gcc/text-art/table.h
new file mode 100644
index 0000000..2dc5c3c
--- /dev/null
+++ b/gcc/text-art/table.h
@@ -0,0 +1,261 @@
+/* Support for tabular/grid-based content.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_TABLE_H
+#define GCC_TEXT_ART_TABLE_H
+
+#include "text-art/canvas.h"
+#include "text-art/theme.h"
+
+namespace text_art {
+
+class table;
+class table_geometry;
+
+/* A class representing the content of a particular table cell,
+ or of a span of table cells. */
+
+class table_cell_content
+{
+ public:
+ table_cell_content () : m_str (), m_size (0, 0) {}
+ table_cell_content (styled_string &&s);
+
+ bool operator== (const table_cell_content &other) const
+ {
+ return m_str == other.m_str;
+ }
+
+ canvas::size_t get_canvas_size () const { return m_size; }
+
+ void paint_to_canvas (canvas &canvas,
+ canvas::coord_t top_left) const;
+
+ private:
+ styled_string m_str;
+ canvas::size_t m_size;
+};
+
+/* A list of required sizes of table rows or columns
+ in canvas units (row heights or column widths). */
+
+struct table_dimension_sizes
+{
+ table_dimension_sizes (unsigned num);
+
+ void require (unsigned idx, int amount)
+ {
+ m_requirements[idx] = std::max (m_requirements[idx], amount);
+ }
+
+ std::vector<int> m_requirements;
+};
+
+/* A 2D grid of cells. Instances of table_cell_content can be assigned
+ to individual table cells, and to rectangular spans of cells. Such
+ assignments do not have to fully cover the 2D grid, but they must not
+ overlap. */
+
+class table
+{
+ public:
+ typedef size<class table> size_t;
+ typedef coord<class table> coord_t;
+ typedef range<class table> range_t;
+ typedef rect<class table> rect_t;
+
+ /* A record of how a table_cell_content was placed at a table::rect_t
+ with a certain alignment. */
+ class cell_placement
+ {
+ public:
+ cell_placement (rect_t rect,
+ table_cell_content &&content,
+ x_align x_align,
+ y_align y_align)
+ : m_rect (rect),
+ m_content (std::move (content)),
+ m_x_align (x_align),
+ m_y_align (y_align)
+ {
+ }
+
+ bool one_by_one_p () const
+ {
+ return m_rect.m_size.w == 1 && m_rect.m_size.h == 1;
+ }
+
+ canvas::size_t get_min_canvas_size () const
+ {
+ // Doesn't include border
+ return m_content.get_canvas_size ();
+ }
+
+ void paint_cell_contents_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg) const;
+
+ const table_cell_content &get_content () const { return m_content; }
+
+ private:
+ friend class table_cell_sizes;
+ rect_t m_rect;
+ table_cell_content m_content;
+ x_align m_x_align;
+ y_align m_y_align;
+ };
+
+ table (size_t size);
+ ~table () = default;
+ table (table &&) = default;
+ table (const table &) = delete;
+ table &operator= (const table &) = delete;
+
+ const size_t &get_size () const { return m_size; }
+
+ int add_row ()
+ {
+ m_size.h++;
+ m_occupancy.add_row (-1);
+ return m_size.h - 1; // return the table_y of the newly-added row
+ }
+
+ void set_cell (coord_t coord,
+ table_cell_content &&content,
+ enum x_align x_align = x_align::CENTER,
+ enum y_align y_align = y_align::CENTER);
+
+ void set_cell_span (rect_t span,
+ table_cell_content &&content,
+ enum x_align x_align = x_align::CENTER,
+ enum y_align y_align = y_align::CENTER);
+
+ canvas to_canvas (const theme &theme, const style_manager &sm) const;
+
+ void paint_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg,
+ const theme &theme) const;
+
+ void debug () const;
+
+ /* Self-test support. */
+ const cell_placement *get_placement_at (coord_t coord) const;
+
+ private:
+ int get_occupancy_safe (coord_t coord) const;
+ directions get_connections (int table_x, int table_y) const;
+ void paint_cell_borders_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg,
+ const theme &theme) const;
+ void paint_cell_contents_to_canvas(canvas &canvas,
+ canvas::coord_t offset,
+ const table_geometry &tg) const;
+
+ friend class table_cell_sizes;
+
+ size_t m_size;
+ std::vector<cell_placement> m_placements;
+ array2<int, size_t, coord_t> m_occupancy; /* indices into the m_placements vec. */
+};
+
+/* A workspace for computing the row heights and column widths
+ of a table (in canvas units).
+ The col_widths and row_heights could be shared between multiple
+ instances, for aligning multiple tables vertically or horizontally. */
+
+class table_cell_sizes
+{
+ public:
+ table_cell_sizes (table_dimension_sizes &col_widths,
+ table_dimension_sizes &row_heights)
+ : m_col_widths (col_widths),
+ m_row_heights (row_heights)
+ {
+ }
+
+ void pass_1 (const table &table);
+ void pass_2 (const table &table);
+
+ canvas::size_t get_canvas_size (const table::rect_t &rect) const;
+
+ table_dimension_sizes &m_col_widths;
+ table_dimension_sizes &m_row_heights;
+};
+
+/* A class responsible for mapping from table cell coords
+ to canvas coords, handling column widths.
+ It's the result of solving "how big are all the table cells and where
+ do they go?"
+ The cell_sizes are passed in, for handling aligning multiple tables,
+ sharing column widths or row heights. */
+
+class table_geometry
+{
+ public:
+ table_geometry (const table &table, table_cell_sizes &cell_sizes);
+
+ void recalc_coords ();
+
+ const canvas::size_t get_canvas_size () const { return m_canvas_size; }
+
+ canvas::coord_t table_to_canvas (table::coord_t table_coord) const;
+ int table_x_to_canvas_x (int table_x) const;
+ int table_y_to_canvas_y (int table_y) const;
+
+ int get_col_width (int table_x) const
+ {
+ return m_cell_sizes.m_col_widths.m_requirements[table_x];
+ }
+
+ canvas::size_t get_canvas_size (const table::rect_t &rect) const
+ {
+ return m_cell_sizes.get_canvas_size (rect);
+ }
+
+ private:
+ const table &m_table;
+ table_cell_sizes &m_cell_sizes;
+ canvas::size_t m_canvas_size;
+
+ /* Start canvas column of table cell, including leading border. */
+ std::vector<int> m_col_start_x;
+
+ /* Start canvas row of table cell, including leading border. */
+ std::vector<int> m_row_start_y;
+};
+
+/* Helper class for handling the simple case of a single table
+ that doesn't need to be aligned with respect to anything else. */
+
+struct simple_table_geometry
+{
+ simple_table_geometry (const table &table);
+
+ table_dimension_sizes m_col_widths;
+ table_dimension_sizes m_row_heights;
+ table_cell_sizes m_cell_sizes;
+ table_geometry m_tg;
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_TABLE_H */
diff --git a/gcc/text-art/theme.cc b/gcc/text-art/theme.cc
new file mode 100644
index 0000000..19c39fa
--- /dev/null
+++ b/gcc/text-art/theme.cc
@@ -0,0 +1,184 @@
+/* Classes for abstracting ascii vs unicode output.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "pretty-print.h"
+#include "selftest.h"
+#include "text-art/selftests.h"
+#include "text-art/ruler.h"
+#include "text-art/theme.h"
+
+using namespace text_art;
+
+/* class theme. */
+
+void
+theme::paint_y_arrow (canvas &canvas,
+ int canvas_x,
+ canvas::range_t y_range,
+ y_arrow_dir dir,
+ style::id_t style_id) const
+{
+ int canvas_y;
+ int delta_y;
+ const canvas::cell_t head (get_cppchar (dir == y_arrow_dir::UP
+ ? cell_kind::Y_ARROW_UP_HEAD
+ : cell_kind::Y_ARROW_DOWN_HEAD),
+ false, style_id);
+ const canvas::cell_t tail (get_cppchar (dir == y_arrow_dir::UP
+ ? cell_kind::Y_ARROW_UP_TAIL
+ : cell_kind::Y_ARROW_DOWN_TAIL),
+ false, style_id);
+ if (dir == y_arrow_dir::UP)
+ {
+ canvas_y = y_range.get_max ();
+ delta_y = -1;
+ }
+ else
+ {
+ canvas_y = y_range.get_min ();
+ delta_y = 1;
+ }
+ for (int len = y_range.get_size (); len; len--)
+ {
+ const canvas::cell_t cell = (len > 1) ? tail : head;
+ canvas.paint (canvas::coord_t (canvas_x, canvas_y), cell);
+ canvas_y += delta_y;
+ }
+}
+
+/* class ascii_theme : public theme. */
+
+canvas::cell_t
+ascii_theme::get_line_art (directions line_dirs) const
+{
+ if (line_dirs.m_up
+ && line_dirs.m_down
+ && !(line_dirs.m_left || line_dirs.m_right))
+ return canvas::cell_t ('|');
+ if (line_dirs.m_left
+ && line_dirs.m_right
+ && !(line_dirs.m_up || line_dirs.m_down))
+ return canvas::cell_t ('-');
+ if (line_dirs.m_up
+ || line_dirs.m_down
+ || line_dirs.m_left
+ || line_dirs.m_right)
+ return canvas::cell_t ('+');
+ return canvas::cell_t (' ');
+}
+
+cppchar_t
+ascii_theme::get_cppchar (enum cell_kind kind) const
+{
+ switch (kind)
+ {
+ default:
+ gcc_unreachable ();
+ case cell_kind::X_RULER_LEFT_EDGE:
+ return '|';
+ case cell_kind::X_RULER_MIDDLE:
+ return '~';
+ case cell_kind::X_RULER_INTERNAL_EDGE:
+ return '|';
+ case cell_kind::X_RULER_CONNECTOR_TO_LABEL_BELOW:
+ case cell_kind::X_RULER_CONNECTOR_TO_LABEL_ABOVE:
+ return '+';
+ case cell_kind::X_RULER_RIGHT_EDGE:
+ return '|';
+ case cell_kind::X_RULER_VERTICAL_CONNECTOR:
+ return '|';
+
+ case cell_kind::TEXT_BORDER_HORIZONTAL:
+ return '-';
+ case cell_kind::TEXT_BORDER_VERTICAL:
+ return '|';
+ case cell_kind::TEXT_BORDER_TOP_LEFT:
+ case cell_kind::TEXT_BORDER_TOP_RIGHT:
+ case cell_kind::TEXT_BORDER_BOTTOM_LEFT:
+ case cell_kind::TEXT_BORDER_BOTTOM_RIGHT:
+ return '+';
+
+ case cell_kind::Y_ARROW_UP_HEAD: return '^';
+ case cell_kind::Y_ARROW_DOWN_HEAD: return 'v';
+
+ case cell_kind::Y_ARROW_UP_TAIL:
+ case cell_kind::Y_ARROW_DOWN_TAIL:
+ return '|';
+ }
+}
+
+/* class unicode_theme : public theme. */
+
+canvas::cell_t
+unicode_theme::get_line_art (directions line_dirs) const
+{
+ return canvas::cell_t (get_box_drawing_char (line_dirs));
+}
+
+cppchar_t
+unicode_theme::get_cppchar (enum cell_kind kind) const
+{
+ switch (kind)
+ {
+ default:
+ gcc_unreachable ();
+ case cell_kind::X_RULER_LEFT_EDGE:
+ return 0x251C; /* "├": U+251C: BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
+ case cell_kind::X_RULER_MIDDLE:
+ return 0x2500; /* "─": U+2500: BOX DRAWINGS LIGHT HORIZONTAL */
+ case cell_kind::X_RULER_INTERNAL_EDGE:
+ return 0x253C; /* "┼": U+253C: BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */
+ case cell_kind::X_RULER_CONNECTOR_TO_LABEL_BELOW:
+ return 0x252C; /* "┬": U+252C: BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */
+ case cell_kind::X_RULER_CONNECTOR_TO_LABEL_ABOVE:
+ return 0x2534; /* "┴": U+2534: BOX DRAWINGS LIGHT UP AND HORIZONTAL */
+ case cell_kind::X_RULER_RIGHT_EDGE:
+ return 0x2524; /* "┤": U+2524: BOX DRAWINGS LIGHT VERTICAL AND LEFT */
+ case cell_kind::X_RULER_VERTICAL_CONNECTOR:
+ return 0x2502; /* "│": U+2502: BOX DRAWINGS LIGHT VERTICAL */
+
+ case cell_kind::TEXT_BORDER_HORIZONTAL:
+ return 0x2500; /* "─": U+2500: BOX DRAWINGS LIGHT HORIZONTAL */
+ case cell_kind::TEXT_BORDER_VERTICAL:
+ return 0x2502; /* "│": U+2502: BOX DRAWINGS LIGHT VERTICAL */
+
+ /* Round corners. */
+ case cell_kind::TEXT_BORDER_TOP_LEFT:
+ return 0x256D; /* "╭": U+256D BOX DRAWINGS LIGHT ARC DOWN AND RIGHT. */
+ case cell_kind::TEXT_BORDER_TOP_RIGHT:
+ return 0x256E; /* "╮": U+256E BOX DRAWINGS LIGHT ARC DOWN AND LEFT. */
+ case cell_kind::TEXT_BORDER_BOTTOM_LEFT:
+ return 0x2570; /* "╰": U+2570 BOX DRAWINGS LIGHT ARC UP AND RIGHT. */
+ case cell_kind::TEXT_BORDER_BOTTOM_RIGHT:
+ return 0x256F; /* "╯": U+256F BOX DRAWINGS LIGHT ARC UP AND LEFT. */
+
+ case cell_kind::Y_ARROW_UP_HEAD:
+ return '^';
+ case cell_kind::Y_ARROW_DOWN_HEAD:
+ return 'v';
+ case cell_kind::Y_ARROW_UP_TAIL:
+ case cell_kind::Y_ARROW_DOWN_TAIL:
+ return 0x2502; /* "│": U+2502: BOX DRAWINGS LIGHT VERTICAL */
+ }
+}
diff --git a/gcc/text-art/theme.h b/gcc/text-art/theme.h
new file mode 100644
index 0000000..8edbc6e
--- /dev/null
+++ b/gcc/text-art/theme.h
@@ -0,0 +1,123 @@
+/* Classes for abstracting ascii vs unicode output.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_THEME_H
+#define GCC_TEXT_ART_THEME_H
+
+#include "text-art/canvas.h"
+#include "text-art/box-drawing.h"
+
+namespace text_art {
+
+class theme
+{
+ public:
+ enum class cell_kind
+ {
+ /* A left-hand edge of a range e.g. "├". */
+ X_RULER_LEFT_EDGE,
+
+ /* Within a range e.g. "─". */
+ X_RULER_MIDDLE,
+
+ /* A border between two neighboring ranges e.g. "┼". */
+ X_RULER_INTERNAL_EDGE,
+
+ /* The connector with the text label within a range e.g. "┬". */
+ X_RULER_CONNECTOR_TO_LABEL_BELOW,
+
+ /* As above, but when the text label is above the ruler. */
+ X_RULER_CONNECTOR_TO_LABEL_ABOVE,
+
+ /* The vertical connection to a text label. */
+ X_RULER_VERTICAL_CONNECTOR,
+
+ /* A right-hand edge of a range e.g. "┤". */
+ X_RULER_RIGHT_EDGE,
+
+ TEXT_BORDER_HORIZONTAL,
+ TEXT_BORDER_VERTICAL,
+ TEXT_BORDER_TOP_LEFT,
+ TEXT_BORDER_TOP_RIGHT,
+ TEXT_BORDER_BOTTOM_LEFT,
+ TEXT_BORDER_BOTTOM_RIGHT,
+
+ Y_ARROW_UP_HEAD,
+ Y_ARROW_UP_TAIL,
+ Y_ARROW_DOWN_HEAD,
+ Y_ARROW_DOWN_TAIL,
+ };
+
+ virtual ~theme () = default;
+
+ virtual bool unicode_p () const = 0;
+ virtual bool emojis_p () const = 0;
+
+ virtual canvas::cell_t
+ get_line_art (directions line_dirs) const = 0;
+
+ canvas::cell_t get_cell (enum cell_kind kind, unsigned style_idx) const
+ {
+ return canvas::cell_t (get_cppchar (kind), false, style_idx);
+ }
+
+ virtual cppchar_t get_cppchar (enum cell_kind kind) const = 0;
+
+ enum class y_arrow_dir { UP, DOWN };
+ void paint_y_arrow (canvas &canvas,
+ int x,
+ canvas::range_t y_range,
+ y_arrow_dir dir,
+ style::id_t style_id) const;
+};
+
+class ascii_theme : public theme
+{
+ public:
+ bool unicode_p () const final override { return false; }
+ bool emojis_p () const final override { return false; }
+
+ canvas::cell_t
+ get_line_art (directions line_dirs) const final override;
+
+ cppchar_t get_cppchar (enum cell_kind kind) const final override;
+};
+
+class unicode_theme : public theme
+{
+ public:
+ bool unicode_p () const final override { return true; }
+ bool emojis_p () const override { return false; }
+
+ canvas::cell_t
+ get_line_art (directions line_dirs) const final override;
+
+ cppchar_t get_cppchar (enum cell_kind kind) const final override;
+};
+
+class emoji_theme : public unicode_theme
+{
+public:
+ bool emojis_p () const final override { return true; }
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_THEME_H */
diff --git a/gcc/text-art/types.h b/gcc/text-art/types.h
new file mode 100644
index 0000000..ea4ff4b
--- /dev/null
+++ b/gcc/text-art/types.h
@@ -0,0 +1,510 @@
+/* Types for drawing 2d "text art".
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_TYPES_H
+#define GCC_TEXT_ART_TYPES_H
+
+/* This header uses std::vector, but <vector> can't be directly
+ included due to issues with macros. Hence it must be included from
+ system.h by defining INCLUDE_MEMORY in any source file using it. */
+
+#ifndef INCLUDE_VECTOR
+# error "You must define INCLUDE_VECTOR before including system.h to use text-art/types.h"
+#endif
+
+#include "cpplib.h"
+#include "pretty-print.h"
+
+namespace text_art {
+
+/* Forward decls. */
+
+class canvas;
+class table;
+class theme;
+
+/* Classes for geometry.
+ We use templates to avoid mixing up e.g. canvas coordinates
+ with table coordinates. */
+
+template <typename CoordinateSystem>
+struct size
+{
+ size (int w_, int h_) : w (w_), h (h_) {}
+ int w;
+ int h;
+};
+
+template <typename CoordinateSystem>
+struct coord
+{
+ coord (int x_, int y_) : x (x_), y (y_) {}
+ int x;
+ int y;
+};
+
+template <typename CoordinateSystem>
+coord<CoordinateSystem> operator+ (coord<CoordinateSystem> a,
+ coord<CoordinateSystem> b)
+{
+ return coord<CoordinateSystem> (a.x + b.x, a.y + b.y);
+}
+
+/* A half-open range [start, next) of int. */
+
+template <typename CoordinateSystem>
+struct range
+{
+ range (int start_, int next_)
+ : start (start_), next (next_)
+ {}
+
+ int get_min () const { return start; }
+ int get_max () const { return next - 1; }
+ int get_next () const { return next; }
+ int get_size () const { return next - start; }
+
+ int get_midpoint () const { return get_min () + get_size () / 2; }
+
+ int start;
+ int next;
+};
+
+/* A rectangle area within CoordinateSystem. */
+
+template <typename CoordinateSystem>
+struct rect
+{
+ rect (coord<CoordinateSystem> top_left,
+ size<CoordinateSystem> size)
+ : m_top_left (top_left),
+ m_size (size)
+ {
+ }
+
+ rect (range<CoordinateSystem> x_range,
+ range<CoordinateSystem> y_range)
+ : m_top_left (x_range.get_min (), y_range.get_min ()),
+ m_size (x_range.get_size (), y_range.get_size ())
+ {
+ }
+
+ int get_min_x () const { return m_top_left.x; }
+ int get_min_y () const { return m_top_left.y; }
+ int get_max_x () const { return m_top_left.x + m_size.w - 1; }
+ int get_max_y () const { return m_top_left.y + m_size.h - 1; }
+ int get_next_x () const { return m_top_left.x + m_size.w; }
+ int get_next_y () const { return m_top_left.y + m_size.h; }
+
+ range<CoordinateSystem> get_x_range () const
+ {
+ return range<CoordinateSystem> (get_min_x (), get_next_x ());
+ }
+ range<CoordinateSystem> get_y_range () const
+ {
+ return range<CoordinateSystem> (get_min_y (), get_next_y ());
+ }
+
+ int get_width () const { return m_size.w; }
+ int get_height () const { return m_size.h; }
+
+ coord<CoordinateSystem> m_top_left;
+ size<CoordinateSystem> m_size;
+};
+
+template <typename ElementType, typename SizeType, typename CoordType>
+class array2
+{
+ public:
+ typedef ElementType element_t;
+ typedef SizeType size_t;
+ typedef CoordType coord_t;
+
+ array2 (size_t sz)
+ : m_size (sz),
+ m_elements (sz.w * sz.h)
+ {
+ }
+ array2 (array2 &&other)
+ : m_size (other.m_size),
+ m_elements (std::move (other.m_elements))
+ {
+ }
+
+ /* Move assignment not implemented or used. */
+ array2 &operator== (array2 &&other) = delete;
+
+ /* No copy ctor or assignment op. */
+ array2 (const array2 &other) = delete;
+ array2 &operator= (const array2 &other) = delete;
+
+
+ const size_t &get_size () const { return m_size; }
+
+ void add_row (const element_t &element)
+ {
+ m_size.h++;
+ m_elements.insert (m_elements.end (), m_size.w, element);
+ }
+
+ const element_t &get (const coord_t &coord) const
+ {
+ ::size_t idx = get_idx (coord);
+ return m_elements[idx];
+ }
+
+ void set (const coord_t &coord, const element_t &element)
+ {
+ ::size_t idx = get_idx (coord);
+ m_elements[idx] = element;
+ }
+
+ void fill (element_t element)
+ {
+ for (int y = 0; y < m_size.h; y++)
+ for (int x = 0; x < m_size.w; x++)
+ set (coord_t (x, y), element);
+ }
+
+ private:
+ ::size_t get_idx (const coord_t &coord) const
+ {
+ gcc_assert (coord.x >= 0);
+ gcc_assert (coord.x < m_size.w);
+ gcc_assert (coord.y >= 0);
+ gcc_assert (coord.y < m_size.h);
+ return (coord.y * m_size.w) + coord.x;
+ }
+
+ size_t m_size;
+ std::vector<element_t> m_elements;
+};
+
+/* A combination of attributes describing how to style a text cell.
+ We only support those attributes mentioned in invoke.texi:
+ - bold,
+ - underscore,
+ - blink,
+ - inverse,
+ - colors for foreground and background:
+ - default color
+ - named colors
+ - 16-color mode colors (the "bright" variants)
+ - 88-color mode
+ - 256-color mode
+ plus URLs. */
+
+struct style
+{
+ typedef unsigned char id_t;
+ static const id_t id_plain = 0;
+
+ /* Colors. */
+ enum class named_color
+ {
+ DEFAULT,
+ // ANSI order
+ BLACK,
+ RED,
+ GREEN,
+ YELLOW,
+ BLUE,
+ MAGENTA,
+ CYAN,
+ WHITE
+ };
+
+
+ struct color
+ {
+ enum class kind
+ {
+ NAMED,
+ BITS_8,
+ BITS_24,
+ } m_kind;
+
+ union
+ {
+ struct {
+ enum named_color m_name;
+ bool m_bright;
+ } m_named;
+ uint8_t m_8bit;
+ struct {
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+ } m_24bit;
+ } u;
+
+ /* Constructor for named colors. */
+ color (enum named_color name = named_color::DEFAULT,
+ bool bright = false)
+ : m_kind (kind::NAMED)
+ {
+ u.m_named.m_name = name;
+ u.m_named.m_bright = bright;
+ }
+
+ /* Constructor for 8-bit colors. */
+ color (uint8_t col_val)
+ : m_kind (kind::BITS_8)
+ {
+ u.m_8bit = col_val;
+ }
+
+ /* Constructor for 24-bit colors. */
+ color (uint8_t r, uint8_t g, uint8_t b)
+ : m_kind (kind::BITS_24)
+ {
+ u.m_24bit.r = r;
+ u.m_24bit.g = g;
+ u.m_24bit.b = b;
+ }
+
+ bool operator== (const color &other) const;
+ bool operator!= (const color &other) const
+ {
+ return !(*this == other);
+ }
+
+ void print_sgr (pretty_printer *pp, bool fg, bool &need_separator) const;
+ };
+
+ style ()
+ : m_bold (false),
+ m_underscore (false),
+ m_blink (false),
+ m_reverse (false),
+ m_fg_color (named_color::DEFAULT),
+ m_bg_color (named_color::DEFAULT),
+ m_url ()
+ {}
+
+ bool operator== (const style &other) const
+ {
+ return (m_bold == other.m_bold
+ && m_underscore == other.m_underscore
+ && m_blink == other.m_blink
+ && m_reverse == other.m_reverse
+ && m_fg_color == other.m_fg_color
+ && m_bg_color == other.m_bg_color
+ && m_url == other.m_url);
+ }
+
+ style &set_style_url (const char *url);
+
+ static void print_changes (pretty_printer *pp,
+ const style &old_style,
+ const style &new_style);
+
+ bool m_bold;
+ bool m_underscore;
+ bool m_blink;
+ bool m_reverse;
+ color m_fg_color;
+ color m_bg_color;
+ std::vector<cppchar_t> m_url; // empty = no URL
+};
+
+/* A class to keep track of all the styles in use in a drawing, so that
+ we can refer to them via the compact style::id_t type, rather than
+ via e.g. pointers. */
+
+class style_manager
+{
+ public:
+ style_manager ();
+ style::id_t get_or_create_id (const style &style);
+ const style &get_style (style::id_t id) const
+ {
+ return m_styles[id];
+ }
+ void print_any_style_changes (pretty_printer *pp,
+ style::id_t old_id,
+ style::id_t new_id) const;
+ unsigned get_num_styles () const { return m_styles.size (); }
+
+private:
+ std::vector<style> m_styles;
+};
+
+class styled_unichar
+{
+ public:
+ friend class styled_string;
+
+ explicit styled_unichar ()
+ : m_code (0),
+ m_style_id (style::id_plain)
+ {}
+ explicit styled_unichar (cppchar_t ch)
+ : m_code (ch),
+ m_emoji_variant_p (false),
+ m_style_id (style::id_plain)
+ {}
+ explicit styled_unichar (cppchar_t ch, bool emoji, style::id_t style_id)
+ : m_code (ch),
+ m_emoji_variant_p (emoji),
+ m_style_id (style_id)
+ {
+ gcc_assert (style_id <= 0x7f);
+ }
+
+ cppchar_t get_code () const { return m_code; }
+ bool emoji_variant_p () const { return m_emoji_variant_p; }
+ style::id_t get_style_id () const { return m_style_id; }
+
+ bool double_width_p () const
+ {
+ int width = cpp_wcwidth (get_code ());
+ gcc_assert (width == 1 || width == 2);
+ return width == 2;
+ }
+
+ bool operator== (const styled_unichar &other) const
+ {
+ return (m_code == other.m_code
+ && m_emoji_variant_p == other.m_emoji_variant_p
+ && m_style_id == other.m_style_id);
+ }
+
+ void set_emoji_variant () { m_emoji_variant_p = true; }
+
+ int get_canvas_width () const
+ {
+ return cpp_wcwidth (m_code);
+ }
+
+ void add_combining_char (cppchar_t ch)
+ {
+ m_combining_chars.push_back (ch);
+ }
+
+ const std::vector<cppchar_t> get_combining_chars () const
+ {
+ return m_combining_chars;
+ }
+
+private:
+ cppchar_t m_code : 24;
+ bool m_emoji_variant_p : 1;
+ style::id_t m_style_id : 7;
+ std::vector<cppchar_t> m_combining_chars;
+};
+
+class styled_string
+{
+ public:
+ explicit styled_string () = default;
+ explicit styled_string (style_manager &sm, const char *str);
+ explicit styled_string (cppchar_t cppchar, bool emoji = false);
+
+ styled_string (styled_string &&) = default;
+ styled_string &operator= (styled_string &&) = default;
+
+ /* No copy ctor or assignment op. */
+ styled_string (const styled_string &) = delete;
+ styled_string &operator= (const styled_string &) = delete;
+
+ /* For the few cases where copying is required, spell it out explicitly. */
+ styled_string copy () const
+ {
+ styled_string result;
+ result.m_chars = m_chars;
+ return result;
+ }
+
+ bool operator== (const styled_string &other) const
+ {
+ return m_chars == other.m_chars;
+ }
+
+ static styled_string from_fmt (style_manager &sm,
+ printer_fn format_decoder,
+ const char *fmt, ...)
+ ATTRIBUTE_GCC_PPDIAG(3, 4);
+ static styled_string from_fmt_va (style_manager &sm,
+ printer_fn format_decoder,
+ const char *fmt,
+ va_list *args)
+ ATTRIBUTE_GCC_PPDIAG(3, 0);
+
+ size_t size () const { return m_chars.size (); }
+ styled_unichar operator[] (size_t idx) const { return m_chars[idx]; }
+
+ std::vector<styled_unichar>::const_iterator begin () const
+ {
+ return m_chars.begin ();
+ }
+ std::vector<styled_unichar>::const_iterator end () const
+ {
+ return m_chars.end ();
+ }
+
+ int calc_canvas_width () const;
+
+ void append (const styled_string &suffix);
+
+ void set_url (style_manager &sm, const char *url);
+
+private:
+ std::vector<styled_unichar> m_chars;
+};
+
+enum class x_align
+{
+ LEFT,
+ CENTER,
+ RIGHT
+};
+
+enum class y_align
+{
+ TOP,
+ CENTER,
+ BOTTOM
+};
+
+/* A set of cardinal directions within a canvas or table. */
+
+struct directions
+{
+public:
+ directions (bool up, bool down, bool left, bool right)
+ : m_up (up), m_down (down), m_left (left), m_right (right)
+ {
+ }
+
+ size_t as_index () const
+ {
+ return (m_up << 3) | (m_down << 2) | (m_left << 1) | m_right;
+ }
+
+ bool m_up: 1;
+ bool m_down: 1;
+ bool m_left: 1;
+ bool m_right: 1;
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_TYPES_H */
diff --git a/gcc/text-art/widget.cc b/gcc/text-art/widget.cc
new file mode 100644
index 0000000..b64a623
--- /dev/null
+++ b/gcc/text-art/widget.cc
@@ -0,0 +1,276 @@
+/* Hierarchical diagram elements.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 3, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#include "config.h"
+#define INCLUDE_MEMORY
+#define INCLUDE_VECTOR
+#include "system.h"
+#include "coretypes.h"
+#include "pretty-print.h"
+#include "selftest.h"
+#include "make-unique.h"
+#include "text-art/selftests.h"
+#include "text-art/widget.h"
+
+using namespace text_art;
+
+/* class text_art::widget. */
+
+canvas
+widget::to_canvas (const style_manager &style_mgr)
+{
+ const canvas::size_t req_size = get_req_size ();
+
+ /* For now we don't constrain the allocation; we give
+ the widget the full size it requested, and widgets
+ assume they got their full size request. */
+ const canvas::size_t alloc_size = req_size;
+
+ set_alloc_rect (canvas::rect_t (canvas::coord_t (0, 0), alloc_size));
+ canvas c (alloc_size, style_mgr);
+ paint_to_canvas (c);
+ return c;
+}
+
+/* class text_art::vbox_widget : public text_art::container_widget. */
+
+const char *
+vbox_widget::get_desc () const
+{
+ return "vbox_widget";
+}
+
+canvas::size_t
+vbox_widget::calc_req_size ()
+{
+ canvas::size_t result (0, 0);
+ for (auto &child : m_children)
+ {
+ canvas::size_t child_req_size = child->get_req_size();
+ result.h += child_req_size.h;
+ result.w = std::max (result.w, child_req_size.w);
+ }
+ return result;
+}
+
+void
+vbox_widget::update_child_alloc_rects ()
+{
+ const int x = get_min_x ();
+ int y = get_min_y ();
+ for (auto &child : m_children)
+ {
+ child->set_alloc_rect
+ (canvas::rect_t (canvas::coord_t (x, y),
+ canvas::size_t (get_alloc_w (),
+ child->get_req_h ())));
+ y += child->get_req_h ();
+ }
+}
+
+/* class text_art::text_widget : public text_art::leaf_widget. */
+
+const char *
+text_widget::get_desc () const
+{
+ return "text_widget";
+}
+
+canvas::size_t
+text_widget::calc_req_size ()
+{
+ return canvas::size_t (m_str.size (), 1);
+}
+
+void
+text_widget::paint_to_canvas (canvas &canvas)
+{
+ canvas.paint_text (get_top_left (), m_str);
+}
+
+/* class text_art::canvas_widget : public text_art::leaf_widget. */
+
+const char *
+canvas_widget::get_desc () const
+{
+ return "canvas_widget";
+}
+
+canvas::size_t
+canvas_widget::calc_req_size ()
+{
+ return m_canvas.get_size ();
+}
+
+void
+canvas_widget::paint_to_canvas (canvas &canvas)
+{
+ for (int y = 0; y < m_canvas.get_size ().h; y++)
+ for (int x = 0; x < m_canvas.get_size ().w; x++)
+ {
+ canvas::coord_t rel_xy (x, y);
+ canvas.paint (get_top_left () + rel_xy,
+ m_canvas.get (rel_xy));
+ }
+}
+
+#if CHECKING_P
+
+namespace selftest {
+
+/* Concrete widget subclass for writing selftests.
+ Requests a hard-coded size, and fills its allocated rectangle
+ with a specific character. */
+
+class test_widget : public leaf_widget
+{
+public:
+ test_widget (canvas::size_t size, char ch)
+ : m_test_size (size), m_ch (ch)
+ {}
+
+ const char *get_desc () const final override
+ {
+ return "test_widget";
+ }
+ canvas::size_t calc_req_size () final override
+ {
+ return m_test_size;
+ }
+ void paint_to_canvas (canvas &canvas) final override
+ {
+ canvas.fill (get_alloc_rect (), canvas::cell_t (m_ch));
+ }
+
+private:
+ canvas::size_t m_test_size;
+ char m_ch;
+};
+
+static void
+test_test_widget ()
+{
+ style_manager sm;
+ test_widget w (canvas::size_t (3, 3), 'A');
+ canvas c (w.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("AAA\n"
+ "AAA\n"
+ "AAA\n"));
+}
+
+static void
+test_text_widget ()
+{
+ style_manager sm;
+ text_widget w (styled_string (sm, "hello world"));
+ canvas c (w.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("hello world\n"));
+}
+
+static void
+test_wrapper_widget ()
+{
+ style_manager sm;
+ wrapper_widget w (::make_unique<test_widget> (canvas::size_t (3, 3), 'B'));
+ canvas c (w.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("BBB\n"
+ "BBB\n"
+ "BBB\n"));
+}
+
+static void
+test_vbox_1 ()
+{
+ style_manager sm;
+ vbox_widget w;
+ for (int i = 0; i < 5; i++)
+ w.add_child
+ (::make_unique <text_widget>
+ (styled_string::from_fmt (sm, nullptr,
+ "this is line %i", i)));
+ canvas c (w.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("this is line 0\n"
+ "this is line 1\n"
+ "this is line 2\n"
+ "this is line 3\n"
+ "this is line 4\n"));
+}
+
+static void
+test_vbox_2 ()
+{
+ style_manager sm;
+ vbox_widget w;
+ w.add_child (::make_unique<test_widget> (canvas::size_t (1, 3), 'A'));
+ w.add_child (::make_unique<test_widget> (canvas::size_t (4, 1), 'B'));
+ w.add_child (::make_unique<test_widget> (canvas::size_t (1, 2), 'C'));
+ canvas c (w.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("AAAA\n"
+ "AAAA\n"
+ "AAAA\n"
+ "BBBB\n"
+ "CCCC\n"
+ "CCCC\n"));
+}
+
+static void
+test_canvas_widget ()
+{
+ style_manager sm;
+ canvas inner_canvas (canvas::size_t (5, 3), sm);
+ inner_canvas.fill (canvas::rect_t (canvas::coord_t (0, 0),
+ canvas::size_t (5, 3)),
+ canvas::cell_t ('a'));
+ canvas_widget cw (std::move (inner_canvas));
+ canvas c (cw.to_canvas (sm));
+ ASSERT_CANVAS_STREQ
+ (c, false,
+ ("aaaaa\n"
+ "aaaaa\n"
+ "aaaaa\n"));
+}
+
+/* Run all selftests in this file. */
+
+void
+text_art_widget_cc_tests ()
+{
+ test_test_widget ();
+ test_text_widget ();
+ test_wrapper_widget ();
+ test_vbox_1 ();
+ test_vbox_2 ();
+ test_canvas_widget ();
+}
+
+} // namespace selftest
+
+
+#endif /* #if CHECKING_P */
diff --git a/gcc/text-art/widget.h b/gcc/text-art/widget.h
new file mode 100644
index 0000000..8798e43
--- /dev/null
+++ b/gcc/text-art/widget.h
@@ -0,0 +1,245 @@
+/* Hierarchical diagram elements.
+ Copyright (C) 2023 Free Software Foundation, Inc.
+ Contributed by David Malcolm <dmalcolm@redhat.com>.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3, or (at your option)
+any later version.
+
+GCC is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING3. If not see
+<http://www.gnu.org/licenses/>. */
+
+#ifndef GCC_TEXT_ART_WIDGET_H
+#define GCC_TEXT_ART_WIDGET_H
+
+#include "text-art/canvas.h"
+#include "text-art/table.h"
+
+namespace text_art {
+
+/* Abstract base class: something that knows how to size itself and
+ how to paint itself to a canvas, potentially with children, with
+ support for hierarchical sizing and positioning.
+
+ Widgets have a two-phase sizing/positioning algorithm.
+
+ Step 1: size requests: the root widget is asked for its size request i.e
+ how big it wants to be. This is handled by recursively asking child
+ widgets for their requested sizes. Each widget subclass can implement
+ their own logic for this in the "calc_req_size" vfunc, and the result
+ is cached in m_req_size.
+
+ Step 2: rect allocation: the root widget is set a canvas::rect_t as
+ its "allocated" rectangle. Each widget subclass can then place its
+ children recursively using the "update_child_alloc_rects" vfunc.
+ For simplicity, all coordinates in the hierarchy are within the same
+ coordinate system (rather than attempting to store per-child offsets).
+
+ Widget subclasses are responsible for managing their own children. */
+
+/* Subclasses in this header, with indentation indicating inheritance. */
+
+class widget; /* Abstract base class. */
+ class wrapper_widget; /* Concrete subclass: a widget with a single child. */
+ class container_widget; /* Abstract subclass: widgets with an arbitrary
+ number of children. */
+ class vbox_widget; /* Concrete widget subclass: lay out children
+ vertically. */
+ class leaf_widget; /* Abstract subclass: a widget with no children. */
+ class text_widget; /* Concrete subclass: a text string. */
+ class canvas_widget; /* Concrete subclass: a pre-rendered canvas. */
+
+class widget
+{
+ public:
+ /* This can be very useful for debugging when implementing new
+ widget subclasses. */
+ static const bool DEBUG_GEOMETRY = false;
+
+ virtual ~widget () {}
+
+ canvas to_canvas (const style_manager &style_mgr);
+
+ canvas::size_t get_req_size ()
+ {
+ m_req_size = calc_req_size();
+ if (DEBUG_GEOMETRY)
+ fprintf (stderr, "calc_req_size (%s) -> (w:%i, h:%i)\n",
+ get_desc (),
+ m_req_size.w, m_req_size.h);
+ return m_req_size;
+ }
+
+ void set_alloc_rect (const canvas::rect_t &rect)
+ {
+ if (DEBUG_GEOMETRY)
+ fprintf (stderr, "set_alloc_rect (%s): ((x:%i, y:%i), (w:%i, h:%i))\n",
+ get_desc (),
+ rect.m_top_left.x, rect.m_top_left.y,
+ rect.m_size.w, rect.m_size.h);
+ m_alloc_rect = rect;
+ update_child_alloc_rects ();
+ }
+
+ virtual const char *get_desc () const = 0;
+ virtual canvas::size_t calc_req_size () = 0;
+ virtual void update_child_alloc_rects () = 0;
+ virtual void paint_to_canvas (canvas &canvas) = 0;
+
+ /* Access to the cached size request of this widget. */
+ const canvas::size_t get_req_size () const { return m_req_size; }
+ int get_req_w () const { return m_req_size.w; }
+ int get_req_h () const { return m_req_size.h; }
+
+ /* Access to the allocated canvas coordinates of this widget. */
+ const canvas::rect_t &get_alloc_rect () const { return m_alloc_rect; }
+ int get_alloc_w () const { return m_alloc_rect.get_width (); }
+ int get_alloc_h () const { return m_alloc_rect.get_height (); }
+ int get_min_x () const { return m_alloc_rect.get_min_x (); }
+ int get_max_x () const { return m_alloc_rect.get_max_x (); }
+ int get_next_x () const { return m_alloc_rect.get_next_x (); }
+ int get_min_y () const { return m_alloc_rect.get_min_y (); }
+ int get_max_y () const { return m_alloc_rect.get_max_y (); }
+ int get_next_y () const { return m_alloc_rect.get_max_y (); }
+ canvas::range_t get_x_range () const { return m_alloc_rect.get_x_range (); }
+ canvas::range_t get_y_range () const { return m_alloc_rect.get_y_range (); }
+ const canvas::coord_t &get_top_left () const
+ {
+ return m_alloc_rect.m_top_left;
+ }
+
+ protected:
+ widget ()
+ : m_req_size (0, 0),
+ m_alloc_rect (canvas::coord_t (0, 0),
+ canvas::size_t (0, 0))
+ {}
+
+private:
+ /* How much size this widget requested. */
+ canvas::size_t m_req_size;
+ /* Where (and how big) this widget was allocated. */
+ canvas::rect_t m_alloc_rect;
+};
+
+/* Concrete subclass for a widget with a single child. */
+
+class wrapper_widget : public widget
+{
+ public:
+ wrapper_widget (std::unique_ptr<widget> child)
+ : m_child (std::move (child))
+ {}
+
+ const char *get_desc () const override
+ {
+ return "wrapper_widget";
+ }
+ canvas::size_t calc_req_size () override
+ {
+ return m_child->get_req_size ();
+ }
+ void update_child_alloc_rects ()
+ {
+ m_child->set_alloc_rect (get_alloc_rect ());
+ }
+ void paint_to_canvas (canvas &canvas) override
+ {
+ m_child->paint_to_canvas (canvas);
+ }
+ private:
+ std::unique_ptr<widget> m_child;
+};
+
+/* Abstract subclass for widgets with an arbitrary number of children. */
+
+class container_widget : public widget
+{
+ public:
+ void add_child (std::unique_ptr<widget> child)
+ {
+ m_children.push_back (std::move (child));
+ }
+
+ void paint_to_canvas (canvas &canvas) final override
+ {
+ for (auto &child : m_children)
+ child->paint_to_canvas (canvas);
+ }
+
+ protected:
+ std::vector<std::unique_ptr<widget>> m_children;
+};
+
+/* Concrete widget subclass: lay out children vertically. */
+
+class vbox_widget : public container_widget
+{
+ public:
+ const char *get_desc () const override;
+ canvas::size_t calc_req_size () override;
+ void update_child_alloc_rects () final override;
+};
+
+/* Abstract subclass for widgets with no children. */
+
+class leaf_widget : public widget
+{
+ public:
+ void update_child_alloc_rects () final override
+ {
+ /* no-op. */
+ }
+
+ protected:
+ leaf_widget () : widget () {}
+};
+
+/* Concrete widget subclass for a text string. */
+
+class text_widget : public leaf_widget
+{
+ public:
+ text_widget (styled_string str)
+ : leaf_widget (), m_str (std::move (str))
+ {
+ }
+
+ const char *get_desc () const override;
+ canvas::size_t calc_req_size () final override;
+ void paint_to_canvas (canvas &canvas) final override;
+
+private:
+ styled_string m_str;
+};
+
+/* Concrete widget subclass for a pre-rendered canvas. */
+
+class canvas_widget : public leaf_widget
+{
+ public:
+ canvas_widget (canvas &&c)
+ : leaf_widget (), m_canvas (std::move (c))
+ {
+ }
+
+ const char *get_desc () const override;
+ canvas::size_t calc_req_size () final override;
+ void paint_to_canvas (canvas &canvas) final override;
+
+private:
+ canvas m_canvas;
+};
+
+} // namespace text_art
+
+#endif /* GCC_TEXT_ART_WIDGET_H */