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

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