summaryrefslogtreecommitdiff
path: root/source/fitz/directory.c
blob: 5b9ccf8293d1e481fd79c8b75b91b84a6b8d565f (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
#include "mupdf/fitz.h"

typedef struct fz_directory_s fz_directory;
struct fz_directory_s
{
	fz_archive super;

	char *path;
};

static void drop_directory(fz_context *ctx, fz_archive *arch)
{
	fz_directory *dir = (fz_directory *) arch;

	fz_free(ctx, dir->path);
}

static fz_stream *open_dir_entry(fz_context *ctx, fz_archive *arch, const char *name)
{
	fz_directory *dir = (fz_directory *) arch;
	char path[2048];
	fz_strlcpy(path, dir->path, sizeof path);
	fz_strlcat(path, "/", sizeof path);
	fz_strlcat(path, name, sizeof path);
	return fz_open_file(ctx, path);
}

static fz_buffer *read_dir_entry(fz_context *ctx, fz_archive *arch, const char *name)
{
	fz_directory *dir = (fz_directory *) arch;
	char path[2048];
	fz_strlcpy(path, dir->path, sizeof path);
	fz_strlcat(path, "/", sizeof path);
	fz_strlcat(path, name, sizeof path);
	return fz_read_file(ctx, path);
}

static int has_dir_entry(fz_context *ctx, fz_archive *arch, const char *name)
{
	fz_directory *dir = (fz_directory *) arch;
	char path[2048];
	fz_strlcpy(path, dir->path, sizeof path);
	fz_strlcat(path, "/", sizeof path);
	fz_strlcat(path, name, sizeof path);
	return fz_file_exists(ctx, path);
}

int
fz_is_directory(fz_context *ctx, const char *path)
{
	struct stat info;

	if (stat(path, &info) < 0)
		fz_throw(ctx, FZ_ERROR_GENERIC, "cannot stat: %s", strerror(errno));

	return info.st_mode & S_IFDIR;
}

fz_archive *
fz_open_directory(fz_context *ctx, const char *path)
{
	fz_directory *dir;

	if (!fz_is_directory(ctx, path))
		fz_throw(ctx, FZ_ERROR_GENERIC, "'%s' is not a directory", path);

	dir = fz_new_archive(ctx, NULL, fz_directory);
	dir->super.format = "dir";
	dir->super.has_entry = has_dir_entry;
	dir->super.read_entry = read_dir_entry;
	dir->super.open_entry = open_dir_entry;
	dir->super.drop_archive = drop_directory;

	fz_try(ctx)
	{
		dir->path = fz_strdup(ctx, path);
	}
	fz_catch(ctx)
	{
		fz_drop_archive(ctx, &dir->super);
		fz_rethrow(ctx);
	}

	return &dir->super;
}