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

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