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

Last change on this file since 2299 was 2299, checked in by Sam Hocevar, 12 years ago
  • Remove #include <stdint.h> etc. from "common.h". Instead, make sure that <cucul.h> will provide the C99 types, even if libcaca has been installed.
  • Rename what's left of "common.h" to "stubs.h".
  • Remove all references to erroneous <inttypes.h> from source files.
  • Property svn:keywords set to Id
File size: 32.4 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 2299 2008-04-19 12:42:50Z sam $
8 *
9 *  This library is free software. It comes without any warranty, to
10 *  the extent permitted by applicable law. You can redistribute it
11 *  and/or modify it under the terms of the Do What The Fuck You Want
12 *  To Public License, Version 2, as published by Sam Hocevar. See
13 *  http://sam.zoy.org/wtfpl/COPYING for more details.
14 */
15
16/*
17 *  This file contains various export functions
18 */
19
20#include "config.h"
21
22#if !defined(__KERNEL__)
23#   include <stdlib.h>
24#   include <stdio.h>
25#   include <string.h>
26#endif
27
28#include "cucul.h"
29#include "cucul_internals.h"
30
31static inline int sprintu32(char *s, uint32_t x)
32{
33    s[0] = (uint8_t)(x >> 24);
34    s[1] = (uint8_t)(x >> 16) & 0xff;
35    s[2] = (uint8_t)(x >>  8) & 0xff;
36    s[3] = (uint8_t)(x      ) & 0xff;
37    return 4;
38}
39
40static inline int sprintu16(char *s, uint16_t x)
41{
42    s[0] = (uint8_t)(x >>  8) & 0xff;
43    s[1] = (uint8_t)(x      ) & 0xff;
44    return 2;
45}
46
47static void *export_caca(cucul_canvas_t const *, unsigned long int *);
48static void *export_ansi(cucul_canvas_t const *, unsigned long int *);
49static void *export_utf8(cucul_canvas_t const *, unsigned long int *, int);
50static void *export_html(cucul_canvas_t const *, unsigned long int *);
51static void *export_html3(cucul_canvas_t const *, unsigned long int *);
52static void *export_bbfr(cucul_canvas_t const *, unsigned long int *);
53static void *export_irc(cucul_canvas_t const *, unsigned long int *);
54static void *export_ps(cucul_canvas_t const *, unsigned long int *);
55static void *export_svg(cucul_canvas_t const *, unsigned long int *);
56static void *export_tga(cucul_canvas_t const *, unsigned long int *);
57
58/** \brief Export a canvas into a foreign format.
59 *
60 *  This function exports a libcucul canvas into various foreign formats such
61 *  as ANSI art, HTML, IRC colours, etc. The returned pointer should be passed
62 *  to free() to release the allocated storage when it is no longer needed.
63 *
64 *  Valid values for \c format are:
65 *  - \c "caca": export native libcaca files.
66 *  - \c "ansi": export ANSI art (CP437 charset with ANSI colour codes).
67 *  - \c "html": export an HTML page with CSS information.
68 *  - \c "html3": export an HTML table that should be compatible with
69 *    most navigators, including textmode ones.
70 *  - \c "irc": export UTF-8 text with mIRC colour codes.
71 *  - \c "ps": export a PostScript document.
72 *  - \c "svg": export an SVG vector image.
73 *  - \c "tga": export a TGA image.
74 *
75 *  If an error occurs, NULL is returned and \b errno is set accordingly:
76 *  - \c EINVAL Unsupported format requested.
77 *  - \c ENOMEM Not enough memory to allocate output buffer.
78 *
79 *  \param cv A libcucul canvas
80 *  \param format A string describing the requested output format.
81 *  \param bytes A pointer to an unsigned long integer where the number of
82 *         allocated bytes will be written.
83 *  \return A pointer to the exported memory area, or NULL in case of error.
84 */
85void *cucul_export_memory(cucul_canvas_t const *cv, char const *format,
86                          unsigned long int *bytes)
87{
88    if(!strcasecmp("caca", format))
89        return export_caca(cv, bytes);
90
91    if(!strcasecmp("ansi", format))
92        return export_ansi(cv, bytes);
93
94    if(!strcasecmp("utf8", format))
95        return export_utf8(cv, bytes, 0);
96
97    if(!strcasecmp("utf8cr", format))
98        return export_utf8(cv, bytes, 1);
99
100    if(!strcasecmp("html", format))
101        return export_html(cv, bytes);
102
103    if(!strcasecmp("html3", format))
104        return export_html3(cv, bytes);
105
106    if(!strcasecmp("bbfr", format))
107        return export_bbfr(cv, bytes);
108
109    if(!strcasecmp("irc", format))
110        return export_irc(cv, bytes);
111
112    if(!strcasecmp("ps", format))
113        return export_ps(cv, bytes);
114
115    if(!strcasecmp("svg", format))
116        return export_svg(cv, bytes);
117
118    if(!strcasecmp("tga", format))
119        return export_tga(cv, bytes);
120
121    seterrno(EINVAL);
122    return NULL;
123}
124
125/** \brief Get available export formats
126 *
127 *  Return a list of available export formats. The list is a NULL-terminated
128 *  array of strings, interleaving a string containing the internal value for
129 *  the export format, to be used with cucul_export_memory(), and a string
130 *  containing the natural language description for that export format.
131 *
132 *  This function never fails.
133 *
134 *  \return An array of strings.
135 */
136char const * const * cucul_get_export_list(void)
137{
138    static char const * const list[] =
139    {
140        "caca", "native libcaca format",
141        "ansi", "ANSI",
142        "utf8", "UTF-8 with ANSI escape codes",
143        "utf8cr", "UTF-8 with ANSI escape codes and MS-DOS \\r",
144        "html", "HTML",
145        "html3", "backwards-compatible HTML",
146        "bbfr", "BBCode (French)",
147        "irc", "IRC with mIRC colours",
148        "ps", "PostScript document",
149        "svg", "SVG vector image",
150        "tga", "TGA image",
151        NULL, NULL
152    };
153
154    return list;
155}
156
157/*
158 * XXX: the following functions are local.
159 */
160
161/* Generate a native libcaca canvas file. */
162static void *export_caca(cucul_canvas_t const *cv, unsigned long int *bytes)
163{
164    char *data, *cur;
165    unsigned int f, n;
166
167    /* 52 bytes for the header:
168     *  - 4 bytes for "\xCA\xCA" + "CV"
169     *  - 16 bytes for the canvas header
170     *  - 32 bytes for the frame info
171     * 8 bytes for each character cell */
172    *bytes = 20 + (32 + 8 * cv->width * cv->height) * cv->framecount;
173    cur = data = malloc(*bytes);
174
175    /* magic */
176    cur += sprintf(cur, "%s", "\xCA\xCA" "CV");
177
178    /* canvas_header */
179    cur += sprintu32(cur, 16 + 32 * cv->framecount);
180    cur += sprintu32(cur, cv->width * cv->height * 8 * cv->framecount);
181    cur += sprintu16(cur, 0x0001);
182    cur += sprintu32(cur, cv->framecount);
183    cur += sprintu16(cur, 0x0000);
184
185    /* frame_info */
186    for(f = 0; f < cv->framecount; f++)
187    {
188        cur += sprintu32(cur, cv->width);
189        cur += sprintu32(cur, cv->height);
190        cur += sprintu32(cur, 0);
191        cur += sprintu32(cur, cv->curattr);
192        cur += sprintu32(cur, cv->frames[f].x);
193        cur += sprintu32(cur, cv->frames[f].y);
194        cur += sprintu32(cur, cv->frames[f].handlex);
195        cur += sprintu32(cur, cv->frames[f].handley);
196    }
197
198    /* canvas_data */
199    for(f = 0; f < cv->framecount; f++)
200    {
201        uint32_t *attrs = cv->frames[f].attrs;
202        uint32_t *chars = cv->frames[f].chars;
203
204        for(n = cv->height * cv->width; n--; )
205        {
206            cur += sprintu32(cur, *chars++);
207            cur += sprintu32(cur, *attrs++);
208        }
209    }
210
211    return data;
212}
213
214/* Generate UTF-8 representation of current canvas. */
215static void *export_utf8(cucul_canvas_t const *cv, unsigned long int *bytes,
216                         int cr)
217{
218    static uint8_t const palette[] =
219    {
220        0,  4,  2,  6, 1,  5,  3,  7,
221        8, 12, 10, 14, 9, 13, 11, 15
222    };
223
224    char *data, *cur;
225    unsigned int x, y;
226
227    /* 23 bytes assumed for max length per pixel ('\e[5;1;3x;4y;9x;10ym' plus
228     * 4 max bytes for a UTF-8 character).
229     * Add height*9 to that (zeroes color at the end and jump to next line) */
230    *bytes = (cv->height * 9) + (cv->width * cv->height * 23);
231    cur = data = malloc(*bytes);
232
233    for(y = 0; y < cv->height; y++)
234    {
235        uint32_t *lineattr = cv->attrs + y * cv->width;
236        uint32_t *linechar = cv->chars + y * cv->width;
237
238        uint8_t prevfg = 0x10;
239        uint8_t prevbg = 0x10;
240
241        for(x = 0; x < cv->width; x++)
242        {
243            uint32_t attr = lineattr[x];
244            uint32_t ch = linechar[x];
245            uint8_t ansifg, ansibg, fg, bg;
246
247            if(ch == CUCUL_MAGIC_FULLWIDTH)
248                continue;
249
250            ansifg = cucul_attr_to_ansi_fg(attr);
251            ansibg = cucul_attr_to_ansi_bg(attr);
252
253            fg = ansifg < 0x10 ? palette[ansifg] : 0x10;
254            bg = ansibg < 0x10 ? palette[ansibg] : 0x10;
255
256            /* TODO: the [0 could be omitted in some cases */
257            if(fg != prevfg || bg != prevbg)
258            {
259                cur += sprintf(cur, "\033[0");
260
261                if(fg < 8)
262                    cur += sprintf(cur, ";3%d", fg);
263                else if(fg < 16)
264                    cur += sprintf(cur, ";1;3%d;9%d", fg - 8, fg - 8);
265
266                if(bg < 8)
267                    cur += sprintf(cur, ";4%d", bg);
268                else if(bg < 16)
269                    cur += sprintf(cur, ";5;4%d;10%d", bg - 8, bg - 8);
270
271                cur += sprintf(cur, "m");
272            }
273
274            cur += cucul_utf32_to_utf8(cur, ch);
275
276            prevfg = fg;
277            prevbg = bg;
278        }
279
280        if(prevfg != 0x10 || prevbg != 0x10)
281            cur += sprintf(cur, "\033[0m");
282
283        cur += sprintf(cur, cr ? "\r\n" : "\n");
284    }
285
286    /* Crop to really used size */
287    debug("utf8 export: alloc %lu bytes, realloc %lu",
288          (unsigned long int)*bytes, (unsigned long int)(cur - data));
289    *bytes = (uintptr_t)(cur - data);
290    data = realloc(data, *bytes);
291
292    return data;
293}
294
295/* Generate ANSI representation of current canvas. */
296static void *export_ansi(cucul_canvas_t const *cv, unsigned long int *bytes)
297{
298    static uint8_t const palette[] =
299    {
300        0,  4,  2,  6, 1,  5,  3,  7,
301        8, 12, 10, 14, 9, 13, 11, 15
302    };
303
304    char *data, *cur;
305    unsigned int x, y;
306
307    uint8_t prevfg = -1;
308    uint8_t prevbg = -1;
309
310    /* 16 bytes assumed for max length per pixel ('\e[5;1;3x;4ym' plus
311     * 1 byte for a CP437 character).
312     * Add height*9 to that (zeroes color at the end and jump to next line) */
313    *bytes = (cv->height * 9) + (cv->width * cv->height * 16);
314    cur = data = malloc(*bytes);
315
316    for(y = 0; y < cv->height; y++)
317    {
318        uint32_t *lineattr = cv->attrs + y * cv->width;
319        uint32_t *linechar = cv->chars + y * cv->width;
320
321        for(x = 0; x < cv->width; x++)
322        {
323            uint8_t ansifg = cucul_attr_to_ansi_fg(lineattr[x]);
324            uint8_t ansibg = cucul_attr_to_ansi_bg(lineattr[x]);
325            uint8_t fg = ansifg < 0x10 ? palette[ansifg] : CUCUL_LIGHTGRAY;
326            uint8_t bg = ansibg < 0x10 ? palette[ansibg] : CUCUL_BLACK;
327            uint32_t ch = linechar[x];
328
329            if(ch == CUCUL_MAGIC_FULLWIDTH)
330                ch = '?';
331
332            if(fg != prevfg || bg != prevbg)
333            {
334                cur += sprintf(cur, "\033[0;");
335
336                if(fg < 8)
337                    if(bg < 8)
338                        cur += sprintf(cur, "3%d;4%dm", fg, bg);
339                    else
340                        cur += sprintf(cur, "5;3%d;4%dm", fg, bg - 8);
341                else
342                    if(bg < 8)
343                        cur += sprintf(cur, "1;3%d;4%dm", fg - 8, bg);
344                    else
345                        cur += sprintf(cur, "5;1;3%d;4%dm", fg - 8, bg - 8);
346            }
347
348            *cur++ = cucul_utf32_to_cp437(ch);
349
350            prevfg = fg;
351            prevbg = bg;
352        }
353
354        if(cv->width == 80)
355        {
356            cur += sprintf(cur, "\033[s\n\033[u");
357        }
358        else
359        {
360            cur += sprintf(cur, "\033[0m\r\n");
361            prevfg = -1;
362            prevbg = -1;
363        }
364    }
365
366    /* Crop to really used size */
367    debug("ansi export: alloc %lu bytes, realloc %lu",
368          (unsigned long int)*bytes, (unsigned long int)(cur - data));
369    *bytes = (uintptr_t)(cur - data);
370    data = realloc(data, *bytes);
371
372    return data;
373}
374
375/* Generate HTML representation of current canvas. */
376static void *export_html(cucul_canvas_t const *cv, unsigned long int *bytes)
377{
378    char *data, *cur;
379    unsigned int x, y, len;
380
381    /* The HTML header: less than 1000 bytes
382     * A line: 7 chars for "<br />\n"
383     * A glyph: 47 chars for "<span style="color:#xxx;background-color:#xxx">"
384     *          83 chars for ";font-weight..."
385     *          up to 9 chars for "&#xxxxxx;", far less for pure ASCII
386     *          7 chars for "</span>" */
387    *bytes = 1000 + cv->height * (7 + cv->width * (47 + 83 + 9 + 7));
388    cur = data = malloc(*bytes);
389
390    /* HTML header */
391    cur += sprintf(cur, "<html><head>\n");
392    cur += sprintf(cur, "<title>Generated by libcaca %s</title>\n",
393                        cucul_get_version());
394    cur += sprintf(cur, "</head><body>\n");
395
396    cur += sprintf(cur, "<div cellpadding='0' cellspacing='0' style='%s'>\n",
397                        "font-family: monospace, fixed; font-weight: bold;");
398
399    for(y = 0; y < cv->height; y++)
400    {
401        uint32_t *lineattr = cv->attrs + y * cv->width;
402        uint32_t *linechar = cv->chars + y * cv->width;
403
404        for(x = 0; x < cv->width; x += len)
405        {
406            cur += sprintf(cur, "<span style=\"");
407            if(cucul_attr_to_ansi_fg(lineattr[x]) < 0x10)
408                cur += sprintf(cur, ";color:#%.03x",
409                               cucul_attr_to_rgb12_fg(lineattr[x]));
410            if(cucul_attr_to_ansi_bg(lineattr[x]) < 0x10)
411                cur += sprintf(cur, ";background-color:#%.03x",
412                               cucul_attr_to_rgb12_bg(lineattr[x]));
413            if(lineattr[x] & CUCUL_BOLD)
414                cur += sprintf(cur, ";font-weight:bold");
415            if(lineattr[x] & CUCUL_ITALICS)
416                cur += sprintf(cur, ";font-style:italic");
417            if(lineattr[x] & CUCUL_UNDERLINE)
418                cur += sprintf(cur, ";text-decoration:underline");
419            if(lineattr[x] & CUCUL_BLINK)
420                cur += sprintf(cur, ";text-decoration:blink");
421            cur += sprintf(cur, "\">");
422
423            for(len = 0;
424                x + len < cv->width && lineattr[x + len] == lineattr[x];
425                len++)
426            {
427                if(linechar[x + len] == CUCUL_MAGIC_FULLWIDTH)
428                    ;
429                else if(linechar[x + len] <= 0x00000020)
430                    cur += sprintf(cur, "&nbsp;");
431                else if(linechar[x + len] < 0x00000080)
432                    cur += sprintf(cur, "%c",
433                                   (unsigned char)linechar[x + len]);
434                else
435                    cur += sprintf(cur, "&#%i;",
436                                   (unsigned int)linechar[x + len]);
437            }
438            cur += sprintf(cur, "</span>");
439        }
440        /* New line */
441        cur += sprintf(cur, "<br />\n");
442    }
443
444    cur += sprintf(cur, "</div></body></html>\n");
445
446    /* Crop to really used size */
447    debug("html export: alloc %lu bytes, realloc %lu",
448          (unsigned long int)*bytes, (unsigned long int)(cur - data));
449    *bytes = (uintptr_t)(cur - data);
450    data = realloc(data, *bytes);
451
452    return data;
453}
454
455/* Export an HTML3 document. This function is way bigger than export_html(),
456 * but permits viewing in old browsers (or limited ones such as links). It
457 * will not work under gecko (mozilla rendering engine) unless you set a
458 * correct header. */
459static void *export_html3(cucul_canvas_t const *cv, unsigned long int *bytes)
460{
461    char *data, *cur;
462    unsigned int x, y, len;
463
464    /* The HTML table markup: less than 1000 bytes
465     * A line: 10 chars for "<tr></tr>\n"
466     * A glyph: 40 chars for "<td bgcolor=#xxxxxx><font color=#xxxxxx>"
467     *          up to 36 chars for "<b><i><u><blink></blink></u></i></b>"
468     *          up to 9 chars for "&#xxxxxx;", far less for pure ASCII
469     *          12 chars for "</font></td>" */
470    *bytes = 1000 + cv->height * (10 + cv->width * (40 + 36 + 9 + 12));
471    cur = data = malloc(*bytes);
472
473    /* Table */
474    cur += sprintf(cur, "<table cols='%d' cellpadding='0' cellspacing='0'>\n",
475                        cv->height);
476
477    for(y = 0; y < cv->height; y++)
478    {
479        uint32_t *lineattr = cv->attrs + y * cv->width;
480        uint32_t *linechar = cv->chars + y * cv->width;
481
482        cur += sprintf(cur, "<tr>");
483
484        for(x = 0; x < cv->width; x += len)
485        {
486            unsigned int i, needfont;
487
488            /* Use colspan option to factor cells with same attributes
489             * (see below) */
490            len = 1;
491            while(x + len < cv->width && lineattr[x + len] == lineattr[x])
492                len++;
493
494            cur += sprintf(cur, "<td");
495
496            if(cucul_attr_to_ansi_fg(lineattr[x]) < 0x10)
497                cur += sprintf(cur, " bgcolor=#%.06lx", (unsigned long int)
498                               _cucul_attr_to_rgb24bg(lineattr[x]));
499
500            if(len > 1)
501                cur += sprintf(cur, " colspan=%d", len);
502
503            cur += sprintf(cur, ">");
504
505            needfont = cucul_attr_to_ansi_bg(lineattr[x]) < 0x10;
506
507            if(needfont)
508                cur += sprintf(cur, "<font color=#%.06lx>", (unsigned long int)
509                               _cucul_attr_to_rgb24fg(lineattr[x]));
510
511            if(lineattr[x] & CUCUL_BOLD)
512                cur += sprintf(cur, "<b>");
513            if(lineattr[x] & CUCUL_ITALICS)
514                cur += sprintf(cur, "<i>");
515            if(lineattr[x] & CUCUL_UNDERLINE)
516                cur += sprintf(cur, "<u>");
517            if(lineattr[x] & CUCUL_BLINK)
518                cur += sprintf(cur, "<blink>");
519
520            for(i = 0; i < len; i++)
521            {
522                if(linechar[x + i] == CUCUL_MAGIC_FULLWIDTH)
523                    ;
524                else if(linechar[x + i] <= 0x00000020)
525                    cur += sprintf(cur, "&nbsp;");
526                else if(linechar[x + i] < 0x00000080)
527                    cur += sprintf(cur, "%c", (unsigned char)linechar[x + i]);
528                else
529                    cur += sprintf(cur, "&#%i;", (unsigned int)linechar[x + i]);
530            }
531
532            if(lineattr[x] & CUCUL_BLINK)
533                cur += sprintf(cur, "</blink>");
534            if(lineattr[x] & CUCUL_UNDERLINE)
535                cur += sprintf(cur, "</u>");
536            if(lineattr[x] & CUCUL_ITALICS)
537                cur += sprintf(cur, "</i>");
538            if(lineattr[x] & CUCUL_BOLD)
539                cur += sprintf(cur, "</b>");
540
541            if(needfont)
542                cur += sprintf(cur, "</font>");
543            cur += sprintf(cur, "</td>");
544        }
545        cur += sprintf(cur, "</tr>\n");
546    }
547
548    /* Footer */
549    cur += sprintf(cur, "</table>\n");
550
551    /* Crop to really used size */
552    debug("html3 export: alloc %lu bytes, realloc %lu",
553          (unsigned long int)*bytes, (unsigned long int)(cur - data));
554    *bytes = (uintptr_t)(cur - data);
555    data = realloc(data, *bytes);
556
557    return data;
558}
559
560static void *export_bbfr(cucul_canvas_t const *cv, unsigned long int *bytes)
561{
562    char *data, *cur;
563    unsigned int x, y, len;
564
565    /* The font markup: less than 100 bytes
566     * A line: 1 char for "\n"
567     * A glyph: 22 chars for "[f=#xxxxxx][c=#xxxxxx]"
568     *          up to 21 chars for "[g][i][s][/s][/i][/g]"
569     *          up to 6 chars for the UTF-8 glyph
570     *          8 chars for "[/c][/f]" */
571    *bytes = 100 + cv->height * (1 + cv->width * (22 + 21 + 6 + 8));
572    cur = data = malloc(*bytes);
573
574    /* Table */
575    cur += sprintf(cur, "[font=Courier New]");
576
577    for(y = 0; y < cv->height; y++)
578    {
579        uint32_t *lineattr = cv->attrs + y * cv->width;
580        uint32_t *linechar = cv->chars + y * cv->width;
581
582        for(x = 0; x < cv->width; x += len)
583        {
584            unsigned int i, needback, needfront;
585
586            /* Use colspan option to factor cells with same attributes
587             * (see below) */
588            len = 1;
589            if(linechar[x] == ' ')
590                while(x + len < cv->width && lineattr[x + len] == lineattr[x]
591                        && linechar[x] == ' ')
592                    len++;
593            else
594                while(x + len < cv->width && lineattr[x + len] == lineattr[x]
595                        && linechar[x] != ' ')
596                    len++;
597
598            needback = cucul_attr_to_ansi_bg(lineattr[x]) < 0x10;
599            needfront = cucul_attr_to_ansi_fg(lineattr[x]) < 0x10;
600
601            if(needback)
602                cur += sprintf(cur, "[f=#%.06lx]", (unsigned long int)
603                               _cucul_attr_to_rgb24bg(lineattr[x]));
604
605            if(linechar[x] == ' ')
606                cur += sprintf(cur, "[c=#%.06lx]", (unsigned long int)
607                               _cucul_attr_to_rgb24bg(lineattr[x]));
608            else if(needfront)
609                cur += sprintf(cur, "[c=#%.06lx]", (unsigned long int)
610                               _cucul_attr_to_rgb24fg(lineattr[x]));
611
612            if(lineattr[x] & CUCUL_BOLD)
613                cur += sprintf(cur, "[g]");
614            if(lineattr[x] & CUCUL_ITALICS)
615                cur += sprintf(cur, "[i]");
616            if(lineattr[x] & CUCUL_UNDERLINE)
617                cur += sprintf(cur, "[s]");
618            if(lineattr[x] & CUCUL_BLINK)
619                ; /* FIXME */
620
621            for(i = 0; i < len; i++)
622            {
623                if(linechar[x + i] == CUCUL_MAGIC_FULLWIDTH)
624                    ;
625                else if(linechar[x + i] == ' ')
626                    *cur++ = '_';
627                else
628                    cur += cucul_utf32_to_utf8(cur, linechar[x + i]);
629            }
630
631            if(lineattr[x] & CUCUL_BLINK)
632                ; /* FIXME */
633            if(lineattr[x] & CUCUL_UNDERLINE)
634                cur += sprintf(cur, "[/s]");
635            if(lineattr[x] & CUCUL_ITALICS)
636                cur += sprintf(cur, "[/i]");
637            if(lineattr[x] & CUCUL_BOLD)
638                cur += sprintf(cur, "[/g]");
639
640            if(linechar[x] == ' ' || needfront)
641                cur += sprintf(cur, "[/c]");
642            if(needback)
643                cur += sprintf(cur, "[/f]");
644        }
645        cur += sprintf(cur, "\n");
646    }
647
648    /* Footer */
649    cur += sprintf(cur, "[/font]\n");
650
651    /* Crop to really used size */
652    debug("bbfr export: alloc %lu bytes, realloc %lu",
653          (unsigned long int)*bytes, (unsigned long int)(cur - data));
654    *bytes = (uintptr_t)(cur - data);
655    data = realloc(data, *bytes);
656
657    return data;
658}
659
660/* Export a text file with IRC colours */
661static void *export_irc(cucul_canvas_t const *cv, unsigned long int *bytes)
662{
663    static uint8_t const palette[] =
664    {
665        1, 2, 3, 10, 5, 6, 7, 15, /* Dark */
666        14, 12, 9, 11, 4, 13, 8, 0, /* Light */
667    };
668
669    char *data, *cur;
670    unsigned int x, y;
671
672    /* 14 bytes assumed for max length per pixel. Worst case scenario:
673     * ^Cxx,yy   6 bytes
674     * ^B^B      2 bytes
675     * ch        6 bytes
676     * 3 bytes for max length per line. Worst case scenario:
677     * <spc>     1 byte (for empty lines)
678     * \r\n      2 bytes
679     * In real life, the average bytes per pixel value will be around 5.
680     */
681
682    *bytes = 2 + cv->height * (3 + cv->width * 14);
683    cur = data = malloc(*bytes);
684
685    for(y = 0; y < cv->height; y++)
686    {
687        uint32_t *lineattr = cv->attrs + y * cv->width;
688        uint32_t *linechar = cv->chars + y * cv->width;
689
690        uint8_t prevfg = 0x10;
691        uint8_t prevbg = 0x10;
692
693        for(x = 0; x < cv->width; x++)
694        {
695            uint32_t attr = lineattr[x];
696            uint32_t ch = linechar[x];
697            uint8_t ansifg, ansibg, fg, bg;
698
699            if(ch == CUCUL_MAGIC_FULLWIDTH)
700                continue;
701
702            ansifg = cucul_attr_to_ansi_fg(attr);
703            ansibg = cucul_attr_to_ansi_bg(attr);
704
705            fg = ansifg < 0x10 ? palette[ansifg] : 0x10;
706            bg = ansibg < 0x10 ? palette[ansibg] : 0x10;
707
708            /* TODO: optimise series of same fg / same bg
709             *       don't change fg value if ch == ' '
710             *       make sure the \x03,%d trick works everywhere */
711            if(bg != prevbg || fg != prevfg)
712            {
713                int need_escape = 0;
714
715                if(bg == 0x10)
716                {
717                    if(fg == 0x10)
718                        cur += sprintf(cur, "\x0f");
719                    else
720                    {
721                        if(prevbg == 0x10)
722                            cur += sprintf(cur, "\x03%d", fg);
723                        else
724                            cur += sprintf(cur, "\x0f\x03%d", fg);
725
726                        if(ch == (uint32_t)',')
727                            need_escape = 1;
728                    }
729                }
730                else
731                {
732                    if(fg == 0x10)
733                        cur += sprintf(cur, "\x0f\x03,%d", bg);
734                    else
735                        cur += sprintf(cur, "\x03%d,%d", fg, bg);
736                }
737
738                if(ch >= (uint32_t)'0' && ch <= (uint32_t)'9')
739                    need_escape = 1;
740
741                if(need_escape)
742                    cur += sprintf(cur, "\x02\x02");
743            }
744
745            cur += cucul_utf32_to_utf8(cur, ch);
746            prevfg = fg;
747            prevbg = bg;
748        }
749
750        /* TODO: do the same the day we optimise whole lines above */
751        if(!cv->width)
752            *cur++ = ' ';
753
754        *cur++ = '\r';
755        *cur++ = '\n';
756    }
757
758    /* Crop to really used size */
759    debug("IRC export: alloc %lu bytes, realloc %lu",
760          (unsigned long int)*bytes, (unsigned long int)(cur - data));
761    *bytes = (uintptr_t)(cur - data);
762    data = realloc(data, *bytes);
763
764    return data;
765}
766
767/* Export a PostScript document. */
768static void *export_ps(cucul_canvas_t const *cv, unsigned long int *bytes)
769{
770    static char const *ps_header =
771        "%!\n"
772        "%% libcaca PDF export\n"
773        "%%LanguageLevel: 2\n"
774        "%%Pages: 1\n"
775        "%%DocumentData: Clean7Bit\n"
776        "/csquare {\n"
777        "  newpath\n"
778        "  0 0 moveto\n"
779        "  0 1 rlineto\n"
780        "  1 0 rlineto\n"
781        "  0 -1 rlineto\n"
782        "  closepath\n"
783        "  setrgbcolor\n"
784        "  fill\n"
785        "} def\n"
786        "/S {\n"
787        "  Show\n"
788        "} bind def\n"
789        "/Courier-Bold findfont\n"
790        "8 scalefont\n"
791        "setfont\n"
792        "gsave\n"
793        "6 10 scale\n";
794
795    char *data, *cur;
796    unsigned int x, y;
797
798    /* 200 is arbitrary but should be ok */
799    *bytes = strlen(ps_header) + 100 + cv->height * (32 + cv->width * 200);
800    cur = data = malloc(*bytes);
801
802    /* Header */
803    cur += sprintf(cur, "%s", ps_header);
804    cur += sprintf(cur, "0 %d translate\n", cv->height);
805
806    /* Background, drawn using csquare macro defined in header */
807    for(y = cv->height; y--; )
808    {
809        uint32_t *lineattr = cv->attrs + y * cv->width;
810
811        for(x = 0; x < cv->width; x++)
812        {
813            uint8_t argb[8];
814            cucul_attr_to_argb64(*lineattr++, argb);
815            cur += sprintf(cur, "1 0 translate\n %f %f %f csquare\n",
816                           (float)argb[1] * (1.0 / 0xf),
817                           (float)argb[2] * (1.0 / 0xf),
818                           (float)argb[3] * (1.0 / 0xf));
819        }
820
821        /* Return to beginning of the line, and jump to the next one */
822        cur += sprintf(cur, "-%d 1 translate\n", cv->width);
823    }
824
825    cur += sprintf(cur, "grestore\n"); /* Restore transformation matrix */
826    cur += sprintf(cur, "0 %d translate\n", cv->height*10);
827
828    for(y = cv->height; y--; )
829    {
830        uint32_t *lineattr = cv->attrs + (cv->height - y - 1) * cv->width;
831        uint32_t *linechar = cv->chars + (cv->height - y - 1) * cv->width;
832
833        for(x = 0; x < cv->width; x++)
834        {
835            uint8_t argb[8];
836            uint32_t ch = *linechar++;
837
838            cucul_attr_to_argb64(*lineattr++, argb);
839
840            cur += sprintf(cur, "newpath\n");
841            cur += sprintf(cur, "%d %d moveto\n", (x + 1) * 6, y * 10 + 2);
842            cur += sprintf(cur, "%f %f %f setrgbcolor\n",
843                           (float)argb[5] * (1.0 / 0xf),
844                           (float)argb[6] * (1.0 / 0xf),
845                           (float)argb[7] * (1.0 / 0xf));
846
847            if(ch < 0x00000020)
848                cur += sprintf(cur, "(?) show\n");
849            else if(ch >= 0x00000080)
850                cur += sprintf(cur, "(?) show\n");
851            else switch((uint8_t)(ch & 0x7f))
852            {
853                case '\\':
854                case '(':
855                case ')':
856                    cur += sprintf(cur, "(\\%c) show\n", (unsigned char)ch);
857                    break;
858                default:
859                    cur += sprintf(cur, "(%c) show\n", (unsigned char)ch);
860                    break;
861            }
862        }
863    }
864
865    cur += sprintf(cur, "showpage\n");
866
867    /* Crop to really used size */
868    debug("PS export: alloc %lu bytes, realloc %lu",
869          (unsigned long int)*bytes, (unsigned long int)(cur - data));
870    *bytes = (uintptr_t)(cur - data);
871    data = realloc(data, *bytes);
872
873    return data;
874}
875
876/* Export an SVG vector image */
877static void *export_svg(cucul_canvas_t const *cv, unsigned long int *bytes)
878{
879    static char const svg_header[] =
880        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
881        "<svg width=\"%d\" height=\"%d\" viewBox=\"0 0 %d %d\""
882        " xmlns=\"http://www.w3.org/2000/svg\""
883        " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
884        " xml:space=\"preserve\" version=\"1.1\"  baseProfile=\"full\">\n";
885
886    char *data, *cur;
887    unsigned int x, y;
888
889    /* 200 is arbitrary but should be ok */
890    *bytes = strlen(svg_header) + 128 + cv->width * cv->height * 200;
891    cur = data = malloc(*bytes);
892
893    /* Header */
894    cur += sprintf(cur, svg_header, cv->width * 6, cv->height * 10,
895                                    cv->width * 6, cv->height * 10);
896
897    cur += sprintf(cur, " <g id=\"mainlayer\" font-size=\"10\""
898                        " style=\"font-family: monospace\">\n");
899
900    /* Background */
901    for(y = 0; y < cv->height; y++)
902    {
903        uint32_t *lineattr = cv->attrs + y * cv->width;
904
905        for(x = 0; x < cv->width; x++)
906        {
907            cur += sprintf(cur, "<rect style=\"fill:#%.03x\" x=\"%d\" y=\"%d\""
908                                " width=\"6\" height=\"10\"/>\n",
909                                cucul_attr_to_rgb12_bg(*lineattr++),
910                                x * 6, y * 10);
911        }
912    }
913
914    /* Text */
915    for(y = 0; y < cv->height; y++)
916    {
917        uint32_t *lineattr = cv->attrs + y * cv->width;
918        uint32_t *linechar = cv->chars + y * cv->width;
919
920        for(x = 0; x < cv->width; x++)
921        {
922            uint32_t ch = *linechar++;
923
924            if(ch == ' ' || ch == CUCUL_MAGIC_FULLWIDTH)
925            {
926                lineattr++;
927                continue;
928            }
929
930            cur += sprintf(cur, "<text style=\"fill:#%.03x\" "
931                                "x=\"%d\" y=\"%d\">",
932                                cucul_attr_to_rgb12_fg(*lineattr++),
933                                x * 6, (y * 10) + 8);
934
935            if(ch < 0x00000020)
936                *cur++ = '?';
937            else if(ch > 0x0000007f)
938                cur += cucul_utf32_to_utf8(cur, ch);
939            else switch((uint8_t)ch)
940            {
941                case '>': cur += sprintf(cur, "&gt;"); break;
942                case '<': cur += sprintf(cur, "&lt;"); break;
943                case '&': cur += sprintf(cur, "&amp;"); break;
944                default: *cur++ = ch; break;
945            }
946            cur += sprintf(cur, "</text>\n");
947        }
948    }
949
950    cur += sprintf(cur, " </g>\n");
951    cur += sprintf(cur, "</svg>\n");
952
953    /* Crop to really used size */
954    debug("SVG export: alloc %lu bytes, realloc %lu",
955          (unsigned long int)*bytes, (unsigned long int)(cur - data));
956    *bytes = (uintptr_t)(cur - data);
957    data = realloc(data, *bytes);
958
959    return data;
960}
961
962/* Export a TGA image */
963static void *export_tga(cucul_canvas_t const *cv, unsigned long int *bytes)
964{
965    char const * const *fontlist;
966    char *data, *cur;
967    cucul_font_t *f;
968    unsigned int i, w, h;
969
970    fontlist = cucul_get_font_list();
971    if(!fontlist[0])
972    {
973        seterrno(EINVAL);
974        return NULL;
975    }
976
977    f = cucul_load_font(fontlist[0], 0);
978
979    w = cucul_get_canvas_width(cv) * cucul_get_font_width(f);
980    h = cucul_get_canvas_height(cv) * cucul_get_font_height(f);
981
982    *bytes = w * h * 4 + 18; /* 32 bpp + 18 bytes for the header */
983    cur = data = malloc(*bytes);
984
985    /* ID Length */
986    cur += sprintf(cur, "%c", 0);
987    /* Color Map Type: no colormap */
988    cur += sprintf(cur, "%c", 0);
989    /* Image Type: uncompressed truecolor */
990    cur += sprintf(cur, "%c", 2);
991    /* Color Map Specification: no color map */
992    memset(cur, 0, 5); cur += 5;
993
994    /* Image Specification */
995    cur += sprintf(cur, "%c%c", 0, 0); /* X Origin */
996    cur += sprintf(cur, "%c%c", 0, 0); /* Y Origin */
997    cur += sprintf(cur, "%c%c", w & 0xff, w >> 8); /* Width */
998    cur += sprintf(cur, "%c%c", h & 0xff, h >> 8); /* Height */
999    cur += sprintf(cur, "%c", 32); /* Pixel Depth */
1000    cur += sprintf(cur, "%c", 40); /* Image Descriptor */
1001
1002    /* Image ID: no ID */
1003    /* Color Map Data: no colormap */
1004
1005    /* Image Data */
1006    cucul_render_canvas(cv, f, cur, w, h, 4 * w);
1007
1008    /* Swap bytes. What a waste of time. */
1009    for(i = 0; i < w * h * 4; i += 4)
1010    {
1011        char c;
1012        c = cur[i]; cur[i] = cur[i + 3]; cur[i + 3] = c;
1013        c = cur[i + 1]; cur[i + 1] = cur[i + 2]; cur[i + 2] = c;
1014    }
1015
1016    cucul_free_font(f);
1017
1018    return data;
1019}
1020
Note: See TracBrowser for help on using the repository browser.