#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <math.h>
#include <cairo/cairo.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>

/* comment/uncomment each of these to render in various ways */
#define VERTICAL
#define RENDER_LINE_BY_LINE
//#define ROTATE_WITH_PANGO
#define SIMPLE_LAYOUT

/* uncomment one of them */
//static const char *text="日本語";
//static const char *text "(日本語)	こんにちは, ｺﾝﾆﾁﾊ";
static const char *text="Katakana 1 &#12468;&#12454;&#12472;&#12473;";

int main()
{
  cairo_surface_t *cs=cairo_image_surface_create(CAIRO_FORMAT_ARGB32,640,480);
  PangoLayoutIter *iter;
  cairo_t *cr=cairo_create(cs);

#ifdef SIMPLE_LAYOUT
  PangoLayout *layout=pango_cairo_create_layout(cr);
  PangoContext *context=pango_layout_get_context(layout);
#else
  PangoFontMap *font_map=pango_cairo_font_map_new();
  PangoContext *context=pango_cairo_font_map_create_context((PangoCairoFontMap*)font_map);
  PangoLayout *layout=pango_layout_new(context);
#endif

  pango_layout_set_markup(layout,text,-1);

  cairo_set_source_rgba(cr,1,1,1,1);
  cairo_translate(cr,320,100);

#ifdef VERTICAL
  pango_context_set_base_gravity(context,PANGO_GRAVITY_AUTO);
#ifdef ROTATE_WITH_PANGO
  {
    PangoMatrix m=PANGO_MATRIX_INIT;
    pango_matrix_rotate(&m,90);
    pango_context_set_matrix(context,&m);
  }
#else
  cairo_rotate(cr,M_PI/2.0);
  pango_cairo_update_context(cr,context);
#endif
  pango_layout_context_changed(layout);
#endif

  cairo_save(cr);
  cairo_set_operator(cr,CAIRO_OPERATOR_SOURCE);
  cairo_set_source_rgba(cr,0,0,0,0);
  cairo_paint(cr);
  cairo_restore(cr);

  printf("gravity: base %d, for matrix %d, resolved %d\n",
      pango_context_get_base_gravity(context),
      pango_gravity_get_for_matrix(pango_context_get_matrix(context)),
      pango_context_get_gravity(context));

#ifdef RENDER_LINE_BY_LINE
  iter=pango_layout_get_iter(layout);
  do {
    PangoLayoutLine *line=pango_layout_iter_get_line_readonly(iter);
    pango_cairo_show_layout_line(cr,line);
  } while (pango_layout_iter_next_line(iter));
  pango_layout_iter_free(iter);
#else
  pango_cairo_show_layout(cr,layout);
#endif

  g_object_unref(layout);

  cairo_surface_flush(cs);
  cairo_destroy(cr);

  if (cairo_surface_write_to_png(cs,"vertical.png")!=CAIRO_STATUS_SUCCESS) {
    fprintf(stderr,"png write trouble\n");
  }

  cairo_surface_destroy(cs);

  return 0;
}

