// 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 const prefix[] = u8"<span font_family=\"Courier New\" size=\"12288\">";
  char const a_with_accent[] = u8"À";
  char const suffix[] = u8"</span>";

  char markup[sizeof(prefix) + (n * (sizeof(a_with_accent)) - 1)
              + sizeof(suffix) + 1];
  markup[0] = '\0';

  strcat(markup, prefix);
  for (unsigned i = 0; i < n; ++i)
    strcat(markup, a_with_accent);
  strcat(markup, suffix);

  pango_layout_set_markup(layout, markup, -1);

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

  do {
    PangoLayoutRun* run = pango_layout_iter_get_run_readonly(layout_iter);

    if (!run)
      continue;

    auto offset = run->item->offset;

    if (offset % 3) {
      std::cout << "we split an A from it's accent at offset " << offset
                << "\n";
      return 6;
    }

  } while (pango_layout_iter_next_run(layout_iter));

  return 0;
}

int main()
{
  for (unsigned n = 0; n < 100; ++n) {
    int ret = do_layout(n);
    if (ret)
      return ret;
  }
}
