#include <glib/gunicode.h>
#include <pango/pango-context.h>
#include <pango/pango-layout.h>
#include <pango/pangocairo.h>
#include <stdio.h>


int main() {
    #define LIT(_lit) {_lit, sizeof("" _lit) - 1}
    struct {char const *str; unsigned len;} tsts[] = {
        LIT("consider the Thai phrase “ทำการบ้าน”, which has three components"),
        LIT("บ้าน”, which has three components"),
        LIT("syl­labi­fication"),   // soft hyphen
        LIT("We use LaΤεΧ"),   // Tau epsilon Chi
        LIT("<span lang=\"en\">didn’t he e’er say “<span lang=\"fr\">Je t’aime</span>” ?</span>"),
        LIT("<span lang=\"hu\">Gabor J.Toth</span>"),   // Actually I can't remember what language it is.
        LIT("Prof. Don­ald E. Knuth"),   // nbsp, soft hyphen
        LIT("ext2fs v2.34 sans-serif Nº ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿"),
        LIT("บ้าน¡¢£¤¥¦§¨©บ้าน"),
    };
    PangoContext *ctx;
    PangoLayout *layout;
    gint t;

    {
        PangoFontMap *pfm = pango_cairo_font_map_get_default();
        ctx = pango_cairo_font_map_create_context(PANGO_CAIRO_FONT_MAP(pfm));
        g_object_unref(pfm);
    }
    layout = pango_layout_new(ctx);

    for (t = 0; t < G_N_ELEMENTS(tsts); ++t) {
        PangoLogAttr *log_attrs = NULL;
        gint n_attrs = -1;
        gint i;
        gchar const *p, *q;
        gchar const *err;
        char const *const markup = tsts[t].str;
        unsigned const markup_len = tsts[t].len;
        char const *txt;

        if (!g_utf8_validate(markup, markup_len, &err)) {
            fprintf(stderr, "bug: markup string not valid utf8\n");
            return 1;
        }

        printf("\n%.*s\n", markup_len, markup);
        pango_layout_set_markup(layout, markup, markup_len);
        txt = pango_layout_get_text(layout);
        puts(txt);
        pango_layout_get_log_attrs(layout, &log_attrs, &n_attrs);
        p = txt;
        for (i = 0; i < n_attrs; ++i) {
            if (log_attrs[i].is_word_end) {
                putchar(')');
            }
            if (log_attrs[i].is_line_break) {
                putchar('|');
            }
            if (log_attrs[i].is_word_start) {
                putchar('(');
            }
            q = g_utf8_next_char(p);
            printf("%.*s", q - p, p);
            p = q;
        }
        putchar('\n');
        g_free(log_attrs);
    }

    return 0;
}

/*
 * Suggested rules:
 *   alnum (,alpha,digit,lower,upper,xdigit,title): inside
 *   cntrl: outside (always?)
 *   graph,print: some
 *   punct,space: outside
 *
 * So: all alnum characters (i.e. those for which g_unichar_isalnum returns true) are within
 * a word, all isspace characters are outside, most or all ispunct characters are outside
 * (and probably all in current implementation, even for the english word o’er)
 */

// vim: expandtab shiftwidth=4 softtabstop=4 tabstop=8
