source: libcaca/trunk/cucul/export.c @ 808

Last change on this file since 808 was 808, checked in by Sam Hocevar, 14 years ago
  • Truecolor support for the HTML and HTMLv3 exporters.
  • Property svn:keywords set to Id
File size: 19.8 KB
Line 
1/*
2 *  libcucul      Canvas for ultrafast compositing of Unicode letters
3 *  Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
4 *                2006 Jean-Yves Lamoureux <jylam@lnxscene.org>
5 *                All Rights Reserved
6 *
7 *  $Id: export.c 808 2006-04-18 10:02:42Z sam $
8 *
9 *  This library is free software; you can redistribute it and/or
10 *  modify it under the terms of the Do What The Fuck You Want To
11 *  Public License, Version 2, as published by Sam Hocevar. See
12 *  http://sam.zoy.org/wtfpl/COPYING for more details.
13 */
14
15/*
16 *  This file contains various export functions
17 */
18
19#include "config.h"
20
21#if !defined(__KERNEL__)
22#   include <stdlib.h>
23#   include <stdio.h>
24#   include <string.h>
25#endif
26
27#include "cucul.h"
28#include "cucul_internals.h"
29
30static void export_ansi(cucul_t *, cucul_buffer_t *);
31static void export_html(cucul_t *, cucul_buffer_t *);
32static void export_html3(cucul_t *, cucul_buffer_t *);
33static void export_irc(cucul_t *, cucul_buffer_t *);
34static void export_ps(cucul_t *, cucul_buffer_t *);
35static void export_svg(cucul_t *, cucul_buffer_t *);
36static void export_tga(cucul_t *, cucul_buffer_t *);
37
38/** \brief Export a canvas into a foreign format.
39 *
40 *  This function exports a libcucul canvas into various foreign formats such
41 *  as ANSI art, HTML, IRC colours, etc. One should use cucul_get_buffer_data()
42 *  and cucul_get_buffer_size() to access the buffer contents. The allocated
43 *  data is valid until cucul_free_buffer() is called.
44 *
45 *  Valid values for \e format are:
46 *
47 *  \li \e "ansi": export ANSI art (CP437 charset with ANSI colour codes).
48 *
49 *  \li \e "html": export an HTML page with CSS information.
50 *
51 *  \li \e "html3": export an HTML table that should be compatible with
52 *      most navigators, including textmode ones.
53 *
54 *  \li \e "irc": export UTF-8 text with mIRC colour codes.
55 *
56 *  \li \e "ps": export a PostScript document.
57 *
58 *  \li \e "svg": export an SVG vector image.
59 *
60 *  \li \e "tga": export a TGA image.
61 *
62 *  \param qq A libcucul canvas
63 *  \param format A string describing the requested output format.
64 */
65cucul_buffer_t * cucul_create_export(cucul_t *qq, char const *format)
66{
67    cucul_buffer_t *ex;
68
69    ex = malloc(sizeof(cucul_buffer_t));
70    ex->size = 0;
71    ex->data = NULL;
72
73    if(!strcasecmp("ansi", format))
74        export_ansi(qq, ex);
75    else if(!strcasecmp("html", format))
76        export_html(qq, ex);
77    else if(!strcasecmp("html3", format))
78        export_html3(qq, ex);
79    else if(!strcasecmp("irc", format))
80        export_irc(qq, ex);
81    else if(!strcasecmp("ps", format))
82        export_ps(qq, ex);
83    else if(!strcasecmp("svg", format))
84        export_svg(qq, ex);
85    else if(!strcasecmp("tga", format))
86        export_tga(qq, ex);
87
88    if(ex->size == 0)
89    {
90        free(ex);
91        return NULL;
92    }
93
94    return ex;
95}
96
97/** \brief Get available export formats
98 *
99 *  Return a list of available export formats. The list is a NULL-terminated
100 *  array of strings, interleaving a string containing the internal value for
101 *  the export format, to be used with \e cucul_create_export(), and a string
102 *  containing the natural language description for that export format.
103 *
104 *  \return An array of strings.
105 */
106char const * const * cucul_get_export_list(void)
107{
108    static char const * const list[] =
109    {
110        "ansi", "ANSI",
111        "html", "HTML",
112        "html3", "backwards-compatible HTML",
113        "irc", "IRC with mIRC colours",
114        "ps", "PostScript document",
115        "svg", "SVG vector image",
116        "tga", "TGA image",
117        NULL, NULL
118    };
119
120    return list;
121}
122
123/*
124 * XXX: the following functions are local.
125 */
126
127/* Generate ANSI representation of current canvas. */
128static void export_ansi(cucul_t *qq, cucul_buffer_t *ex)
129{
130    static uint8_t const palette[] =
131    {
132        0,  4,  2,  6, 1,  5,  3,  7,
133        8, 12, 10, 14, 9, 13, 11, 15
134    };
135
136    char *cur;
137    unsigned int x, y;
138
139    /* 23 bytes assumed for max length per pixel ('\e[5;1;3x;4y;9x;10ym' plus
140     * 4 max bytes for a UTF-8 character).
141     * Add height*9 to that (zeroes color at the end and jump to next line) */
142    ex->size = (qq->height * 9) + (qq->width * qq->height * 23);
143    ex->data = malloc(ex->size);
144
145    cur = ex->data;
146
147    for(y = 0; y < qq->height; y++)
148    {
149        uint32_t *lineattr = qq->attr + y * qq->width;
150        uint32_t *linechar = qq->chars + y * qq->width;
151
152        uint8_t prevfg = -1;
153        uint8_t prevbg = -1;
154
155        for(x = 0; x < qq->width; x++)
156        {
157            uint8_t fg = palette[_cucul_argb32_to_ansi4fg(lineattr[x])];
158            uint8_t bg = palette[_cucul_argb32_to_ansi4bg(lineattr[x])];
159            uint32_t c = linechar[x];
160
161            if(fg != prevfg || bg != prevbg)
162            {
163                cur += sprintf(cur, "\033[0;");
164
165                if(fg < 8)
166                    if(bg < 8)
167                        cur += sprintf(cur, "3%d;4%dm", fg, bg);
168                    else
169                        cur += sprintf(cur, "5;3%d;4%d;10%dm",
170                                            fg, bg - 8, bg - 8);
171                else
172                    if(bg < 8)
173                        cur += sprintf(cur, "1;3%d;4%d;9%dm",
174                                            fg - 8, bg, fg - 8);
175                    else
176                        cur += sprintf(cur, "5;1;3%d;4%d;9%d;10%dm",
177                                            fg - 8, bg - 8, fg - 8, bg - 8);
178            }
179
180            *cur++ = c & 0x7f;
181
182            prevfg = fg;
183            prevbg = bg;
184        }
185
186        cur += sprintf(cur, "\033[0m\r\n");
187    }
188
189    /* Crop to really used size */
190    ex->size = (uintptr_t)(cur - ex->data);
191    ex->data = realloc(ex->data, ex->size);
192}
193
194/* Generate HTML representation of current canvas. */
195static void export_html(cucul_t *qq, cucul_buffer_t *ex)
196{
197    char *cur;
198    unsigned int x, y, len;
199
200    /* The HTML header: less than 1000 bytes
201     * A line: 7 chars for "<br />\n"
202     * A glyph: 47 chars for "<span style="color:#xxx;background-color:#xxx">"
203     *          up to 9 chars for "&#xxxxxx;", far less for pure ASCII
204     *          7 chars for "</span>" */
205    ex->size = 1000 + qq->height * (7 + qq->width * (47 + 9 + 7));
206    ex->data = malloc(ex->size);
207
208    cur = ex->data;
209
210    /* HTML header */
211    cur += sprintf(cur, "<html><head>\n");
212    cur += sprintf(cur, "<title>Generated by libcaca %s</title>\n", VERSION);
213    cur += sprintf(cur, "</head><body>\n");
214
215    cur += sprintf(cur, "<div cellpadding='0' cellspacing='0' style='%s'>\n",
216                        "font-family: monospace, fixed; font-weight: bold;");
217
218    for(y = 0; y < qq->height; y++)
219    {
220        uint32_t *lineattr = qq->attr + y * qq->width;
221        uint32_t *linechar = qq->chars + y * qq->width;
222
223        for(x = 0; x < qq->width; x += len)
224        {
225            cur += sprintf(cur, "<span style=\"color:#%.03x;"
226                                "background-color:#%.03x\">",
227                                _cucul_argb32_to_rgb12fg(lineattr[x]),
228                                _cucul_argb32_to_rgb12bg(lineattr[x]));
229
230            for(len = 0;
231                x + len < qq->width && lineattr[x + len] == lineattr[x];
232                len++)
233            {
234                if(linechar[x + len] <= 0x00000020)
235                    cur += sprintf(cur, "&nbsp;");
236                else if(linechar[x + len] < 0x00000080)
237                    cur += sprintf(cur, "%c", linechar[x + len]);
238                else
239                    cur += sprintf(cur, "&#%i;", linechar[x + len]);
240            }
241            cur += sprintf(cur, "</span>");
242        }
243        /* New line */
244        cur += sprintf(cur, "<br />\n");
245    }
246
247    cur += sprintf(cur, "</div></body></html>\n");
248
249    /* Crop to really used size */
250    ex->size = strlen(ex->data) + 1;
251    ex->data = realloc(ex->data, ex->size);
252}
253
254/* Export an HTML3 document. This function is way bigger than export_html(),
255 * but permits viewing in old browsers (or limited ones such as links). It
256 * will not work under gecko (mozilla rendering engine) unless you set a
257 * correct header. */
258static void export_html3(cucul_t *qq, cucul_buffer_t *ex)
259{
260    char *cur;
261    unsigned int x, y, len;
262
263    /* The HTML table markup: less than 1000 bytes
264     * A line: 10 chars for "<tr></tr>\n"
265     * A glyph: 40 chars for "<td bgcolor=#xxxxxx><font color=#xxxxxx>"
266     *          up to 9 chars for "&#xxxxxx;", far less for pure ASCII
267     *          12 chars for "</font></td>" */
268    ex->size = 1000 + qq->height * (10 + qq->width * (40 + 9 + 12));
269    ex->data = malloc(ex->size);
270
271    cur = ex->data;
272
273    /* Table */
274    cur += sprintf(cur, "<table cols='%d' cellpadding='0' cellspacing='0'>\n",
275                        qq->height);
276
277    for(y = 0; y < qq->height; y++)
278    {
279        uint32_t *lineattr = qq->attr + y * qq->width;
280        uint32_t *linechar = qq->chars + y * qq->width;
281
282        cur += sprintf(cur, "<tr>");
283
284        for(x = 0; x < qq->width; x += len)
285        {
286            unsigned int i;
287
288            /* Use colspan option to factor cells with same attributes
289             * (see below) */
290            len = 1;
291            while(x + len < qq->width && lineattr[x + len] == lineattr[x])
292                len++;
293
294            cur += sprintf(cur, "<td bgcolor=#%.06x",
295                           _cucul_argb32_to_rgb24bg(lineattr[x]));
296
297            if(len > 1)
298                cur += sprintf(cur, " colspan=%d", len);
299
300            cur += sprintf(cur, "><font color=#%.06x>",
301                           _cucul_argb32_to_rgb24fg(lineattr[x]));
302
303            for(i = 0; i < len; i++)
304            {
305                if(linechar[x + i] <= 0x00000020)
306                    cur += sprintf(cur, "&nbsp;");
307                else if(linechar[x + i] < 0x00000080)
308                    cur += sprintf(cur, "%c", linechar[x + i]);
309                else
310                    cur += sprintf(cur, "&#%i;", linechar[x + i]);
311            }
312
313            cur += sprintf(cur, "</font></td>");
314        }
315        cur += sprintf(cur, "</tr>\n");
316    }
317
318    /* Footer */
319    cur += sprintf(cur, "</table>\n");
320
321    /* Crop to really used size */
322    ex->size = (uintptr_t)(cur - ex->data);
323    ex->data = realloc(ex->data, ex->size);
324}
325
326/* Export a text file with IRC colours */
327static void export_irc(cucul_t *qq, cucul_buffer_t *ex)
328{
329    static uint8_t const palette[] =
330    {
331        1, 2, 3, 10, 5, 6, 7, 15, /* Dark */
332        14, 12, 9, 11, 4, 13, 8, 0, /* Light */
333    };
334
335    char *cur;
336    unsigned int x, y;
337
338    /* 11 bytes assumed for max length per pixel. Worst case scenario:
339     * ^Cxx,yy   6 bytes
340     * ^B^B      2 bytes
341     * c         1 byte
342     * \r\n      2 bytes
343     * In real life, the average bytes per pixel value will be around 5.
344     */
345
346    ex->size = 2 + (qq->width * qq->height * 11);
347    ex->data = malloc(ex->size);
348
349    cur = ex->data;
350
351    for(y = 0; y < qq->height; y++)
352    {
353        uint32_t *lineattr = qq->attr + y * qq->width;
354        uint32_t *linechar = qq->chars + y * qq->width;
355
356        uint8_t prevfg = -1;
357        uint8_t prevbg = -1;
358
359        for(x = 0; x < qq->width; x++)
360        {
361            uint8_t fg = palette[_cucul_argb32_to_ansi4fg(lineattr[x])];
362            uint8_t bg = palette[_cucul_argb32_to_ansi4bg(lineattr[x])];
363            uint32_t c = linechar[x];
364
365            if(bg == prevbg)
366            {
367                if(fg == prevfg)
368                    ; /* Same fg/bg, do nothing */
369                else if(c == (uint32_t)' ')
370                    fg = prevfg; /* Hackety hack */
371                else
372                {
373                    cur += sprintf(cur, "\x03%d", fg);
374                    if(c >= (uint32_t)'0' && c <= (uint32_t)'9')
375                        cur += sprintf(cur, "\x02\x02");
376                }
377            }
378            else
379            {
380                if(fg == prevfg)
381                    cur += sprintf(cur, "\x03,%d", bg);
382                else
383                    cur += sprintf(cur, "\x03%d,%d", fg, bg);
384
385                if(c >= (uint32_t)'0' && c <= (uint32_t)'9')
386                    cur += sprintf(cur, "\x02\x02");
387            }
388            *cur++ = c & 0x7f;
389            prevfg = fg;
390            prevbg = bg;
391        }
392        *cur++ = '\r';
393        *cur++ = '\n';
394    }
395
396    /* Crop to really used size */
397    ex->size = (uintptr_t)(cur - ex->data);
398    ex->data = realloc(ex->data, ex->size);
399}
400
401/* Export a PostScript document. */
402static void export_ps(cucul_t *qq, cucul_buffer_t *ex)
403{
404    static char const *ps_header =
405        "%!\n"
406        "%% libcaca PDF export\n"
407        "%%LanguageLevel: 2\n"
408        "%%Pages: 1\n"
409        "%%DocumentData: Clean7Bit\n"
410        "/csquare {\n"
411        "  newpath\n"
412        "  0 0 moveto\n"
413        "  0 1 rlineto\n"
414        "  1 0 rlineto\n"
415        "  0 -1 rlineto\n"
416        "  closepath\n"
417        "  setrgbcolor\n"
418        "  fill\n"
419        "} def\n"
420        "/S {\n"
421        "  Show\n"
422        "} bind def\n"
423        "/Courier-Bold findfont\n"
424        "8 scalefont\n"
425        "setfont\n"
426        "gsave\n"
427        "6 10 scale\n";
428
429    char *cur;
430    unsigned int x, y;
431
432    /* 200 is arbitrary but should be ok */
433    ex->size = strlen(ps_header) + (qq->width * qq->height * 200);
434    ex->data = malloc(ex->size);
435
436    cur = ex->data;
437
438    /* Header */
439    cur += sprintf(cur, "%s", ps_header);
440
441    /* Background, drawn using csquare macro defined in header */
442    for(y = qq->height; y--; )
443    {
444        uint32_t *lineattr = qq->attr + y * qq->width;
445
446        for(x = 0; x < qq->width; x++)
447        {
448            uint8_t argb[8];
449            _cucul_argb32_to_argb4(*lineattr++, argb);
450            cur += sprintf(cur, "1 0 translate\n %f %f %f csquare\n",
451                           (float)argb[1] * (1.0 / 0xf),
452                           (float)argb[2] * (1.0 / 0xf),
453                           (float)argb[3] * (1.0 / 0xf));
454        }
455
456        /* Return to beginning of the line, and jump to the next one */
457        cur += sprintf(cur, "-%d 1 translate\n", qq->width);
458    }
459
460    cur += sprintf(cur, "grestore\n"); /* Restore transformation matrix */
461
462    for(y = qq->height; y--; )
463    {
464        uint32_t *lineattr = qq->attr + (qq->height - y - 1) * qq->width;
465        uint32_t *linechar = qq->chars + (qq->height - y - 1) * qq->width;
466
467        for(x = 0; x < qq->width; x++)
468        {
469            uint8_t argb[8];
470            uint32_t c = *linechar++;
471
472            _cucul_argb32_to_argb4(*lineattr++, argb);
473
474            cur += sprintf(cur, "newpath\n");
475            cur += sprintf(cur, "%d %d moveto\n", (x + 1) * 6, y * 10 + 2);
476            cur += sprintf(cur, "%f %f %f setrgbcolor\n",
477                           (float)argb[5] * (1.0 / 0xf),
478                           (float)argb[6] * (1.0 / 0xf),
479                           (float)argb[7] * (1.0 / 0xf));
480
481            if(c < 0x00000020)
482                cur += sprintf(cur, "(?) show\n");
483            else if(c >= 0x00000080)
484                cur += sprintf(cur, "(?) show\n");
485            else switch((uint8_t)(c & 0x7f))
486            {
487                case '\\':
488                case '(':
489                case ')':
490                    cur += sprintf(cur, "(\\%c) show\n", c);
491                    break;
492                default:
493                    cur += sprintf(cur, "(%c) show\n", c);
494                    break;
495            }
496        }
497    }
498
499    cur += sprintf(cur, "showpage\n");
500
501    /* Crop to really used size */
502    ex->size = (uintptr_t)(cur - ex->data);
503    ex->data = realloc(ex->data, ex->size);
504}
505
506/* Export an SVG vector image */
507static void export_svg(cucul_t *qq, cucul_buffer_t *ex)
508{
509    static char const svg_header[] =
510        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
511        "<svg width=\"%d\" height=\"%d\" viewBox=\"0 0 %d %d\""
512        " xmlns=\"http://www.w3.org/2000/svg\""
513        " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
514        " xml:space=\"preserve\" version=\"1.1\"  baseProfile=\"full\">\n";
515
516    char *cur;
517    unsigned int x, y;
518
519    /* 200 is arbitrary but should be ok */
520    ex->size = strlen(svg_header) + (qq->width * qq->height * 200);
521    ex->data = malloc(ex->size);
522
523    cur = ex->data;
524
525    /* Header */
526    cur += sprintf(cur, svg_header, qq->width * 6, qq->height * 10,
527                                    qq->width * 6, qq->height * 10);
528
529    cur += sprintf(cur, " <g id=\"mainlayer\" font-size=\"12\">\n");
530
531    /* Background */
532    for(y = 0; y < qq->height; y++)
533    {
534        uint32_t *lineattr = qq->attr + y * qq->width;
535
536        for(x = 0; x < qq->width; x++)
537        {
538            cur += sprintf(cur, "<rect style=\"fill:#%.03x\" x=\"%d\" y=\"%d\""
539                                " width=\"6\" height=\"10\"/>\n",
540                                _cucul_argb32_to_rgb12bg(*lineattr++),
541                                x * 6, y * 10);
542        }
543    }
544
545    /* Text */
546    for(y = 0; y < qq->height; y++)
547    {
548        uint32_t *lineattr = qq->attr + y * qq->width;
549        uint32_t *linechar = qq->chars + y * qq->width;
550
551        for(x = 0; x < qq->width; x++)
552        {
553            uint32_t c = *linechar++;
554
555            cur += sprintf(cur, "<text style=\"fill:#%.03x\" "
556                                "x=\"%d\" y=\"%d\">",
557                                _cucul_argb32_to_rgb12fg(*lineattr++),
558                                x * 6, (y * 10) + 10);
559            if(c < 0x00000020)
560                cur += sprintf(cur, "?");
561            else if(c > 0x0000007f)
562            {
563                static const uint8_t mark[7] =
564                {
565                    0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
566                };
567
568                char buf[10], *parser;
569                int bytes = (c < 0x800) ? 2 : (c < 0x10000) ? 3 : 4;
570
571                buf[bytes] = '\0';
572                parser = buf + bytes;
573
574                switch(bytes)
575                {
576                    case 4: *--parser = (c | 0x80) & 0xbf; c >>= 6;
577                    case 3: *--parser = (c | 0x80) & 0xbf; c >>= 6;
578                    case 2: *--parser = (c | 0x80) & 0xbf; c >>= 6;
579                }
580                *--parser = c | mark[bytes];
581
582                cur += sprintf(cur, "%s", buf);
583            }
584            else switch((uint8_t)c)
585            {
586                case '>': cur += sprintf(cur, "&gt;"); break;
587                case '<': cur += sprintf(cur, "&lt;"); break;
588                case '&': cur += sprintf(cur, "&amp;"); break;
589                default: cur += sprintf(cur, "%c", c); break;
590            }
591            cur += sprintf(cur, "</text>\n");
592        }
593    }
594
595    cur += sprintf(cur, " </g>\n");
596    cur += sprintf(cur, "</svg>\n");
597
598    /* Crop to really used size */
599    ex->size = (uintptr_t)(cur - ex->data);
600    ex->data = realloc(ex->data, ex->size);
601}
602
603/* Export a TGA image */
604static void export_tga(cucul_t *qq, cucul_buffer_t *ex)
605{
606    char const * const * fontlist;
607    char * cur;
608    cucul_font_t *f;
609    unsigned int i, w, h;
610
611    fontlist = cucul_get_font_list();
612    if(!fontlist[0])
613        return;
614
615    f = cucul_load_font(fontlist[0], 0);
616
617    w = cucul_get_width(qq) * cucul_get_font_width(f);
618    h = cucul_get_height(qq) * cucul_get_font_height(f);
619
620    ex->size = w * h * 4 + 18; /* 32 bpp + 18 bytes for the header */
621    ex->data = malloc(ex->size);
622
623    cur = ex->data;
624
625    /* ID Length */
626    cur += sprintf(cur, "%c", 0);
627    /* Color Map Type: no colormap */
628    cur += sprintf(cur, "%c", 0);
629    /* Image Type: uncompressed truecolor */
630    cur += sprintf(cur, "%c", 2);
631    /* Color Map Specification: no color map */
632    memset(cur, 0, 5); cur += 5;
633
634    /* Image Specification */
635    cur += sprintf(cur, "%c%c", 0, 0); /* X Origin */
636    cur += sprintf(cur, "%c%c", 0, 0); /* Y Origin */
637    cur += sprintf(cur, "%c%c", w & 0xff, w >> 8); /* Width */
638    cur += sprintf(cur, "%c%c", h & 0xff, h >> 8); /* Height */
639    cur += sprintf(cur, "%c", 32); /* Pixel Depth */
640    cur += sprintf(cur, "%c", 40); /* Image Descriptor */
641
642    /* Image ID: no ID */
643    /* Color Map Data: no colormap */
644
645    /* Image Data */
646    cucul_render_canvas(qq, f, cur, w, h, 4 * w);
647
648    /* Swap bytes. What a waste of time. */
649    for(i = 0; i < w * h * 4; i += 4)
650    {
651        char w;
652        w = cur[i]; cur[i] = cur[i + 3]; cur[i + 3] = w;
653        w = cur[i + 1]; cur[i + 1] = cur[i + 2]; cur[i + 2] = w;
654    }
655
656    cucul_free_font(f);
657}
658
Note: See TracBrowser for help on using the repository browser.