forked from telephil9/view
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
125 lines (113 loc) · 1.82 KB
/
utils.c
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
#include <u.h>
#include <libc.h>
#include <draw.h>
#include "a.h"
void*
emalloc(ulong n)
{
void *p;
p = malloc(n);
if(p==nil)
sysfatal("malloc: %r");
return p;
}
void*
erealloc(void *p, ulong n)
{
void *q;
q = realloc(p, n);
if(q==nil)
sysfatal("realloc: %r");
return q;
}
Image*
eallocimage(int w, int h, ulong chan, int repl, ulong col)
{
Image *i;
i = allocimage(display, Rect(0, 0, w, h), chan, repl, col);
if(i==nil)
sysfatal("allocimage: %r");
return i;
}
uchar*
readfile(char *f, int *len)
{
uchar *buf;
int fd, n, s, r;
fd = open(f, OREAD);
if(fd<0)
sysfatal("open: %r");
n = 0;
s = 4096;
buf = emalloc(s);
for(;;){
r = read(fd, buf + n, s - n);
if(r<0)
sysfatal("read: %r");
if(r==0)
break;
n += r;
if(n==s){
s *= 1.5;
buf = erealloc(buf, s);
}
}
buf[n] = 0;
close(fd);
*len = n;
return buf;
}
int
writefile(char *filename, char *data, int ndata)
{
int fd;
fd = create(filename, OWRITE|OEXCL, 0600);
if(fd < 0)
return -1;
if(write(fd, data, ndata) != ndata)
return -1;
close(fd);
return 0;
}
int
fileformat(char *filename)
{
static struct {
char *k;
int v;
} mimes[] = {
"text/html", SVG,
"image/jpeg", JPEG,
"image/gif", GIF,
"image/png", PNG,
"image/bmp", BMP,
"image/p9bit", NINE,
};
int fd[2], n, i;
char s[32];
if(pipe(fd) < 0)
return -1;
switch(rfork(RFFDG|RFPROC|RFNOWAIT)){
case -1:
close(fd[0]);
close(fd[1]);
return -1;
case 0:
dup(fd[1], 1);
close(fd[1]);
close(fd[0]);
execl("/bin/file", "file", "-m", filename, nil);
_exits("execl");
}
if((n = read(fd[0], s, sizeof s)) <= 0)
return -1;
s[n-1] = 0; /* remove newline */
close(fd[1]);
close(fd[0]);
for(i=0; i<nelem(mimes); i++){
if(strncmp(s, mimes[i].k, strlen(mimes[i].k)) == 0)
return mimes[i].v;
}
werrstr("unknown image type %s", s);
return -1;
}