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

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