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

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