source: libcaca/trunk/cucul/import.c @ 1104

Last change on this file since 1104 was 1104, checked in by Sam Hocevar, 14 years ago
  • Fix enumeration layout in the manpage documentation.
  • Property svn:keywords set to Id
File size: 15.0 KB
Line 
1/*
2 *  libcucul      Canvas for ultrafast compositing of Unicode letters
3 *  Copyright (c) 2002-2006 Sam Hocevar <sam@zoy.org>
4 *                All Rights Reserved
5 *
6 *  $Id: import.c 1104 2006-09-25 16:00:10Z sam $
7 *
8 *  This library is free software; you can redistribute it and/or
9 *  modify it under the terms of the Do What The Fuck You Want To
10 *  Public License, Version 2, as published by Sam Hocevar. See
11 *  http://sam.zoy.org/wtfpl/COPYING for more details.
12 */
13
14/*
15 *  This file contains various import functions.
16 */
17
18#include "config.h"
19#include "common.h"
20
21#if !defined(__KERNEL__)
22#   if defined(HAVE_ERRNO_H)
23#       include <errno.h>
24#   endif
25#   include <stdio.h>
26#   include <stdlib.h>
27#   include <string.h>
28#endif
29
30#include "cucul.h"
31#include "cucul_internals.h"
32
33/* ANSI Graphic Rendition Combination Mode */
34struct ansi_grcm
35{
36    uint8_t fg, bg;   /* ANSI-context fg/bg */
37    uint8_t efg, ebg; /* Effective (libcucul) fg/bg */
38    uint8_t bold, negative, concealed;
39};
40
41static cucul_canvas_t *import_caca(void const *, unsigned int);
42static cucul_canvas_t *import_text(void const *, unsigned int);
43static cucul_canvas_t *import_ansi(void const *, unsigned int);
44
45static void ansi_parse_grcm(cucul_canvas_t *, struct ansi_grcm *,
46                            unsigned int, unsigned int const *);
47
48/** \brief Import a buffer into a canvas
49 *
50 *  This function imports a libcucul buffer as returned by cucul_load_memory()
51 *  or cucul_load_file() into an internal libcucul canvas.
52 *
53 *  Valid values for \c format are:
54 *  - \c "": attempt to autodetect the file format.
55 *  - \c "ansi": import ANSI files.
56 *  - \c "caca": import native libcaca files.
57 *
58 *  If an error occurs, NULL is returned and \b errno is set accordingly:
59 *  - \c ENOMEM Not enough memory to allocate canvas.
60 *  - \c EINVAL Invalid format requested.
61 *
62 *  \param buffer A \e libcucul buffer containing the data to be loaded
63 *         into a canvas.
64 *  \param format A string describing the input format.
65 *  \return A libcucul canvas, or NULL in case of error.
66 */
67cucul_canvas_t * cucul_import_canvas(cucul_buffer_t *buffer, char const *format)
68{
69    char const *buf = (char const*)buffer->data;
70
71    if(!strcasecmp("caca", format))
72        return import_caca(buffer->data, buffer->size);
73    if(!strcasecmp("text", format))
74        return import_text(buffer->data, buffer->size);
75    if(!strcasecmp("ansi", format))
76        return import_ansi(buffer->data, buffer->size);
77
78    /* Autodetection */
79    if(!strcasecmp("", format))
80    {
81        unsigned int i;
82
83        /* If 4 first letters are CACA */
84        if(buffer->size >= 4 &&
85           buf[0] == 'C' && buf[1] == 'A' && buf[2] == 'C' && buf[3] != 'A')
86            return import_caca(buffer->data, buffer->size);
87
88        /* If we find ESC[ argv, we guess it's an ANSI file */
89        for(i = 0; i < buffer->size - 1; i++)
90            if((buf[i] == 0x1b) && (buf[i + 1] == '['))
91                return import_ansi(buffer->data, buffer->size);
92
93        /* Otherwise, import it as text */
94        return import_text(buffer->data, buffer->size);
95    }
96
97#if defined(HAVE_ERRNO_H)
98    errno = EINVAL;
99#endif
100    return NULL;
101}
102
103/** \brief Get available import formats
104 *
105 *  Return a list of available import formats. The list is a NULL-terminated
106 *  array of strings, interleaving a string containing the internal value for
107 *  the import format, to be used with cucul_import_canvas(), and a string
108 *  containing the natural language description for that import format.
109 *
110 *  This function never fails.
111 *
112 *  \return An array of strings.
113 */
114char const * const * cucul_get_import_list(void)
115{
116    static char const * const list[] =
117        {
118            "", "autodetect",
119            "text", "plain text",
120            "caca", "native libcaca format",
121            "ansi", "ANSI coloured text",
122            NULL, NULL
123        };
124
125    return list;
126}
127
128/*
129 * XXX: the following functions are local.
130 */
131
132static cucul_canvas_t *import_caca(void const *data, unsigned int size)
133{
134    cucul_canvas_t *cv;
135    uint8_t const *buf = (uint8_t const *)data;
136    unsigned int width, height, n;
137
138    if(size < 16)
139        goto invalid_caca;
140
141    if(buf[0] != 'C' || buf[1] != 'A' || buf[2] != 'C' || buf[3] != 'A')
142        goto invalid_caca;
143
144    if(buf[4] != 'C' || buf[5] != 'A' || buf[6] != 'N' || buf[7] != 'V')
145        goto invalid_caca;
146
147    width = ((uint32_t)buf[8] << 24) | ((uint32_t)buf[9] << 16)
148        | ((uint32_t)buf[10] << 8) | (uint32_t)buf[11];
149    height = ((uint32_t)buf[12] << 24) | ((uint32_t)buf[13] << 16)
150        | ((uint32_t)buf[14] << 8) | (uint32_t)buf[15];
151
152    if(!width || !height)
153        goto invalid_caca;
154
155    if(size != 16 + width * height * 8)
156        goto invalid_caca;
157
158    cv = cucul_create_canvas(width, height);
159
160    if(!cv)
161    {
162#if defined(HAVE_ERRNO_H)
163        errno = ENOMEM;
164#endif
165        return NULL;
166    }
167
168    for(n = height * width; n--; )
169        {
170            cv->chars[n] = ((uint32_t)buf[16 + 0 + 8 * n] << 24)
171                | ((uint32_t)buf[16 + 1 + 8 * n] << 16)
172                | ((uint32_t)buf[16 + 2 + 8 * n] << 8)
173                | (uint32_t)buf[16 + 3 + 8 * n];
174            cv->attr[n] = ((uint32_t)buf[16 + 4 + 8 * n] << 24)
175                | ((uint32_t)buf[16 + 5 + 8 * n] << 16)
176                | ((uint32_t)buf[16 + 6 + 8 * n] << 8)
177                | (uint32_t)buf[16 + 7 + 8 * n];
178        }
179
180    return cv;
181
182invalid_caca:
183#if defined(HAVE_ERRNO_H)
184    errno = EINVAL;
185#endif
186    return NULL;
187}
188
189static cucul_canvas_t *import_text(void const *data, unsigned int size)
190{
191    cucul_canvas_t *cv;
192    char const *text = (char const *)data;
193    unsigned int width = 1, height = 1, x = 0, y = 0, i;
194
195    cv = cucul_create_canvas(width, height);
196    if(!cv)
197    {
198#if defined(HAVE_ERRNO_H)
199        errno = ENOMEM;
200#endif
201        return NULL;
202    }
203
204    cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
205
206    for(i = 0; i < size; i++)
207    {
208        unsigned char ch = *text++;
209
210        if(ch == '\r')
211            continue;
212
213        if(ch == '\n')
214        {
215            x = 0;
216            y++;
217            continue;
218        }
219
220        if(x >= width || y >= height)
221        {
222            if(x >= width)
223                width = x + 1;
224
225            if(y >= height)
226                height = y + 1;
227
228            cucul_set_canvas_size(cv, width, height);
229        }
230
231        cucul_putchar(cv, x, y, ch);
232        x++;
233    }
234
235    return cv;
236}
237
238static cucul_canvas_t *import_ansi(void const *data, unsigned int size)
239{
240    struct ansi_grcm grcm;
241    unsigned char const *buffer = (unsigned char const*)data;
242    cucul_canvas_t *cv;
243    unsigned int i, j, skip, dummy = 0;
244    unsigned int width = 1, height = 1;
245    int x = 0, y = 0, save_x = 0, save_y = 0;
246
247    cv = cucul_create_canvas(width, height);
248    if(!cv)
249    {
250#if defined(HAVE_ERRNO_H)
251        errno = ENOMEM;
252#endif
253        return NULL;
254    }
255
256    ansi_parse_grcm(cv, &grcm, 1, &dummy);
257
258    for(i = 0; i < size; i += skip)
259    {
260        skip = 1;
261
262        /* Wrap long lines */
263        if((unsigned int)x >= 80)
264        {
265            x = 0;
266            y++;
267        }
268
269        if(buffer[i] == '\x1a' && size - i >= 8
270           && !memcmp(buffer + i + 1, "SAUCE00", 7))
271            break; /* End before SAUCE data */
272
273        if(buffer[i] == '\r')
274            continue; /* DOS sucks */
275
276        if(buffer[i] == '\n')
277        {
278            x = 0;
279            y++;
280            continue;
281        }
282
283        /* Interpret escape commands, as per Standard ECMA-48 "Control
284         * Functions for Coded Character Sets", 5.4. Control sequences. */
285        if(buffer[i] == '\x1b' && buffer[i + 1] == '[')
286        {
287            unsigned int argc = 0, argv[101];
288            unsigned int param, inter, final;
289
290        /* Compute offsets to parameter bytes, intermediate bytes and
291         * to the final byte. Only the final byte is mandatory, there
292         * can be zero of the others.
293         * 0  param=2             inter                 final           final+1
294         * +-----+------------------+---------------------+-----------------+
295         * | CSI | parameter bytes  | intermediate bytes  |   final byte    |
296         * |     |   0x30 - 0x3f    |    0x20 - 0x2f      |   0x40 - 0x7e   |
297         * | ^[[ | 0123456789:;<=>? | SPC !"#$%&'()*+,-./ | azAZ@[\]^_`{|}~ |
298         * +-----+------------------+---------------------+-----------------+
299         */
300            param = 2;
301
302            for(inter = param; i + inter < size; inter++)
303                if(buffer[i + inter] < 0x30 || buffer[i + inter] > 0x3f)
304                    break;
305
306            for(final = inter; i + final < size; final++)
307                if(buffer[i + final] < 0x20 || buffer[i + final] > 0x2f)
308                    break;
309
310            if(buffer[i + final] < 0x40 || buffer[i + final] > 0x7e)
311                break; /* Invalid Final Byte */
312
313            skip += final;
314
315            /* Sanity checks */
316            if(param < inter && buffer[i + param] >= 0x3c)
317            {
318                fprintf(stderr, "private sequence \"^[[%.*s\"\n",
319                        final - param + 1, buffer + i + param);
320                continue; /* Private sequence, skip it entirely */
321            }
322
323            if(final - param > 100)
324                continue; /* Suspiciously long sequence, skip it */
325
326            /* Parse parameter bytes as per ECMA-48 5.4.2: Parameter string
327             * format */
328            if(param < inter)
329            {
330                argv[0] = 0;
331                for(j = param; j < inter; j++)
332                {
333                    if(buffer[i + j] == ';')
334                        argv[++argc] = 0;
335                    else if(buffer[i + j] >= '0' && buffer[i + j] <= '9')
336                        argv[argc] = 10 * argv[argc] + (buffer[i + j] - '0');
337                }
338                argc++;
339            }
340
341            /* Interpret final byte. The code representations are given in
342             * ECMA-48 5.4: Control sequences, and the code definitions are
343             * given in ECMA-48 8.3: Definition of control functions. */
344            switch(buffer[i + final])
345            {
346            case 'f': /* CUP - Cursor Position */
347            case 'H': /* HVP - Character And Line Position */
348                x = (argc > 1 && argv[1] > 0) ? argv[1] - 1 : 0;
349                y = (argc > 0 && argv[0] > 0) ? argv[0] - 1 : 0;
350                break;
351            case 'A': /* CUU - Cursor Up */
352                y -= argc ? argv[0] : 1;
353                if(y < 0)
354                    y = 0;
355                break;
356            case 'B': /* CUD - Cursor Down */
357                y += argc ? argv[0] : 1;
358                break;
359            case 'C': /* CUF - Cursor Right */
360                x += argc ? argv[0] : 1;
361                break;
362            case 'D': /* CUB - Cursor Left */
363                x -= argc ? argv[0] : 1;
364                if(x < 0)
365                    x = 0;
366                break;
367            case 's': /* Private (save cursor position) */
368                save_x = x;
369                save_y = y;
370                break;
371            case 'u': /* Private (reload cursor position) */
372                x = save_x;
373                y = save_y;
374                break;
375            case 'J': /* ED - Erase In Page */
376                if(argv[0] == 2)
377                    x = y = 0;
378                break;
379            case 'K': /* EL - Erase In Line */
380                if(width < 80)
381                    cucul_set_color(cv, CUCUL_COLOR_DEFAULT,
382                                        CUCUL_COLOR_TRANSPARENT);
383                    cucul_set_canvas_size(cv, width = 80, height);
384                for(j = x; j < 80; j++)
385                    cucul_putchar(cv, j, y, ' ');
386                x = 80;
387                break;
388            case 'm': /* SGR - Select Graphic Rendition */
389                ansi_parse_grcm(cv, &grcm, argc, argv);
390                break;
391            default:
392                fprintf(stderr, "unknown command %c\n", buffer[i + final]);
393                break;
394            }
395
396            continue;
397        }
398
399        /* We're going to paste a character. First make sure the canvas
400         * is big enough. */
401        if((unsigned int)x >= width)
402        {
403            cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
404            cucul_set_canvas_size(cv, width = x + 1, height);
405        }
406
407        if((unsigned int)y >= height)
408        {
409            cucul_set_color(cv, CUCUL_COLOR_DEFAULT, CUCUL_COLOR_TRANSPARENT);
410            cucul_set_canvas_size(cv, width, height = y + 1);
411        }
412
413        /* Now paste our character */
414        cucul_set_color(cv, grcm.efg, grcm.ebg);
415        cucul_putchar(cv, x, y, cucul_cp437_to_utf32(buffer[i]));
416        x++;
417    }
418
419    return cv;
420}
421
422/* XXX : ANSI loader helper */
423
424static void ansi_parse_grcm(cucul_canvas_t *cv, struct ansi_grcm *g,
425                            unsigned int argc, unsigned int const *argv)
426{
427    static uint8_t const ansi2cucul[] =
428    {
429        CUCUL_COLOR_BLACK, CUCUL_COLOR_RED,
430        CUCUL_COLOR_GREEN, CUCUL_COLOR_BROWN,
431        CUCUL_COLOR_BLUE, CUCUL_COLOR_MAGENTA,
432        CUCUL_COLOR_CYAN, CUCUL_COLOR_LIGHTGRAY
433    };
434
435    unsigned int j;
436
437    for(j = 0; j < argc; j++)
438    {
439        /* Defined in ECMA-48 8.3.117: SGR - SELECT GRAPHIC RENDITION */
440        if(argv[j] >= 30 && argv[j] <= 37)
441            g->fg = ansi2cucul[argv[j] - 30];
442        else if(argv[j] >= 40 && argv[j] <= 47)
443            g->bg = ansi2cucul[argv[j] - 40];
444        else if(argv[j] >= 90 && argv[j] <= 97)
445            g->fg = ansi2cucul[argv[j] - 90] + 8;
446        else if(argv[j] >= 100 && argv[j] <= 107)
447            g->bg = ansi2cucul[argv[j] - 100] + 8;
448        else switch(argv[j])
449        {
450        case 0: /* default rendition */
451            g->fg = CUCUL_COLOR_DEFAULT;
452            g->bg = CUCUL_COLOR_DEFAULT;
453            g->bold = g->negative = g->concealed = 0;
454            break;
455        case 1: /* bold or increased intensity */
456            g->bold = 1;
457            break;
458        case 4: /* singly underlined */
459            break;
460        case 5: /* slowly blinking (less then 150 per minute) */
461            break;
462        case 7: /* negative image */
463            g->negative = 1;
464            break;
465        case 8: /* concealed characters */
466            g->concealed = 1;
467            break;
468        case 22: /* normal colour or normal intensity (neither bold nor faint) */
469            g->bold = 0;
470            break;
471        case 28: /* revealed characters */
472            g->concealed = 0;
473            break;
474        case 39: /* default display colour (implementation-defined) */
475            g->fg = CUCUL_COLOR_DEFAULT;
476            break;
477        case 49: /* default background colour (implementation-defined) */
478            g->bg = CUCUL_COLOR_DEFAULT;
479            break;
480        default:
481            fprintf(stderr, "unknown sgr %i\n", argv[j]);
482            break;
483        }
484    }
485
486    if(g->concealed)
487    {
488        g->efg = g->ebg = CUCUL_COLOR_TRANSPARENT;
489    }
490    else
491    {
492        g->efg = g->negative ? g->bg : g->fg;
493        g->ebg = g->negative ? g->fg : g->bg;
494
495        if(g->bold)
496        {
497            if(g->efg < 8)
498                g->efg += 8;
499            else if(g->efg == CUCUL_COLOR_DEFAULT)
500                g->efg = CUCUL_COLOR_WHITE;
501        }
502    }
503}
504
Note: See TracBrowser for help on using the repository browser.