Debian Codegraph @

src/cacaplay.c

raw
1 /*
2 * cacaplay caca file player
3 * Copyright (c) 2006-2012 Sam Hocevar <[email protected]>
4 * All Rights Reserved
5 *
6 * This program is free software. It comes without any warranty, to
7 * the extent permitted by applicable law. You can redistribute it
8 * and/or modify it under the terms of the Do What the Fuck You Want
9 * to Public License, Version 2, as published by Sam Hocevar. See
10 * http://www.wtfpl.net/ for more details.
11 */
12
13 #include "config.h"
14
15 #if !defined(__KERNEL__)
16 # include <stdio.h>
17 # include <stdlib.h>
18 # include <sys/types.h>
19 # include <sys/stat.h>
20 # include <fcntl.h>
21 # include <string.h>
22 # include <unistd.h>
23 #endif
24
25 #include "caca.h"
26
27 int main(int argc, char **argv)
28 {
29 caca_canvas_t *cv, *app;
30 caca_display_t *dp;
31 uint8_t *buf = NULL;
32 long int bytes = 0, total = 0;
33 int fd;
34
35 if(argc < 2 || !strcmp(argv[1], "-"))
36 {
37 fd = 0; /* use stdin */
38 }
39 else
40 {
41 fd = open(argv[1], O_RDONLY);
42 if(fd < 0)
43 {
44 fprintf(stderr, "%s: could not open `%s'.\n", argv[0], argv[1]);
45 return 1;
46 }
47 }
48
49 cv = caca_create_canvas(0, 0);
50 app = caca_create_canvas(0, 0);
51 if(cv == NULL || app == NULL)
52 {
53 printf("Can't created canvas\n");
54 return -1;
55 }
56 dp = caca_create_display(cv);
57 if(dp == NULL)
58 {
59 printf("Can't create display\n");
60 return -1;
61 }
62
63
64 for(;;)
65 {
66 caca_event_t ev;
67 int ret = caca_get_event(dp, CACA_EVENT_ANY, &ev, 0);
68 int has_eof = 0;
69
70 if(ret && caca_get_event_type(&ev) & CACA_EVENT_KEY_PRESS)
71 break;
72
73 if(bytes == 0)
74 {
75 ssize_t n;
76 buf = realloc(buf, total + 1);
77 n = read(fd, buf + total, 1);
78 if(n < 0)
79 {
80 fprintf(stderr, "%s: read error\n", argv[0]);
81 free(buf);
82 return -1;
83 }
84 else if(n == 0)
85 {
86 has_eof = 1;
87 }
88 total += n;
89 }
90
91 bytes = caca_import_canvas_from_memory(app, buf, total, "caca");
92
93 if(bytes > 0)
94 {
95 total -= bytes;
96 memmove(buf, buf + bytes, total);
97
98 caca_blit(cv, 0, 0, app, NULL);
99 caca_refresh_display(dp);
100 }
101 else if(bytes < 0)
102 {
103 fprintf(stderr, "%s: corrupted caca file\n", argv[0]);
104 break;
105 }
106
107 if(has_eof)
108 break;
109 }
110
111 caca_get_event(dp, CACA_EVENT_KEY_PRESS, NULL, -1);
112
113 /* Clean up */
114 free(buf);
115 close(fd);
116
117 caca_free_display(dp);
118 caca_free_canvas(cv);
119
120 return 0;
121 }
122