forked from pytroll/aggdraw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aggdraw.cxx
2726 lines (2359 loc) · 84.6 KB
/
aggdraw.cxx
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* AGG Draw Library
*
* WCK-style drawing using the AGG library.
*
* history:
* 2004-09-14 fl created, based on experimental code
* 2004-09-15 fl added pen/brush objects (from ironpil), multiple modes
* 2004-09-16 fl added text, arc/ellipse support
* 2005-03-25 fl added BGRA support
* 2005-05-02 fl added (experimental) symbol support
* 2005-05-12 fl added image constructor and flush method
* 2005-05-18 fl fixed possible image constructor crash
* 2005-05-18 fl make sure to keep a reference to the image
* 2005-05-19 fl improved symbol path support
* 2005-06-12 fl added support for S and T path operators
* 2005-06-15 fl added support for outline fonts
* 2005-06-15 fl support settransform for basic primitives and text
* 2005-06-19 fl use ImageColor.getrgb to resolve colors
* 2005-06-30 fl added Path object (stub)
* 2005-07-04 fl added Path methods (moveto, lineto, etc)
* 2005-07-05 fl added Path support to the line and polygon primitives
* 2005-08-10 fl fixed Draw(im) buffer memory leak (ouch!)
* 2005-08-20 fl fixed background color setting for RGB modes
* 2005-08-30 fl expand polygons by 0.5 pixels by default (experimental)
* 2005-08-30 fl fixed proper clipping in rasterizer
* 2005-09-23 fl added antialias setting
* 2005-09-24 fl don't recreate draw adaptor for each operation
* 2005-09-26 fl added coords method to Path type
* 2005-10-10 fl fixed broken add_path calls in symbol renderer (1.1)
* 2005-10-19 fl added native Windows support (via the Dib factory)
* 2005-10-20 fl added clear method
* 2005-10-23 fl support either hdc or hwnd in expose
* 2006-02-12 fl fixed crashes in type(obj) and path constructor
* 2014-07-28 dg Updated to agg-2.4
* 2015-07-15 ej fixed broken paths
* 2017-01-03 ej added support for python 3
* 2017-01-03 ej tostring() -> tobytes(), fromstring() -> frombytes()
* 2017-08-18 dh fixed mode to be python str instead of bytes
* 2017-08-18 dh fixed a couple compiler warnings (specifically clang)
* 2018-04-21 dh fixed python 2 compatibility in getcolor
*
* Copyright (c) 2003-2006 by Secret Labs AB
* Copyright (c) 2014-2016 by Dov Grobgeld
* Copyright (c) 2011-2017 by AggDraw Developers
*
*/
#define Q(x) #x
#define QUOTE(x) Q(x)
#if defined(_MSC_VER)
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifndef M_PI
#define M_PI 3.1415926535897931
#endif
#define PY_SSIZE_T_CLEAN 1
#include "Python.h"
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#define HAVE_UNICODE
#define NON_CONST_MAYBE(s) (s)
#else
#define NON_CONST_MAYBE(s) (char*)(s)
#endif
#include "bytesobject.h"
#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x01060000
#if PY_VERSION_HEX < 0x02020000 || defined(Py_USING_UNICODE)
/* defining this enables unicode support (default under 1.6a1 and later) */
#define HAVE_UNICODE
#endif
#endif
/* agg2 components */
#include "agg_arc.h"
#include "agg_conv_contour.h"
#include "agg_conv_curve.h"
// #include "agg_conv_dash.h"
#include "agg_conv_stroke.h"
#include "agg_conv_transform.h"
#include "agg_ellipse.h"
#include "agg_rounded_rect.h"
#if defined(HAVE_FREETYPE2)
#include "agg_font_freetype.h"
#endif
#include "agg_path_storage.h"
#include "agg_pixfmt_gray.h"
#include "agg_pixfmt_rgb.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_renderer_scanline.h"
#include "agg_rendering_buffer.h"
#include "agg_scanline_p.h"
#include "agg_vcgen_stroke.h"
#include "platform/agg_platform_support.h" // agg::pix_format_*
/* -------------------------------------------------------------------- */
/* AGG Drawing Surface */
#if defined(HAVE_FREETYPE2)
typedef agg::font_engine_freetype_int32 font_engine_type;
typedef agg::font_cache_manager<font_engine_type> font_manager_type;
static font_engine_type font_engine;
static font_manager_type font_manager(font_engine);
#endif
/* forward declaration */
class draw_adaptor_base;
template<class PixFmt> class draw_adaptor;
typedef struct {
PyObject_HEAD
draw_adaptor_base *draw;
agg::rendering_buffer* buffer;
agg::trans_affine* transform;
unsigned char* buffer_data;
int mode; // agg::pix_format_*
int xsize, ysize;
int buffer_size;
PyObject* image;
PyObject* background;
#if defined(WIN32)
HDC dc;
HBITMAP bitmap;
HGDIOBJ old_bitmap;
BITMAPINFO info;
#endif
} DrawObject;
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
/* glue functions (see the init function for details) */
static PyObject* aggdraw_getcolor_obj;
static void draw_dealloc(DrawObject* self);
#ifdef IS_PY3K
static PyObject* draw_getattro(DrawObject* self, PyObject* nameobj);
static PyTypeObject DrawType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Draw", sizeof(DrawObject), 0,
/* methods */
(destructor) draw_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash*/
0, /* tp_call*/
0, /* tp_str*/
(getattrofunc)draw_getattro, /* tp_getattro */
};
#else
static PyObject* draw_getattr(DrawObject* self, char* name);
static PyTypeObject DrawType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Draw", sizeof(DrawObject), 0,
/* methods */
(destructor) draw_dealloc, /* tp_dealloc */
(printfunc)0, /* tp_print */
(getattrfunc)draw_getattr, /* tp_getattr */
0, /* tp_setattr */
};
#endif
typedef struct {
PyObject_HEAD
agg::rgba8 color;
float width;
agg::line_join_e line_join;
agg::line_cap_e line_cap;
float miter_limit;
} PenObject;
static void pen_dealloc(PenObject* self);
#ifdef IS_PY3K
static PyTypeObject PenType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Pen", sizeof(PenObject), 0,
/* methods */
(destructor) pen_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
};
#else
static PyTypeObject PenType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Pen", sizeof(PenObject), 0,
/* methods */
(destructor) pen_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
};
#endif
#define Pen_Check(op) ((op) != NULL && Py_TYPE(op) == &PenType)
typedef struct {
PyObject_HEAD
agg::rgba8 color;
} BrushObject;
static void brush_dealloc(BrushObject* self);
#ifdef IS_PY3K
static PyTypeObject BrushType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Brush", sizeof(BrushObject), 0,
/* methods */
(destructor) brush_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
};
#else
static PyTypeObject BrushType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Brush", sizeof(BrushObject), 0,
/* methods */
(destructor) brush_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
};
#endif
#define Brush_Check(op) ((op) != NULL && Py_TYPE(op) == &BrushType)
typedef struct {
PyObject_HEAD
char* filename;
float height;
agg::rgba8 color;
} FontObject;
#if defined(HAVE_FREETYPE2)
static FT_Face font_load(FontObject* font, bool outline=false);
#endif
static void font_dealloc(FontObject* self);
#ifdef IS_PY3K
static PyObject* font_getattro(FontObject* self, PyObject* nameobj);
static PyTypeObject FontType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Font", sizeof(FontObject), 0,
/* methods */
(destructor) font_dealloc, /* tp_dealloc */
(printfunc)0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
(getattrofunc)font_getattro, /* tp_getattro */
};
#else
static PyObject* font_getattr(FontObject* self, char* name);
static PyTypeObject FontType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Font", sizeof(FontObject), 0,
/* methods */
(destructor) font_dealloc, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) font_getattr, /* tp_getattr */
0, /* tp_setattr */
};
#endif
#define Font_Check(op) ((op) != NULL && Py_TYPE(op) == &FontType)
typedef struct {
PyObject_HEAD
agg::path_storage* path;
} PathObject;
static void path_dealloc(PathObject* self);
#ifdef IS_PY3K
static PyObject* path_getattro(PathObject* self, PyObject* nameobj);
static PyTypeObject PathType = {
PyVarObject_HEAD_INIT(NULL, 0)
"Path", sizeof(PathObject), 0,
/* methods */
(destructor) path_dealloc, /* tp_dealloc */
(printfunc)0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
(getattrofunc)path_getattro, /* tp_getattro */
};
#else
static PyObject* path_getattr(PathObject* self, char* name);
static PyTypeObject PathType = {
PyObject_HEAD_INIT(NULL)
0, "Path", sizeof(PathObject), 0,
/* methods */
(destructor) path_dealloc, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) path_getattr, /* tp_getattr */
0, /* tp_setattr */
};
#endif
#define Path_Check(op) ((op) != NULL && Py_TYPE(op) == &PathType)
static agg::rgba8 getcolor(PyObject* color, int opacity=255);
/* -------------------------------------------------------------------- */
#if defined(HAVE_FREETYPE2)
static int
text_getchar(PyObject* string, int index, unsigned long* char_out)
{
#if defined(HAVE_UNICODE)
if (PyUnicode_Check(string)) {
Py_UNICODE* p = PyUnicode_AS_UNICODE(string);
int size = PyUnicode_GET_SIZE(string);
if (index >= size)
return 0;
*char_out = p[index];
return 1;
}
#endif
if (PyBytes_Check(string)) {
unsigned char* p = (unsigned char*) PyBytes_AS_STRING(string);
int size = PyBytes_GET_SIZE(string);
if (index >= size)
return 0;
*char_out = (unsigned char) p[index];
return 1;
}
return 0;
}
#endif
/* This template class is used to automagically instantiate drawing
code for all pixel formats used by the library. */
class draw_adaptor_base
{
public:
char* mode;
draw_adaptor_base() : mode(NULL) {};
virtual ~draw_adaptor_base() {
if(mode)
free(mode);
};
virtual void setantialias(bool flag) = 0;
virtual void draw(agg::path_storage &path, PyObject* obj1,
PyObject* obj2=NULL) = 0;
virtual void drawtext(float xy[2], PyObject* text, FontObject* font) {};
};
template<class PixFmt> class draw_adaptor : public draw_adaptor_base {
DrawObject* self;
typedef agg::renderer_base<PixFmt> renderer_base;
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;
agg::rasterizer_scanline_aa<> rasterizer;
agg::scanline_p8 scanline;
public:
draw_adaptor(DrawObject* self_, const char* mode_)
{
self = self_;
if (mode)
free(mode);
mode = strdup(mode_);
setantialias(true);
rasterizer.clip_box(0,0, self->xsize, self->ysize);
}
void setantialias(bool flag)
{
if (flag)
rasterizer.gamma(agg::gamma_linear());
else
rasterizer.gamma(agg::gamma_threshold(0.5));
};
void draw(agg::path_storage &path, PyObject* obj1, PyObject* obj2=NULL)
{
PixFmt pf(*self->buffer);
renderer_base rb(pf);
renderer_aa renderer(rb);
agg::path_storage* p;
PenObject* pen;
if (Pen_Check(obj1))
pen = (PenObject*) obj1;
else if (Pen_Check(obj2))
pen = (PenObject*) obj2;
else
pen = NULL;
BrushObject* brush;
if (Brush_Check(obj2))
brush = (BrushObject*) obj2;
else if (Brush_Check(obj1))
brush = (BrushObject*) obj1;
else
brush = NULL;
if (self->transform) {
p = new agg::path_storage();
agg::conv_transform<agg::path_storage, agg::trans_affine>
tp(path, *self->transform);
p->concat_path(tp, 0);
} else
p = &path;
if (brush) {
/* interior */
agg::conv_contour<agg::path_storage> contour(*p);
contour.auto_detect_orientation(true);
rasterizer.reset();
rasterizer.add_path(contour);
renderer.color(brush->color);
agg::render_scanlines(rasterizer, scanline, renderer);
}
if (pen) {
/* outline */
/* FIXME: add path for dashed lines */
agg::conv_stroke<agg::path_storage> stroke(*p);
stroke.line_join(pen->line_join);
stroke.line_cap(pen->line_cap);
stroke.miter_limit(pen->miter_limit);
stroke.width(pen->width);
rasterizer.reset();
rasterizer.add_path(stroke);
renderer.color(pen->color);
agg::render_scanlines(rasterizer, scanline, renderer);
}
if (self->transform)
delete p;
}
#if defined(HAVE_FREETYPE2)
void drawtext(float xy[2], PyObject* text, FontObject* font)
{
PixFmt pf(*self->buffer);
renderer_base rb(pf);
renderer_aa renderer(rb);
typedef agg::conv_curve<font_manager_type::path_adaptor_type> curve_t;
curve_t curves(font_manager.path_adaptor());
bool outline = (self->transform != NULL);
FT_Face face = font_load(font, outline);
if (!face)
return;
double x = xy[0];
double y = xy[1] + face->size->metrics.ascender/64.0;
renderer.color(font->color);
curves.approximation_scale(1);
unsigned long ch;
int index = 0;
while (text_getchar(text, index, &ch)) {
const agg::glyph_cache* glyph;
glyph = font_manager.glyph(ch);
if (!glyph)
continue;
font_manager.add_kerning(&x, &y);
font_manager.init_embedded_adaptors(glyph, x, y);
if (outline) {
rasterizer.reset();
if (self->transform) {
agg::conv_transform<curve_t, agg::trans_affine>
tp(curves, *self->transform);
rasterizer.add_path(tp);
} else
rasterizer.add_path(curves);
agg::render_scanlines(rasterizer, scanline, renderer);
} else {
agg::render_scanlines(
font_manager.gray8_adaptor(),
font_manager.gray8_scanline(), renderer
);
}
x += glyph->advance_x;
y += glyph->advance_y;
index++;
}
}
#endif
};
/* -------------------------------------------------------------------- */
static void clear(DrawObject* self, PyObject* background)
{
if (background && background != Py_None) {
agg::rgba8 ink = getcolor(background);
unsigned char* p = self->buffer_data;
int c, i;
switch (self->mode) {
case agg::pix_format_gray8:
c = (ink.r*299 + ink.g*587 + ink.b*114) / 1000;
memset(self->buffer_data, c, self->buffer_size);
break;
case agg::pix_format_rgb24:
for (i = 0; i < self->buffer_size; i += 3) {
p[i+0] = ink.r;
p[i+1] = ink.g;
p[i+2] = ink.b;
}
break;
case agg::pix_format_bgr24:
for (i = 0; i < self->buffer_size; i += 3) {
p[i+0] = ink.b;
p[i+1] = ink.g;
p[i+2] = ink.r;
}
break;
case agg::pix_format_rgba32:
for (i = 0; i < self->buffer_size; i += 4) {
p[i+0] = ink.r;
p[i+1] = ink.g;
p[i+2] = ink.b;
p[i+3] = ink.a;
}
break;
case agg::pix_format_bgra32:
for (i = 0; i < self->buffer_size; i += 4) {
p[i+0] = ink.b;
p[i+1] = ink.g;
p[i+2] = ink.r;
p[i+3] = ink.a;
}
break;
}
} else
memset(self->buffer_data, 255, self->buffer_size);
}
static void draw_setup(DrawObject* self)
{
switch (self->mode) {
case agg::pix_format_gray8:
self->draw = new draw_adaptor<agg::pixfmt_gray8>(self, "L");
break;
case agg::pix_format_rgb24:
self->draw = new draw_adaptor<agg::pixfmt_rgb24>(self, "RGB");
break;
case agg::pix_format_bgr24:
self->draw = new draw_adaptor<agg::pixfmt_bgr24>(self, "BGR");
break;
default:
self->draw = new draw_adaptor<agg::pixfmt_rgba32>(self, "RGBA");
break;
}
}
const char *draw_doc = "Creates a drawing interface object.\n"
"\n"
"Parameters\n"
"----------\n"
"image_or_mode : PIL.Image.Image or str\n"
" A PIL Image or a mode string. The following modes\n"
" are supported: \"L\", \"RGB\", \"RGBA\", \"BGR\", \"BGRA\".\n"
"size : tuple\n"
" If a mode string was given, this argument gives the image size\n"
" as a 2-element tuple.\n"
"color\n"
" An optional background color specifier.\n"
" If a mode string was given, this is used to initialize the image memory.\n"
" If omitted, it defaults to white with full alpha.\n"
"\n"
"Examples\n"
"--------\n"
"\n"
" >>> d = aggdraw.Draw(im)\n"
" >>> d = aggdraw.Draw(\"RGB\", (800, 600), \"white\")\n";
static PyObject*
draw_new(PyObject* self_, PyObject* args)
{
char buffer[10];
int ok;
PyObject* image;
char* mode;
int xsize, ysize;
PyObject* background = NULL;
if (PyArg_ParseTuple(args, "O:Draw", &image)) {
/* get mode (use a local buffer to avoid GC issues) */
PyObject* mode_obj = PyObject_GetAttrString(image, "mode");
if (!mode_obj)
return NULL;
if (PyBytes_Check(mode_obj)) {
strncpy(buffer, PyBytes_AS_STRING(mode_obj), sizeof buffer);
buffer[sizeof(buffer)-1] = '\0'; /* to be on the safe side */
mode = buffer;
} else if (PyUnicode_Check(mode_obj)) {
PyObject* ascii_mode = PyUnicode_AsASCIIString(mode_obj);
if (ascii_mode == NULL) {
mode = NULL;
} else {
strncpy(buffer, PyBytes_AsString(ascii_mode), sizeof buffer);
buffer[sizeof(buffer)-1] = '\0'; /* to be on the safe side */
mode = buffer;
Py_XDECREF(ascii_mode);
}
} else
mode = NULL;
Py_DECREF(mode_obj);
if (!mode) {
PyErr_SetString(
PyExc_TypeError,
"bad 'mode' attribute (expected string)"
);
return NULL;
}
PyObject* size_obj = PyObject_GetAttrString(image, "size");
if (!size_obj)
return NULL;
if (PyTuple_Check(size_obj))
ok = PyArg_ParseTuple(size_obj, "ii", &xsize, &ysize);
else {
PyErr_SetString(
PyExc_TypeError,
"bad 'size' attribute (expected 2-tuple)"
);
ok = 0;
}
Py_DECREF(size_obj);
if (!ok)
return NULL;
} else {
PyErr_Clear();
if (!PyArg_ParseTuple(args, "s(ii)|O:Draw",
&mode, &xsize, &ysize, &background))
return NULL;
image = NULL;
}
DrawObject* self = PyObject_NEW(DrawObject, &DrawType);
if (self == NULL)
return NULL;
int stride;
if (!strcmp(mode, "L")) {
self->mode = agg::pix_format_gray8;
stride = xsize;
} else if (!strcmp(mode, "RGB")) {
self->mode = agg::pix_format_rgb24;
stride = xsize * 3;
} else if (!strcmp(mode, "BGR")) {
self->mode = agg::pix_format_bgr24;
stride = xsize * 3;
} else if (!strcmp(mode, "RGBA")) {
self->mode = agg::pix_format_rgba32;
stride = xsize * 4;
} else if (!strcmp(mode, "BGRA")) {
self->mode = agg::pix_format_bgra32;
stride = xsize * 4;
} else {
PyErr_SetString(PyExc_ValueError, "bad mode");
PyObject_DEL(self);
return NULL;
}
self->buffer_size = ysize * stride;
self->buffer_data = new unsigned char[self->buffer_size];
Py_XINCREF(background);
self->background = background;
clear(self, background);
self->buffer = new agg::rendering_buffer(
self->buffer_data, xsize, ysize, stride
);
self->xsize = xsize;
self->ysize = ysize;
self->transform = NULL;
self->image = image;
if (image) {
PyObject* buffer = PyObject_CallMethod(image, NON_CONST_MAYBE("tobytes"), NULL);
if (!buffer)
return NULL; /* FIXME: release resources */
if (!PyBytes_Check(buffer)) {
PyErr_SetString(
PyExc_TypeError,
"bad 'tobytes' return value (expected string)"
);
Py_DECREF(buffer);
return NULL;
}
char* data = PyBytes_AS_STRING(buffer);
int data_size = PyBytes_GET_SIZE(buffer);
if (data_size >= self->buffer_size)
memcpy(self->buffer_data, data, self->buffer_size);
else {
PyErr_SetString(PyExc_ValueError, "not enough data");
Py_DECREF(buffer);
return NULL; /* FIXME: release resources */
}
Py_INCREF(image); /* hang on to this image */
Py_DECREF(buffer);
}
draw_setup(self);
#if defined(WIN32)
self->dc = NULL;
#endif
return (PyObject*) self;
}
#if defined(WIN32)
const char *dib_doc = "Creates a drawing interface object that can be copied to a window.\n"
"\n"
"This class is only available on Windows platforms.\n"
"This object has the same methods as :class:`Draw`,\n"
"plus an expose method that copies the contents to a given window.\n"
"\n"
".. versionadded:: 1.2\n"
"\n"
"Parameters\n"
"----------\n"
"mode : str\n"
" A mode string. Currently this must be \"RGB\".\n"
"size : tuple\n"
" The image size as a 2-element tuple.\n"
"color\n"
" An optional background color specifier.\n"
" If a mode string was given, this is used to initialize the image memory.\n"
" If omitted, it defaults to white with full alpha.\n"
"\n"
"Example\n"
"-------\n"
"\n"
" >>> d = aggdraw.Dib(\"RGB\", (800, 600), \"white\")\n"
" >>> # other operations\n"
" >>> d.expose(hwnd=window)\n";
static PyObject*
draw_dib(PyObject* self_, PyObject* args)
{
char* mode;
int xsize, ysize;
PyObject* background = NULL;
if (!PyArg_ParseTuple(args, "s(ii)|O:Dib", &mode, &xsize, &ysize, &background))
return NULL;
DrawObject* self = PyObject_NEW(DrawObject, &DrawType);
if (self == NULL)
return NULL;
if (strcmp(mode, "RGB")) {
PyErr_SetString(PyExc_ValueError, "bad mode");
PyObject_DEL(self);
return NULL;
}
int stride = xsize * 3;
self->mode = agg::pix_format_bgr24;
memset(&self->info, 0, sizeof(BITMAPINFOHEADER));
self->info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
self->info.bmiHeader.biWidth = xsize;
self->info.bmiHeader.biHeight = ysize;
self->info.bmiHeader.biPlanes = 1;
self->info.bmiHeader.biBitCount = strlen(mode)*8;
self->info.bmiHeader.biCompression = BI_RGB;
/* Create DIB */
self->dc = CreateCompatibleDC(NULL);
if (!self->dc) {
/* FIXME: cleanup */
PyErr_NoMemory();
return NULL;
}
void* bits;
self->bitmap = CreateDIBSection(
self->dc, &self->info, DIB_RGB_COLORS, &bits, NULL, 0
);
if (!self->bitmap) {
/* FIXME: cleanup */
PyErr_NoMemory();
return NULL;
}
/* Bind the DIB to the device context */
self->old_bitmap = SelectObject(self->dc, self->bitmap);
self->buffer_size = ysize * stride;
self->buffer_data = (unsigned char*) bits;
Py_XINCREF(background);
self->background = background;
clear(self, background);
self->buffer = new agg::rendering_buffer(
self->buffer_data, xsize, ysize, -stride
);
self->xsize = xsize;
self->ysize = ysize;
self->transform = NULL;
self->image = NULL;
draw_setup(self);
return (PyObject*) self;
}
#endif
struct PointF {
float X;
float Y;
};
#ifdef IS_PY3K
#define GETFLOAT(op) \
(PyLong_Check(op) ? (float) PyLong_AS_LONG((op)) :\
PyFloat_Check(op) ? (float) PyFloat_AS_DOUBLE((op)) :\
(float) PyFloat_AsDouble(op))
#else
#define GETFLOAT(op) \
(PyInt_Check(op) ? (float) PyInt_AS_LONG((op)) :\
PyFloat_Check(op) ? (float) PyFloat_AS_DOUBLE((op)) :\
(float) PyFloat_AsDouble(op))
#endif
static PointF*
getpoints(PyObject* xyIn, int* count)
{
PointF *xy;
int i, n;
/* FIXME: use local buffer (provided by caller) for short
sequences */
if (!PySequence_Check(xyIn)) {
PyErr_SetString(PyExc_TypeError, "argument must be a sequence");
return NULL;
}
n = PyObject_Length(xyIn);
if (PyErr_Occurred())
return NULL;
if (n & 1) {
PyErr_SetString(PyExc_TypeError,
"expected even number of coordinates");
return NULL;
}
n /= 2;
xy = new PointF[n+1];
if (!xy) {
PyErr_NoMemory();
*count = -1;
return NULL;
}
if (PyList_Check(xyIn))
for (i = 0; i < n; i++) {
xy[i].X = GETFLOAT(PyList_GET_ITEM(xyIn, i+i));
xy[i].Y = GETFLOAT(PyList_GET_ITEM(xyIn, i+i+1));
}
else if (PyTuple_Check(xyIn))
for (i = 0; i < n; i++) {
xy[i].X = GETFLOAT(PyTuple_GET_ITEM(xyIn, i+i));
xy[i].Y = GETFLOAT(PyTuple_GET_ITEM(xyIn, i+i+1));
}
else
for (i = 0; i < n; i++) {
PyObject *op;
op = PySequence_GetItem(xyIn, i+i);
xy[i].X = GETFLOAT(op);
Py_DECREF(op);
op = PySequence_GetItem(xyIn, i+i+1);
xy[i].Y = GETFLOAT(op);
Py_DECREF(op);
}
PyErr_Clear();
*count = n;
return xy;
}
static agg::rgba8
getcolor(PyObject* color, int opacity)
{
#ifdef IS_PY3K
if (PyLong_Check(color)) {
int ink = PyLong_AsLong(color);
return agg::rgba8(ink, ink, ink, opacity);
}
#else
if (PyInt_Check(color)) {
int ink = PyInt_AsLong(color);
return agg::rgba8(ink, ink, ink, opacity);
}
#endif
char buffer[10];
char* ink = NULL;
if (PyUnicode_Check(color)) {
PyObject* ascii_color = PyUnicode_AsASCIIString(color);
if (ascii_color == NULL) {
ink = NULL;
} else {
strncpy(buffer, PyBytes_AsString(ascii_color), sizeof buffer);
buffer[sizeof(buffer)-1] = '\0'; /* to be on the safe side */
ink = buffer;
Py_XDECREF(ascii_color);
}
} else if (PyBytes_Check(color)) {
ink = PyBytes_AsString(color);
}
/* hex colors */
if (ink && ink[0] == '#' && strlen(ink) == 7) {
int i = strtol(ink+1, NULL, 16); /* FIXME: rough parsing */
return agg::rgba8((i>>16)&255,(i>>8)&255,i&255,opacity);
}
int red, green, blue, alpha = opacity;
if (PyArg_ParseTuple(color, "iii|i", &red, &green, &blue, &alpha))
return agg::rgba8(red, green, blue, alpha);
PyErr_Clear();
/* unknown color: pass it to the Python layer */
if (aggdraw_getcolor_obj) {
PyObject* result;
result = PyObject_CallFunction(aggdraw_getcolor_obj, NON_CONST_MAYBE("O"), color);
if (result) {
int ok = PyArg_ParseTuple(result, "iii", &red, &green, &blue);
Py_DECREF(result);
if (ok)
return agg::rgba8(red, green, blue, opacity);
}
PyErr_Clear();
}
/* check for well-known color names (HTML) */
if (PyUnicode_Check(color) || PyBytes_Check(color)) {
if (!strcmp(ink, "aqua"))
return agg::rgba8(0x00,0xFF,0xFF,opacity);
if (!strcmp(ink, "black"))
return agg::rgba8(0x00,0x00,0x00,opacity);