// Compile as -std=c++1y

#include <pango/pango.h>
#include <pango/pangocairo.h>

#include <cairo/cairo.h>
#include <cairo/cairo-pdf.h>

#include <cstring>
#include <climits>
#include <iostream>

int do_layout(unsigned n)
{
  cairo_surface_t* surface
      = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
  if (!surface)
    return 1;

  cairo_t* cr = cairo_create(surface);
  if (!cr)
    return 2;

  PangoLayout* layout = pango_cairo_create_layout(cr);
  if (!layout)
    return 3;

  pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR);

  PangoContext* pango_context = pango_layout_get_context(layout);
  if (!pango_context)
    return 4;

  pango_cairo_context_set_resolution(pango_context, 72.0);
  pango_layout_context_changed(layout);

  pango_layout_set_width(layout, (72 + n) * PANGO_SCALE);
  pango_layout_set_indent(layout, 0);
  pango_layout_set_height(layout, INT_MAX);

  char markup[4096]{0};

  char const* as = u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ"
                   u8"ÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀÀ";

  strncat(strncat(strcat(markup,
                         u8"<span font_family=\"Courier New\" size=\"12288\">"),
                  as,
                  n * 3),
          u8"</span>",
          sizeof(markup));

  pango_layout_set_markup(layout, markup, -1);

  PangoLayoutIter* layout_iter = pango_layout_get_iter(layout);
  if (!layout_iter)
    return 5;

  do {
    PangoLayoutRun* layout_run
        = pango_layout_iter_get_run_readonly(layout_iter);

    if (nullptr == layout_run)
      continue;

    auto text_offset = layout_run->item->offset;

    if (text_offset % 3) {
      std::cout << "oops, we split the A from it's accent at offset "
                << text_offset << "\n";
      return 99;
    }

  } while (pango_layout_iter_next_run(layout_iter));

  return 0;
}

int main()
{
  for (unsigned n = 0; !do_layout(n); ++n)
    ;
}
