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

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