]> git.imager.perl.org - imager.git/blob - context.c
9967c66b683bc312ed870b863291e7ee8e12b7c6
[imager.git] / context.c
1 #include "imageri.h"
2
3 /*
4 =item im_context_new()
5
6 Create a new Imager context object.
7
8 =cut
9 */
10
11 im_context_t
12 im_context_new(void) {
13   im_context_t ctx = malloc(sizeof(im_context_struct));
14   int i;
15
16   if (!ctx)
17     return NULL;
18   
19   ctx->error_sp = IM_ERROR_COUNT-1;
20   for (i = 0; i < IM_ERROR_COUNT; ++i) {
21     ctx->error_alloc[i] = 0;
22     ctx->error_stack[i].msg = NULL;
23     ctx->error_stack[i].code = 0;
24   }
25 #ifdef IMAGER_LOG
26   ctx->log_level = 0;
27   ctx->lg_file = NULL;
28 #endif
29   ctx->max_width = 0;
30   ctx->max_height = 0;
31   ctx->max_bytes = DEF_BYTES_LIMIT;
32
33   return ctx;
34 }
35
36 /*
37 =item im_context_delete(ctx)
38
39 Release memory used by an Imager context object.
40
41 =cut
42 */
43
44 void
45 im_context_delete(im_context_t ctx) {
46   int i;
47
48   for (i = 0; i < IM_ERROR_COUNT; ++i) {
49     if (ctx->error_stack[i].msg)
50       myfree(ctx->error_stack[i].msg);
51   }
52 #ifdef IMAGER_LOG
53   if (ctx->lg_file)
54     fclose(ctx->lg_file);
55 #endif
56
57   free(ctx);
58 }
59
60 /*
61 =item im_context_clone(ctx)
62
63 Clone an Imager context object, returning the result.
64
65 =cut
66 */
67
68 im_context_t
69 im_context_clone(im_context_t ctx) {
70   im_context_t nctx = malloc(sizeof(im_context_struct));
71   int i;
72
73   if (!nctx)
74     return NULL;
75
76   nctx->error_sp = ctx->error_sp;
77   for (i = 0; i < IM_ERROR_COUNT; ++i) {
78     if (ctx->error_stack[i].msg) {
79       size_t sz = ctx->error_alloc[i];
80       nctx->error_alloc[i] = sz;
81       nctx->error_stack[i].msg = mymalloc(sz);
82       memcpy(nctx->error_stack[i].msg, ctx->error_stack[i].msg, sz);
83     }
84     else {
85       nctx->error_alloc[i] = 0;
86       nctx->error_stack[i].msg = NULL;
87     }
88     nctx->error_stack[i].code = ctx->error_stack[i].code;
89   }
90 #ifdef IMAGER_LOG
91   nctx->log_level = ctx->log_level;
92   if (ctx->lg_file) {
93     /* disable buffering, this isn't perfect */
94     setvbuf(ctx->lg_file, NULL, _IONBF, 0);
95
96     /* clone that and disable buffering some more */
97     nctx->lg_file = fdopen(fileno(ctx->lg_file), "a");
98     if (nctx->lg_file)
99       setvbuf(nctx->lg_file, NULL, _IONBF, 0);
100   }
101   else {
102     nctx->lg_file = NULL;
103   }
104 #endif
105   nctx->max_width = ctx->max_width;
106   nctx->max_height = ctx->max_height;
107   nctx->max_bytes = ctx->max_bytes;
108
109   return ctx;
110 }