summaryrefslogtreecommitdiff
path: root/test/any2ppm.c
blob: 3b590d943744a30991627d569d3e4ae055ef6b45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/*
 * Copyright © 2008 Chris Wilson
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without
 * fee, provided that the above copyright notice appear in all copies
 * and that both that copyright notice and this permission notice
 * appear in supporting documentation, and that the name of
 * Chris Wilson not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission. Chris Wilson makes no representations about the
 * suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * CHRIS WILSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL CHRIS WILSON BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author: Chris Wilson <chris@chris-wilson.co.uk>
 *
 * Contributor(s):
 *	Carlos Garcia Campos <carlosgc@gnome.org>
 *
 * Adapted from pdf2png.c:
 * Copyright © 2005 Red Hat, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without
 * fee, provided that the above copyright notice appear in all copies
 * and that both that copyright notice and this permission notice
 * appear in supporting documentation, and that the name of
 * Red Hat, Inc. not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior
 * permission. Red Hat, Inc. makes no representations about the
 * suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * RED HAT, INC. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL RED HAT, INC. BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author: Kristian Høgsberg <krh@redhat.com>
 */

#if HAVE_CONFIG_H
#include "config.h"
#endif

#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <cairo.h>

#if CAIRO_CAN_TEST_PDF_SURFACE
#include <poppler.h>
#endif

#if CAIRO_CAN_TEST_SVG_SURFACE
#include <librsvg/rsvg.h>
#include <librsvg/rsvg-cairo.h>
#endif

#if CAIRO_HAS_SPECTRE
#include <libspectre/spectre.h>
#endif

#if HAVE_FCNTL_H && HAVE_SIGNAL_H && HAVE_SYS_STAT_H && HAVE_SYS_SOCKET_H && HAVE_SYS_POLL_H && HAVE_SYS_UN_H
#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/un.h>
#include <errno.h>

#define SOCKET_PATH "./.any2ppm"
#define TIMEOUT 60000 /* 60 seconds */

#define CAN_RUN_AS_DAEMON 1
#endif

#define ARRAY_LENGTH(A) (sizeof (A) / sizeof (A[0]))

static int
_writen (int fd, char *buf, int len)
{
    while (len) {
	int ret;

	ret = write (fd, buf, len);
	if (ret == -1) {
	    int err = errno;
	    switch (err) {
	    case EINTR:
	    case EAGAIN:
		continue;
	    default:
		return 0;
	    }
	}
	len -= ret;
	buf += ret;
    }

    return 1;
}

static int
_write (int fd,
	char *buf, int maxlen, int buflen,
	const unsigned char *src, int srclen)
{
    if (buflen < 0)
	return buflen;

    while (srclen) {
	int len;

	len = buflen + srclen;
	if (len > maxlen)
	    len = maxlen;
	len -= buflen;

	memcpy (buf + buflen, src, len);
	buflen += len;
	srclen -= len;
	src += len;

	if (buflen == maxlen) {
	    if (! _writen (fd, buf, buflen))
		return -1;

	    buflen = 0;
	}
    }

    return buflen;
}

static const char *
write_ppm (cairo_surface_t *surface, int fd)
{
    char buf[4096];
    cairo_format_t format;
    const char *format_str;
    const unsigned char *data;
    int len;
    int width, height, stride;
    int i, j;

    data = cairo_image_surface_get_data (surface);
    height = cairo_image_surface_get_height (surface);
    width = cairo_image_surface_get_width (surface);
    stride = cairo_image_surface_get_stride (surface);
    format = cairo_image_surface_get_format (surface);
    if (format == CAIRO_FORMAT_ARGB32) {
	/* see if we can convert to a standard ppm type and trim a few bytes */
	const unsigned char *alpha = data;
	for (j = height; j--; alpha += stride) {
	    for (i = 0; i < width; i++) {
		if ((*(unsigned int *) (alpha+4*i) & 0xff000000) != 0xff000000)
		    goto done;
	    }
	}
	format = CAIRO_FORMAT_RGB24;
 done: ;
    }

    switch (format) {
    case CAIRO_FORMAT_ARGB32:
	/* XXX need true alpha for svg */
	format_str = "P7";
	break;
    case CAIRO_FORMAT_RGB24:
	format_str = "P6";
	break;
    case CAIRO_FORMAT_A8:
	format_str = "P5";
	break;
    case CAIRO_FORMAT_A1:
    default:
	return "unhandled image format";
    }

    len = sprintf (buf, "%s %d %d 255\n", format_str, width, height);
    for (j = 0; j < height; j++) {
	const unsigned char *row = data + stride * j;

	switch ((int) format) {
	case CAIRO_FORMAT_ARGB32:
	    len = _write (fd,
			  buf, sizeof (buf), len,
			  row, 4 * width);
	    break;
	case CAIRO_FORMAT_RGB24:
	    for (i = 0; i < width; i++) {
		unsigned char rgb[3];
		unsigned int p = *row++;
		rgb[0] = (p & 0xff0000) >> 16;
		rgb[1] = (p & 0x00ff00) >> 8;
		rgb[2] = (p & 0x0000ff) >> 0;
		len = _write (fd,
			      buf, sizeof (buf), len,
			      rgb, 3);
	    }
	    break;
	case CAIRO_FORMAT_A8:
	    len = _write (fd,
			  buf, sizeof (buf), len,
			  row, width);
	    break;
	}
	if (len < 0)
	    return "write failed";
    }

    if (len && ! _writen (fd, buf, len))
	return "write failed";

    return NULL;
}

#if CAIRO_CAN_TEST_PDF_SURFACE
/* adapted from pdf2png.c */
static const char *
_poppler_render_page (const char *filename,
		      const char *page_label,
		      cairo_surface_t **surface_out)
{
    PopplerDocument *document;
    PopplerPage *page;
    double width, height;
    GError *error = NULL;
    gchar *absolute, *uri;
    cairo_surface_t *surface;
    cairo_t *cr;
    cairo_status_t status;

    if (g_path_is_absolute (filename)) {
	absolute = g_strdup (filename);
    } else {
	gchar *dir = g_get_current_dir ();
	absolute = g_build_filename (dir, filename, (gchar *) 0);
	g_free (dir);
    }

    uri = g_filename_to_uri (absolute, NULL, &error);
    g_free (absolute);
    if (uri == NULL)
	return error->message; /* XXX g_error_free (error) */

    document = poppler_document_new_from_file (uri, NULL, &error);
    g_free (uri);
    if (document == NULL)
	return error->message; /* XXX g_error_free (error) */

    page = poppler_document_get_page_by_label (document, page_label);
    g_object_unref (document);
    if (page == NULL)
	return "page not found";

    poppler_page_get_size (page, &width, &height);

    surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height);
    cr = cairo_create (surface);

    cairo_set_source_rgb (cr, 1., 1., 1.);
    cairo_paint (cr);

    poppler_page_render (page, cr);
    g_object_unref (page);

    status = cairo_status (cr);
    cairo_destroy (cr);

    if (status) {
	cairo_surface_destroy (surface);
	return  cairo_status_to_string (status);
    }

    *surface_out = surface;
    return NULL;
}

static const char *
pdf_convert (char **argv, int fd)
{
    const char *err;
    cairo_surface_t *surface = NULL; /* silence compiler warning */

    err = _poppler_render_page (argv[0], argv[1], &surface);
    if (err != NULL)
	return err;

    err = write_ppm (surface, fd);
    cairo_surface_destroy (surface);

    return err;
}
#else
static const char *
pdf_convert (char **argv, int fd)
{
    return "compiled without PDF support.";
}
#endif

#if CAIRO_CAN_TEST_SVG_SURFACE
static const char *
_rsvg_render_page (const char *filename,
		   cairo_surface_t **surface_out)
{
    RsvgHandle *handle;
    RsvgDimensionData dimensions;
    GError *error = NULL;
    cairo_surface_t *surface;
    cairo_t *cr;
    cairo_status_t status;

    handle = rsvg_handle_new_from_file (filename, &error);
    if (handle == NULL)
	return error->message; /* XXX g_error_free */

    rsvg_handle_get_dimensions (handle, &dimensions);
    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
					  dimensions.width,
					  dimensions.height);
    cr = cairo_create (surface);

    rsvg_handle_render_cairo (handle, cr);
    g_object_unref (handle);

    status = cairo_status (cr);
    cairo_destroy (cr);

    if (status) {
	cairo_surface_destroy (surface);
	return  cairo_status_to_string (status);
    }

    *surface_out = surface;
    return NULL;
}

static const char *
svg_convert (char **argv, int fd)
{
    const char *err;
    cairo_surface_t *surface = NULL; /* silence compiler warning */

    err = _rsvg_render_page (argv[0], &surface);
    if (err != NULL)
	return err;

    err = write_ppm (surface, fd);
    cairo_surface_destroy (surface);

    return err;
}
#else
static const char *
svg_convert (char **argv, int fd)
{
    return "compiled without SVG support.";
}
#endif

#if CAIRO_HAS_SPECTRE
static const char *
_spectre_render_page (const char *filename,
		      const char *page_label,
		      cairo_surface_t **surface_out)
{
    static const cairo_user_data_key_t key;

    SpectreDocument *document;
    SpectreStatus status;
    int width, height, stride;
    unsigned char *pixels;
    cairo_surface_t *surface;

    document = spectre_document_new ();
    spectre_document_load (document, filename);
    status = spectre_document_status (document);
    if (status) {
	spectre_document_free (document);
	return spectre_status_to_string (status);
    }

    if (page_label) {
	SpectrePage *page;
	SpectreRenderContext *rc;

	page = spectre_document_get_page_by_label (document, page_label);
	spectre_document_free (document);
	if (page == NULL)
	    return "page not found";

	spectre_page_get_size (page, &width, &height);
	rc = spectre_render_context_new ();
	spectre_render_context_set_page_size (rc, width, height);
	spectre_page_render (page, rc, &pixels, &stride);
	spectre_render_context_free (rc);
	status = spectre_page_status (page);
	spectre_page_free (page);
	if (status) {
	    free (pixels);
	    return spectre_status_to_string (status);
	}
    } else {
	spectre_document_get_page_size (document, &width, &height);
	spectre_document_render (document, &pixels, &stride);
	spectre_document_free (document);
    }

    surface = cairo_image_surface_create_for_data (pixels,
						   CAIRO_FORMAT_RGB24,
						   width, height,
						   stride);
    cairo_surface_set_user_data (surface, &key,
				 pixels, (cairo_destroy_func_t) free);
    *surface_out = surface;
    return NULL;
}

static const char *
ps_convert (char **argv, int fd)
{
    const char *err;
    cairo_surface_t *surface = NULL; /* silence compiler warning */

    err = _spectre_render_page (argv[0], argv[1], &surface);
    if (err != NULL)
	return err;

    err = write_ppm (surface, fd);
    cairo_surface_destroy (surface);

    return err;
}
#else
static const char *
ps_convert (char **argv, int fd)
{
    return "compiled without PostScript support.";
}
#endif

static const char *
convert (char **argv, int fd)
{
    static const struct converter {
	const char *type;
	const char *(*func) (char **, int);
    } converters[] = {
	{ "pdf", pdf_convert },
	{ "ps", ps_convert },
	{ "svg", svg_convert },
	{ NULL, NULL }
    };
    const struct converter *converter = converters;
    char *type;

    type = strrchr (argv[0], '.');
    if (type == NULL)
	return "no file extension";
    type++;

    while (converter->type) {
	if (strcmp (type, converter->type) == 0)
	    return converter->func (argv, fd);
	converter++;
    }
    return "no converter";
}

#if CAN_RUN_AS_DAEMON
static int
_getline (int fd, char **linep, size_t *lenp)
{
    char *line;
    size_t len, i;
    ssize_t ret;

    line = *linep;
    if (line == NULL) {
	line = malloc (1024);
	if (line == NULL)
	    return -1;
	line[0] = '\0';
	len = 1024;
    } else
	len = *lenp;

    /* XXX simple, but ugly! */
    i = 0;
    do {
	if (i == len - 1) {
	    char *nline;

	    nline = realloc (line, len + 1024);
	    if (nline == NULL)
		goto out;

	    line = nline;
	    len += 1024;
	}

	ret = read (fd, line + i, 1);
	if (ret == -1 || ret == 0)
	    goto out;
    } while (line[i++] != '\n');

out:
    line[i] = '\0';
    *linep = line;
    *lenp = len;
    return i-1;
}

static int
split_line (char *line, char *argv[], int max_argc)
{
    int i = 0;

    max_argc--; /* leave one spare for the trailing NULL */

    argv[i++] = line;
    while (i < max_argc && (line = strchr (line, ' ')) != NULL) {
	*line++ = '\0';
	argv[i++] = line;
    }

    /* chomp the newline */
    line = strchr (argv[i-1], '\n');
    if (line != NULL)
	*line = '\0';

    argv[i] = NULL;

    return i;
}

static int
any2ppm_daemon_exists (void)
{
    struct stat st;
    int fd;
    char buf[80];
    int pid;
    int ret;

    if (stat (SOCKET_PATH, &st) < 0)
	return 0;

    fd = open (SOCKET_PATH ".pid", O_RDONLY);
    if (fd < 0)
	return 0;

    pid = 0;
    ret = read (fd, buf, sizeof (buf) - 1);
    if (ret > 0) {
	buf[ret] = '\0';
	pid = atoi (buf);
    }
    close (fd);

    return pid > 0 && kill (pid, 0) == 0;
}

static int
write_pid_file (void)
{
    int fd;
    char buf[80];
    int ret;

    fd = open (SOCKET_PATH ".pid", O_CREAT | O_TRUNC | O_WRONLY, 0666);
    if (fd < 0)
	return 0;

    ret = sprintf (buf, "%d\n", getpid ());
    ret = write (fd, buf, ret) == ret;
    close (fd);

    return ret;
}

static const char *
any2ppm_daemon (void)
{
    int timeout = TIMEOUT;
    struct pollfd pfd;
    int sk, fd;
    long flags;
    struct sockaddr_un addr;
    char *line = NULL;
    size_t len = 0;

#ifdef SIGPIPE
    signal (SIGPIPE, SIG_IGN);
#endif

    /* XXX racy! */
    if (getenv ("ANY2PPM_FORCE") == NULL && any2ppm_daemon_exists ())
	return "any2ppm daemon already running";

    unlink (SOCKET_PATH);

    sk = socket (PF_UNIX, SOCK_STREAM, 0);
    if (sk == -1)
	return "unable to create socket";

    memset (&addr, 0, sizeof (addr));
    addr.sun_family = AF_UNIX;
    strcpy (addr.sun_path, SOCKET_PATH);
    if (bind (sk, (struct sockaddr *) &addr, sizeof (addr)) == -1) {
	close (sk);
	return "unable to bind socket";
    }

    flags = fcntl (sk, F_GETFL);
    if (flags == -1 || fcntl (sk, F_SETFL, flags | O_NONBLOCK) == -1) {
	close (sk);
	return "unable to set socket to non-blocking";
    }

    if (listen (sk, 5) == -1) {
	close (sk);
	return "unable to listen on socket";
    }

    /* ready for client connection - detach from parent/terminal */
    if (getenv ("ANY2PPM_NODAEMON") == NULL && daemon (1, 0) == -1) {
	close (sk);
	return "unable to detach from parent";
    }

    if (! write_pid_file ()) {
	close (sk);
	return "unable to write pid file";
    }

    if (getenv ("ANY2PPM_TIMEOUT") != NULL) {
	timeout = atoi (getenv ("ANY2PPM_TIMEOUT"));
	if (timeout == 0)
	    timeout = -1;
	if (timeout > 0)
	    timeout *= 1000; /* convert env (in seconds) to milliseconds */
    }

    pfd.fd = sk;
    pfd.events = POLLIN;
    pfd.revents = 0; /* valgrind */
    while (poll (&pfd, 1, timeout) > 0) {
	while ((fd = accept (sk, NULL, NULL)) != -1) {
	    if (_getline (fd, &line, &len) != -1) {
		char *argv[10];

		if (split_line (line, argv, ARRAY_LENGTH (argv)) > 0) {
		    const char *err;

		    err = convert (argv, fd);
		    if (err != NULL) {
			FILE *file = fopen (".any2ppm.errors", "a");
			if (file != NULL) {
			    fprintf (file,
				     "Failed to convert '%s': %s\n",
				     argv[0], err);
			    fclose (file);
			}
		    }
		}
	    }
	    close (fd);
	}
    }
    close (sk);
    unlink (SOCKET_PATH);
    unlink (SOCKET_PATH ".pid");

    free (line);
    return NULL;
}
#else
static const char *
any2ppm_daemon (void)
{
    return "daemon not compiled in.";
}
#endif

int
main (int argc, char **argv)
{
    const char *err;

    g_type_init ();

#if CAIRO_CAN_TEST_SVG_SURFACE
    rsvg_init ();
    rsvg_set_default_dpi (72.0);
#endif

    if (argc == 1)
	err = any2ppm_daemon ();
    else
	err = convert (argv + 1, 1);
    if (err != NULL) {
	fprintf (stderr, "Failed to run converter: %s\n", err);
	return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}