-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathpostscriptlight.c
6235 lines (5546 loc) · 252 KB
/
postscriptlight.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
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
/*--------------------------------------------------------------------
*
* Copyright (c) 2009-2025 by the GMT Team (https://www.generic-mapping-tools.org/team.html)
* See LICENSE.TXT file for copying and redistribution conditions.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; version 3 or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* Contact info: www.generic-mapping-tools.org
*--------------------------------------------------------------------*/
/* PSL: PostScript Light
*
* PSL is a library of plot functions that create PostScript.
* All the routines write their output to the same plotting file,
* which can be dumped to a Postscript output device (laserwriters).
* PSL can handle and mix text, line-drawings, and bit-map graphics
* in both black/white and color. Colors are specified with r,g,b
* values in the range 0-1.
*
* PSL conforms to the Encapsulated PostScript Files Specification V 3.0.
*
* C considerations:
* Include postscriptlight.h in your program.
* All floating point data are assumed to be of type double.
* All integer data are assumed to be of type long.
*
* FORTRAN considerations:
* All floating point data are assumed to be DOUBLE PRECISION
* All integer data are assumed to be a long INTEGER, i.e. INTEGER*8
*
* When passing (from FORTRAN to C) a fixed-length character variable which has
* blanks at the end, append '\0' (null character) after the last non-blank
* character. This is so that C will know where the character string ends.
* It is NOT sufficient to pass, for example, "string(1:string_length)".
*
* List of API functions:
*
* PSL_beginaxes
* PSL_beginclipping : Clips plot outside the specified polygon
* PSL_beginlayer : Place begin object group DSC comment.
* PSL_beginplot : Initialize parameters for a new plot.
* PSL_beginsession : Creates a new PSL session
* PSL_copy : Writes the given string as is to the PS output
* PSL_endaxes : Turns off mapping of user coordinates to PS units
* PSL_endclipping : Restores previous clipping path
* PSL_endlayer : Place end object group DSC comment.
* PSL_endplot : Close plotfile
* PSL_endsession : Terminates the PSL session
* PSL_getplot : Return string with entire PS code
* PSL_plotarc : Plots a circular arc
* PSL_plotaxis : Plots an axis with tickmarks and annotation/label
* PSL_plotbitimage : Plots a 1-bit image or imagemask
* PSL_plotcolorimage : Plots a 24-bit 2-D image using the colorimage operator
* PSL_plotepsimage : Inserts EPS image
* PSL_plotline : Plots a line
* PSL_plotparagraph : Plots a text paragraph
* PSL_plotparagraphbox : Plots a box beneath a text paragraph
* PSL_plotpoint : Absolute or relative move to new position (pen up or down)
* PSL_plotpolygon : Creates a polygon and optionally fills it
* PSL_plotsegment : Plots a 2-point straight line segment
* PSL_plotsymbol : Plots a geometric symbol and [optionally] fills it
* PSL_plottext : Plots textstring
* PSL_plottextbox : Draw a filled box around a textstring
* PSL_plottextline : Place labels along paths (straight or curved), set clip path, draw line
* PSL_loadeps : Read EPS file into string
* PSL_command : Writes a given PostScript statement to the plot file
* PSL_comment : Writes a comment statement to the plot file
* PSL_makecolor : Returns string with PostScript command to set a new color
* PSL_makepen : Returns string with PostScript command to set a new pen
* PSL_setcolor : Sets the pen color or pattern
* PSL_setcurrentpoint : Sets the current point
* PSL_setdefaults : Change several PSL session default values
* PSL_setdash : Specify pattern for dashed line
* PSL_setfill : Sets the fill color or pattern
* PSL_setfont : Changes current font and possibly re-encodes it to current encoding
* PSL_setformat : Changes # of decimals used in color and gray specs [3]
* PSL_setlinecap : Changes the line cap setting
* PSL_setlinejoin : Changes the line join setting
* PSL_setlinewidth : Sets a new linewidth
* PSL_setmiterlimit : Changes the miter limit setting for joins
* PSL_setimage : Sets up an image pattern fill in PS
* PSL_setorigin : Translates/rotates the coordinate system
* PSL_setparagraph : Sets parameters used to typeset text paragraphs
* PSL_settransparencymode : Set a new mode for how transparency is understoody
* PSL_settransparency : Set a new transparency
* PSL_defpen : Encodes a pen with attributes by name in the PS output
* PSL_definteger : Encodes an integer by name in the PS output
* PSL_defpoints : Encodes a pointsize by name in the PS output
* PSL_defcolor : Encodes a rgb color by name in the PS output
* PSL_deftextdim : Sets variables for text height and width in the PS output
* PSL_defunits: : Encodes a dimension by name in the PS output
*
* For information about usage, syntax etc, see the postscriptlight documentation
*
* Authors: Paul Wessel, Dept. of Geology and Geophysics, SOEST, U Hawaii
* Remko Scharroo, EUMETSAT, Darmstadt, Germany
* Date: 13-OCT-2017
* Version: 6.0 [64-bit enabled API edition, decoupled from GMT]
*
* Thanks to J. Goff and L. Parkes for their contributions to an earlier version.
*
*/
/*--------------------------------------------------------------------
* SYSTEM HEADER FILES
*--------------------------------------------------------------------*/
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <stdbool.h>
#include <inttypes.h> /* Exact-width integer types */
#include "postscriptlight.h"
#ifdef HAVE_CTYPE_H_
# include <ctype.h>
#endif
#ifdef HAVE_ASSERT_H_
# include <assert.h>
#else
# define assert(e) ((void)0)
#endif
#ifdef HAVE_UNISTD_H_
# include <unistd.h>
#endif
#ifdef __CYGWIN__ /* See http://gmt.soest.hawaii.edu/boards/1/topics/5428 */
#ifdef __x86_64
#define lrint(x) ((long int)(int)lrint(x))
#endif
#endif
/*
* Windows headers
*/
#ifdef HAVE_IO_H_
# include <io.h>
#endif
#ifdef HAVE_PROCESS_H_
# include <process.h>
#endif
#ifdef HAVE_ZLIB
# include <zlib.h>
#endif
#ifndef PATH_MAX
# define PATH_MAX 1024
#endif
/* Size prefixes for printf/scanf for size_t and ptrdiff_t */
#ifdef _MSC_VER
# define PRIuS "Iu" /* printf size_t */
#else
# define PRIuS "zu" /* printf size_t */
#endif
#if _WIN32
#include <fcntl.h> /* for _O_TEXT and _O_BINARY */
#endif
/* Define bswap32 */
#undef bswap32
#ifdef HAVE___BUILTIN_BSWAP32
# define bswap32 __builtin_bswap32
#elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
# define bswap32 gnuc_bswap32
static inline uint32_t inline_bswap32 (uint32_t x) {
return
(((x & 0xFF000000U) >> 24) |
((x & 0x00FF0000U) >> 8) |
((x & 0x0000FF00U) << 8) |
((x & 0x000000FFU) << 24));
}
static inline uint32_t gnuc_bswap32(uint32_t x) {
if (__builtin_constant_p(x))
x = inline_bswap32(x);
else
__asm__("bswap %0" : "+r" (x));
return x;
}
#elif defined HAVE__BYTESWAP_ULONG /* HAVE___BUILTIN_BSWAP32 */
# define bswap32 _byteswap_ulong
#else /* HAVE___BUILTIN_BSWAP32 */
static inline uint32_t inline_bswap32 (uint32_t x) {
return
(((x & 0xFF000000U) >> 24) |
((x & 0x00FF0000U) >> 8) |
((x & 0x0000FF00U) << 8) |
((x & 0x000000FFU) << 24));
}
# define bswap32 inline_bswap32
#endif /* HAVE___BUILTIN_BSWAP32 */
#define PSL_M_unused(x) (void)(x)
/* ISO Font encodings. Ensure that the order of PSL_ISO_names matches order of includes below */
static char *PSL_ISO_name[] = {
"PSL_Standard",
"PSL_Standard+",
"PSL_ISOLatin1",
"PSL_ISOLatin1+",
"PSL_ISO-8859-1",
"PSL_ISO-8859-2",
"PSL_ISO-8859-3",
"PSL_ISO-8859-4",
"PSL_ISO-8859-5",
"PSL_ISO-8859-6",
"PSL_ISO-8859-7",
"PSL_ISO-8859-8",
"PSL_ISO-8859-9",
"PSL_ISO-8859-10",
"PSL_ISO-8859-11",
"PSL_ISO-8859-13",
"PSL_ISO-8859-14",
"PSL_ISO-8859-15",
"PSL_ISO-8859-16",
NULL
};
static char *PSL_ISO_encoding[] = {
#include "PSL_Standard.h"
#include "PSL_Standard+.h"
#include "PSL_ISOLatin1.h"
#include "PSL_ISOLatin1+.h"
#include "PSL_ISO-8859-1.h"
#include "PSL_ISO-8859-2.h"
#include "PSL_ISO-8859-3.h"
#include "PSL_ISO-8859-4.h"
#include "PSL_ISO-8859-5.h"
#include "PSL_ISO-8859-6.h"
#include "PSL_ISO-8859-7.h"
#include "PSL_ISO-8859-8.h"
#include "PSL_ISO-8859-9.h"
#include "PSL_ISO-8859-10.h"
#include "PSL_ISO-8859-11.h"
#include "PSL_ISO-8859-13.h"
#include "PSL_ISO-8859-14.h"
#include "PSL_ISO-8859-15.h"
#include "PSL_ISO-8859-16.h"
NULL
};
/* Include the 90 hardwired hachure patterns */
#include "PSL_patterns.h"
/* Listing of "Standard" 35 PostScript fonts found on most PS printers
* plus the 4 Japanese fonts we have supported since GMT 3.
* The fontheight is the height of A for unit fontsize. */
#define PSL_N_STANDARD_FONTS 39
static struct PSL_FONT PSL_standard_fonts[PSL_N_STANDARD_FONTS] = {
#include "standard_adobe_fonts.h"
};
/*--------------------------------------------------------------------
* STANDARD CONSTANTS MACRO DEFINITIONS
*--------------------------------------------------------------------*/
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef R2D
#define R2D (180.0/M_PI)
#endif
#ifndef D2R
#define D2R (M_PI/180.0)
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880
#endif
#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef MAX
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#endif
/* GMT normally gets these macros from unistd.h */
#ifndef HAVE_UNISTD_H_
# define R_OK 4
# define W_OK 2
# ifdef WIN32
# define X_OK R_OK /* X_OK == 1 crashes on Windows */
# else
# define X_OK 1
# endif
# define F_OK 0
#endif /* !HAVE_UNISTD_H_ */
/* access is usually in unistd.h; we use a macro here
* since the same function under WIN32 is prefixed with _
* and defined in io.h */
#if defined HAVE__ACCESS && !defined HAVE_ACCESS
# define access _access
#endif
#if defined HAVE_STRTOK_S && !defined HAVE_STRTOK_R
# define strtok_r strtok_s
#elif !defined HAVE_STRTOK_R
/* define custom function */
#endif
/* getpid is usually in unistd.h; we use a macro here
* since the same function under WIN32 is prefixed with _
* and defined in process.h */
#if defined HAVE__GETPID && !defined HAVE_GETPID
# define getpid _getpid
#endif
/*--------------------------------------------------------------------
* PSL CONSTANTS MACRO DEFINITIONS
*--------------------------------------------------------------------*/
#define PS_LANGUAGE_LEVEL 2
#define PSL_Version "5.0"
#define PSL_SMALL 1.0e-10
#define PSL_PAGE_HEIGHT_IN_PTS 842 /* A4 height */
#define PSL_PEN_LEN 128 /* Style length string */
#define PSL_SUBSUP_SIZE 0.7 /* Relative size of sub/sup-script to normal size */
#define PSL_SCAPS_SIZE 0.85 /* Relative size of small caps to normal size */
#define PSL_SUB_DOWN 0.25 /* Baseline shift down in font size for subscript */
#define PSL_SUP_UP_LC 0.35 /* Baseline shift up in font size for superscript after lowercase letter */
#define PSL_SUP_UP_UC 0.35 /* Baseline shift up in font size for superscript after uppercase letter */
#define PSL_ASCII_ES 27 /* ASCII code for escape (used to prevent +? strings in plain text from being seen as modifiers) */
#if 0
/* These are potential revisions to some of the settings above but remains to be tested */
#define PSL_SUBSUP_SIZE 0.58 /* Relative size of sub/sup-script to normal size */
#define PSL_SCAPS_SIZE 0.80 /* Relative size of small caps to normal size */
#define PSL_SUB_DOWN 0.25 /* Baseline shift down in font size for subscript */
#define PSL_SUP_UP_LC 0.35 /* Baseline shift up in font size for superscript after lowercase letter */
#define PSL_SUP_UP_UC 0.45 /* Baseline shift up in font size for superscript after uppercase letter */
#define PSL_SUBSUP_SIZE 0.58 /* Relative size of sub/sup-script to normal size */
#define PSL_SCAPS_SIZE 0.80 /* Relative size of small caps to normal size */
#define PSL_SUB_DOWN 0.33 /* Baseline shift down in font size for subscript */
#define PSL_SUP_UP 0.33 /* Baseline shift up in font size for superscript */
#endif
/*--------------------------------------------------------------------
* PSL FUNCTION MACRO DEFINITIONS
*--------------------------------------------------------------------*/
#define PSL_s255(s) (s * 255.0) /* Conversion from 0-1 to 0-255 range */
#define PSL_u255(s) ((unsigned char)rint(PSL_s255(s))) /* Conversion from 0-1 to 0-255 range */
#define PSL_t255(t) PSL_u255(t[0]),PSL_u255(t[1]),PSL_u255(t[2]) /* ... same for triplet */
#define PSL_q255(q) PSL_u255(q[0]),PSL_u255(q[1]),PSL_u255(q[2]),PSL_u255(q[3]) /* ... same for quadruplet */
#define PSL_YIQ(rgb) (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) /* How B/W TV's convert RGB to Gray */
#define PSL_eq(a,b) (fabs((a)-(b)) < PSL_SMALL) /* If two color component are ~identical */
#define PSL_is_gray(rgb) (PSL_eq(rgb[0],rgb[1]) && PSL_eq(rgb[1],rgb[2])) /* If the rgb is a color and not gray */
#define PSL_same_rgb(a,b) (PSL_eq(a[0],b[0]) && PSL_eq(a[1],b[1]) && PSL_eq(a[2],b[2]) && PSL_eq(a[3],b[3])) /* If two colors are ~identical */
#define PSL_rgb_copy(a,b) memcpy((void*)a,(void*)b,4*sizeof(double)); /* Copy RGB[T] triplets: a = b */
#define PSL_memory(C,ptr,n,type) (type*)psl_memory(C,(void*)ptr,(size_t)(n),sizeof(type)) /* Easier macro for psl_memory */
/* Special macros and structure for PSL_plotparagraph */
#define PSL_NO_SPACE 0
#define PSL_ONE_SPACE 1
#define PSL_COMPOSITE_1 8
#define PSL_COMPOSITE_2 16
#define PSL_COMPOSITE_2_FNT 64
#define PSL_SYMBOL_FONT 12
#define PSL_CHUNK 2048
#define PSL_CLOSE_INTERIOR 16
/* Indices for use with PSL->current.sup_up[] */
#define PSL_LC 0
#define PSL_UC 1
/* Arguments for psl_convert_path */
#define PSL_SHORTEN_PATH 0 /* Will apply one of two shortening algorithm to the integer PSL coordinates */
#define PSL_CONVERT_PATH 1 /* Will only convert to PSL integer coordinates but no shortening takes place */
struct PSL_WORD { /* Used for type-setting text */
int font_no;
int flag;
int index;
int baseshift;
int fontsize;
double rgb[4];
char *txt;
};
struct PSL_COLOR {
double rgb[4]; /* r/g/b plus alpha (PDF only) */
};
/* Special macros and structure for color(sic) maps-> */
#define PSL_INDEX_BITS 8 /* PostScript indices may be 12 bit */
/* But we only do 8 bits for now. */
#define PSL_MAX_COLORS (1<<PSL_INDEX_BITS)
typedef struct
{
size_t ncolors;
unsigned char colors[PSL_MAX_COLORS][3];
} *psl_colormap_t;
typedef struct
{
unsigned char *buffer;
psl_colormap_t colormap;
} *psl_indexed_image_t;
typedef struct {
size_t nbytes;
int depth;
unsigned char *buffer;
} *psl_byte_stream_t;
/* These are used when the PDF pdfmark or Ghostscript extensions for transparency is used:
* Adobe: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdfmarkReference_v9.pdf
* Ghostscript: https://www.ghostscript.com/doc/current/Language.htm#Transparency
*
* From gs 9.53 their transparency model takes two transparencies (stroke and fill) while before
* it only took one. The pdfmark took two but we simply duplicated it since GMT itself only dealt
* with one transparency for both. From GMT 6.2.0 we will allow these two transparencies to be set
* individually if the user so selects. Note: We do not support any of the soft masks/shapes stuff.
*/
#define N_PDF_TRANSPARENCY_MODES 16
static const char *PDF_transparency_modes[N_PDF_TRANSPARENCY_MODES] = {
"Color", "ColorBurn", "ColorDodge", "Darken",
"Difference", "Exclusion", "HardLight", "Hue",
"Lighten", "Luminosity", "Multiply", "Normal",
"Overlay", "Saturation", "SoftLight", "Screen"
};
#ifdef WIN32
#ifndef HAVE_STRSEP
/* Copyright (C) 2004, 2007, 2009-2012 Free Software Foundation, Inc.
Written by Yoann Vandoorselaere <[email protected]>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
char *strsep (char **stringp, const char *delim) {
char *start = *stringp;
char *ptr;
if (start == NULL)
return NULL;
/* Optimize the case of no delimiters. */
if (delim[0] == '\0') {
*stringp = NULL;
return start;
}
/* Optimize the case of one delimiter. */
if (delim[1] == '\0')
ptr = strchr (start, delim[0]);
else
/* The general case. */
ptr = strpbrk (start, delim);
if (ptr == NULL) {
*stringp = NULL;
return start;
}
*ptr = '\0';
*stringp = ptr + 1;
return start;
}
#endif /* ifndef HAVE_STRSEP */
/* SUpport for differences between UNIX and DOS paths */
static void psl_strlshift (char *string, size_t n) {
/* Left shift a string by n characters */
size_t len;
assert (string != NULL); /* NULL pointer */
if ((len = strlen(string)) <= n ) {
/* String shorter than shift width */
*string = '\0'; /* Truncate entire string */
return;
}
/* Move entire string back */
memmove(string, string + n, len + 1);
}
static void psl_strrepc (char *string, int c, int r) {
/* Replaces all occurrences of c in the string with r */
assert (string != NULL); /* NULL pointer */
do {
if (*string == c)
*string = (char)r;
} while (*(++string)); /* repeat until \0 reached */
}
/* Turn '/c/dir/...' paths into 'c:/dir/...'
* Must do it in a loop since dir may be several ';'-separated dirs */
static void psl_dos_path_fix (char *dir) {
size_t n, k;
if (!dir || (n = strlen (dir)) < 2U)
/* Given NULL or too short dir to work */
return;
if (!strncmp (dir, "/cygdrive/", 10U))
/* May happen for example when Cygwin sets GMT_SHAREDIR */
psl_strlshift (dir, 9); /* Chop '/cygdrive' */
/* Replace dumb backslashes with slashes */
psl_strrepc (dir, '\\', '/');
/* If dir begins with '/' and is 2 long, as in '/c', replace with 'c:' */
if (n == 2U && dir[0] == '/') {
dir[0] = dir[1];
dir[1] = ':';
return;
}
/* If dir is longer than 2 and, e.g., '/c/', replace with 'c:/' */
if (n > 2U && dir[0] == '/' && dir[2] == '/' && isalpha ((int)dir[1])) {
dir[0] = dir[1];
dir[1] = ':';
}
/* Do the same with dirs separated by ';' but do not replace '/c/j/...' with 'c:j:/...' */
for (k = 4; k < n-2; k++) {
if ( (dir[k-1] == ';' && dir[k] == '/' && dir[k+2] == '/' && isalpha ((int)dir[k+1])) ) {
dir[k] = dir[k+1];
dir[k+1] = ':';
}
}
/* Replace ...:C:/... by ...;C:/... as that was a multi-path set by an e.g. bash shell (msys or cygwin) */
for (k = 4; k < n-2; k++) {
if ((dir[k-1] == ':' && dir[k+1] == ':' && dir[k+2] == '/' && isalpha ((int)dir[k])) )
dir[k-1] = ';';
else if ((dir[k-1] == ':' && dir[k] == '/' && dir[k+2] == '/' && isalpha ((int)dir[k+1])) ) {
/* The form ...:/C/... will become ...;C:/... */
dir[k-1] = ';';
dir[k] = dir[k+1];
dir[k+1] = ':';
}
}
}
#else
# define psl_dos_path_fix(e) ((void)0) /* dummy function */
#endif
/* ----------------------------------------------------------------------
* Support functions used in PSL_* functions.
* ----------------------------------------------------------------------
*/
static void *psl_memory (struct PSL_CTRL *PSL, void *prev_addr, size_t nelem, size_t size) {
/* Multi-functional memory allocation subroutine.
If prev_addr is NULL, allocate new memory of nelem elements of size bytes.
Ignore when nelem == 0.
If prev_addr exists, reallocate the memory to a larger or smaller chunk of nelem elements of size bytes.
When nelem = 0, free the memory.
*/
void *tmp = NULL;
const char *m_unit[4] = {"bytes", "kb", "Mb", "Gb"};
double mem;
int k;
if (prev_addr) {
if (nelem == 0) { /* Take care of n == 0 */
PSL_free (prev_addr);
return (NULL);
}
if ((tmp = realloc ( prev_addr, nelem * size)) == NULL) {
mem = (double)(nelem * size);
k = 0;
while (mem >= 1024.0 && k < 3) mem /= 1024.0, k++;
PSL_message (PSL, PSL_MSG_ERROR, "Error: Could not reallocate more memory [%.2f %s, %" PRIuS " items of %" PRIuS " bytes]\n",
mem, m_unit[k], nelem, size);
return (NULL);
}
}
else {
if (nelem == 0) return (NULL); /* Take care of n = 0 */
if ((tmp = calloc (nelem, size)) == NULL) {
mem = (double)(nelem * size);
k = 0;
while (mem >= 1024.0 && k < 3) mem /= 1024.0, k++;
PSL_message (PSL, PSL_MSG_ERROR, "Error: Could not allocate memory [%.2f %s, %" PRIuS " items of %" PRIuS " bytes]\n",
mem, m_unit[k], nelem, size);
return (NULL);
}
}
return (tmp);
}
/* Things to do with UTF8 */
/* Try to convert UTF-8 accented characters to PostScriptLight octal codes.
* This depends on which character set we have. We will limit this to just
* Standard, Standard+, ISOILatin1, and ISOLatin1+. Of these, Standard will
* only work for some of the encoded letters while the three others should
* all be fine.
* We also handle the differences between hyphens and minus symbol.
* In ISOLatin1 the hyphen key on the keyboard results in a minus sign while
* in Standard it gives a hyphen. In GMT we want minus signs in annotations
* contours and other numerical negative values. This behavior is controlled
* by the setting in PSL_settextmode. */
static unsigned int psl_ut8_code_to_ISOLatin (char code) {
/* This is called when the previous character in a string has octal 0303 */
unsigned int kode = (unsigned char)code;
return (kode >= 0200 && kode <= 0277) ? kode += 64 : 0;
}
static void psl_fix_utf8 (struct PSL_CTRL *PSL, char *in_string) {
/* Given in_string check if UTF8 characters are present and if so replace with PSL octal codes. Assumes ISOLatin1+ */
unsigned int k, kout, use, utf8_codes = 0;
bool do_minus = (PSL->current.use_minus == PSL_TXTMODE_MINUS);
char *out_string = NULL;
if (!strncmp (PSL->init.encoding, "Standard+", 9U) && do_minus) { /* For Standard+ encoding we may need to swap leading minus values encoded as hyphen with the actual minus symbol */
for (k = 0; in_string[k]; k++) {
if ((k == 0 || in_string[k-1] != '@') && in_string[k] == 0055) /* Found a hyphen which we interpret to be a minus sign */
in_string[k] = 0224; /* Minus is octal 224 in Standard+ but not present in just Standard */
}
}
if (strncmp (PSL->init.encoding, "ISOLatin1", 9U)) return; /* Do nothing unless ISOLatin[+] */
for (k = 0; in_string[k]; k++) {
if ((unsigned char)(in_string[k]) == 0303 || (unsigned char)(in_string[k]) == 0305)
utf8_codes++; /* Count them up */
else if (k == 0 || in_string[k-1] != '@') {
if ((unsigned char)in_string[k] == 0255 && do_minus)
in_string[k] = 0055; /* Minus symbol is octal 0055 in ISOLatin1 */
else if ((unsigned char)in_string[k] == 0055 && !do_minus)
in_string[k] = 0255; /* Hyphen symbol is octal 0255 in ISOLatin1 */
}
}
if (utf8_codes == 0) return; /* Nothing to do */
out_string = PSL_memory (PSL, NULL, strlen(in_string) + 1, char); /* Get a new string of same length (extra byte for '\0') */
for (k = kout = 0; in_string[k]; k++) {
if ((unsigned char)(in_string[k]) == 0303) { /* Found octal 303 */
k++; /* Skip the control code */
if ((use = psl_ut8_code_to_ISOLatin (in_string[k]))) /* Found a 2-char utf8 combo, replace with single octal code from our table */
out_string[kout++] = use;
else { /* Not a recognized code - just output both as they were given */
out_string[kout++] = in_string[k-1];
out_string[kout++] = in_string[k];
}
}
else if ((unsigned char)(in_string[k]) == 0305) { /* Found Ydieresis, ae, AE, L&l-slash and the S,Z,s,z carons */
k++; /* Skip the control code */
switch ((unsigned char)in_string[k]) { /* These 9 chars are placed all over the table so must have individual cases */
case 0201: use = 0203; break; /* Lslash */
case 0202: use = 0213; break; /* lslash */
case 0222: use = 0200; break; /* ae */
case 0223: use = 0210; break; /* AE */
case 0240: use = 0206; break; /* Scaron */
case 0241: use = 0177; break; /* scaron */
case 0270: use = 0211; break; /* Ydieresis */
case 0275: use = 0212; break; /* Zcaron */
case 0276: use = 0037; break; /* zcaron */
default: use = 0; break; /* Not one of the recognized ones in our table */
}
if (use) /* Found a 2-char utf8 combo */
out_string[kout++] = use;
else { /* Not a recognized code - just output both as they were given */
out_string[kout++] = in_string[k-1];
out_string[kout++] = in_string[k];
}
}
else /* Just output char as was given */
out_string[kout++] = in_string[k];
}
memset (in_string, 0, strlen (in_string)); /* Set old in_string to NULL */
strncpy (in_string, out_string, strlen (out_string)); /* Overwrite old string with possibly adjusted string */
PSL_free (out_string);
}
/* This one is NOT static since needed in psimage, at least for now */
unsigned char *psl_gray_encode (struct PSL_CTRL *PSL, size_t *nbytes, unsigned char *input) {
/* Recode RGB stream as gray-scale stream */
size_t in, out, nout;
unsigned char *output = NULL;
nout = *nbytes / 3;
output = PSL_memory (PSL, NULL, nout, unsigned char);
for (in = out = 0; in < *nbytes; out++, in += 3) output[out] = (char) lrint (PSL_YIQ ((&input[in])));
*nbytes = nout;
return (output);
}
/* Define local (static) support functions called inside the public PSL functions */
static int psl_ix (struct PSL_CTRL *PSL, double x) {
/* Convert user x to PS dots */
return (PSL->internal.x0 + (int)lrint (x * PSL->internal.x2ix));
}
static int psl_iy (struct PSL_CTRL *PSL, double y) {
/* Convert user y to PS dots */
return (PSL->internal.y0 + (int)lrint (y * PSL->internal.y2iy));
}
static double psl_ix10 (struct PSL_CTRL *PSL, double x) {
/* Convert user x to PS dots with 1 decimal point */
return (PSL->internal.x0 + 0.1 *lrint (10.0 * x * PSL->internal.x2ix));
}
static double psl_iy10 (struct PSL_CTRL *PSL, double y) {
/* Convert user y to PS dots with 1 decimal point */
return (PSL->internal.y0 + 0.1 * lrint (10.0 * y * PSL->internal.y2iy));
}
static int psl_iz (struct PSL_CTRL *PSL, double z) {
/* Convert user distances to PS dots */
return ((int)lrint (z * PSL->internal.dpu));
}
static int psl_ip (struct PSL_CTRL *PSL, double p) {
/* Convert PS points to PS dots */
return ((int)lrint (p * PSL->internal.dpp));
}
static int psl_convert_path_new (struct PSL_CTRL *PSL, double *x, double *y, int n, int *ix, int *iy, int mode) {
/* Simplifies the (x,y) array by converting it to pixel coordinates (ix,iy)
* and eliminating repeating points and intermediate points along straight
* line segments. The result is the fewest points needed to draw the path
* and still look exactly like the original path. However, if mode == 1 we do
* no shortening. */
int i, k, dx, dy;
int d, db, bx, by, j, ij;
if (n < 2) return (n); /* Not a path to start with */
for (i = 0; i < n; i++) { /* Convert all coordinates to integers at current scale */
ix[i] = psl_ix (PSL, x[i]);
iy[i] = psl_iy (PSL, y[i]);
}
if (mode == PSL_CONVERT_PATH) return (n); /* No shortening */
/* Skip intermediate points that are "close" to the line between point i and point j, where
"close" is defined as less than 1 "dot" (the PostScript resolution) in either direction.
A point is always close when it coincides with one of the end points (i or j).
An intermediate point is also considered "far" when it is beyond i or j.
Algorithm requires that |dx by - bx dy| >= max(|dx|,|dy|) for points to be "far".
*/
for (i = k = 0, j = 2; j < n; j++) {
dx = ix[j] - ix[i];
dy = iy[j] - iy[i];
d = MAX(abs((int)dx),abs((int)dy));
/* We know that d can be zero. That is OK, since it will only happen when (dx,dy) = (0,0).
And in that cases all intermediate points will always be "far" */
for (ij = j - 1; ij > i; ij--) {
bx = ix[ij] - ix[i];
/* Check if the intermediate point is outside the x-range between points i and j.
In case of a vertical line, any point with a different x-coordinate is "far" */
if (dx > 0) {
if (bx < 0 || bx > dx) break;
}
else {
if (bx > 0 || bx < dx) break;
}
by = iy[ij] - iy[i];
/* Check if the intermediate point is outside the y-range between points i and j.
In case of a horizontal line, any point with a different y-coordinate is "far" */
if (dy > 0) {
if (by < 0 || by > dy) break;
}
else {
if (by > 0 || by < dy) break;
}
/* Generic case where the intermediate point is within the x- and y-range */
db = abs((int)(dx * by) - (int)(bx * dy));
if (db >= d) break; /* Point ij is "far" from line connecting i and j */
}
if (ij > i) { /* Some intermediate point failed test */
i = j - 1;
k++;
ix[k] = ix[i];
iy[k] = iy[i];
}
}
/* We have gotten to the last point. If this is a duplicate, skip it */
if (ix[k] != ix[n-1] || iy[k] != iy[n-1]) {
k++;
ix[k] = ix[n-1];
iy[k] = iy[n-1];
}
k++;
return (k);
}
static int psl_convert_path_old (struct PSL_CTRL *PSL, double *x, double *y, int n, int *ix, int *iy, int mode) {
/* Simplifies the (x,y) array by converting it to pixel coordinates (ix,iy)
* and eliminating repeating points and intermediate points along straight
* line segments. The result is the fewest points needed to draw the path
* and still look exactly like the original path. However, if mode == 1 we do
* no shortening. */
int i, k, dx, dy;
int old_dir = 0, new_dir;
double old_slope = -DBL_MAX, new_slope;
/* These seeds for old_slope and old_dir make sure that first point gets saved */
if (n < 2) return (n); /* Not a path to start with */
for (i = 0; i < n; i++) { /* Convert all coordinates to integers at current scale */
ix[i] = psl_ix (PSL, x[i]);
iy[i] = psl_iy (PSL, y[i]);
}
if (mode == PSL_CONVERT_PATH) return (n); /* No shortening */
/* The only truly unique point is the starting point; all else must show increments
* relative to the previous point */
/* First point is the anchor. We will find at least one point, unless all points are the same */
for (i = k = 0; i < n - 1; i++) {
dx = ix[i+1] - ix[i];
dy = iy[i+1] - iy[i];
if (dx == 0 && dy == 0) continue; /* Skip duplicates */
new_slope = (dx == 0) ? copysign (DBL_MAX, (double)dy) : ((double)dy) / ((double)dx);
new_dir = (dx >= 0) ? 1 : -1;
if (new_slope != old_slope || new_dir != old_dir) {
ix[k] = ix[i];
iy[k] = iy[i];
k++;
old_slope = new_slope;
old_dir = new_dir;
}
}
/* If all points are the same, we get here with k = 0, so we can exit here now with 1 point */
if (k < 1) return (1);
/* Last point (k cannot be < 1 so k-1 >= 0) */
if (ix[k-1] != ix[n-1] || iy[k-1] != iy[n-1]) { /* Do not do slope check on last point since we must end there */
ix[k] = ix[n-1];
iy[k] = iy[n-1];
k++;
}
return (k);
}
/* Addressing issue https://github.com/GenericMappingTools/gmt/issues/439 for long DCW polygons.
#define N_LENGTH_THRESHOLD 100000000 meant we only did new path but now we try 50000 as cutoff */
#define N_LENGTH_THRESHOLD 50000
static int psl_convert_path (struct PSL_CTRL *PSL, double *x, double *y, int n, int *ix, int *iy, int mode) {
if (n > N_LENGTH_THRESHOLD)
return psl_convert_path_old (PSL, x, y, n, ix, iy, mode);
else
return psl_convert_path_new (PSL, x, y, n, ix, iy, mode);
}
static int psl_forcelinewidth (struct PSL_CTRL *PSL, double linewidth) {
if (linewidth < 0.0) {
PSL_message (PSL, PSL_MSG_ERROR, "Warning: Selected linewidth is negative (%g), ignored\n", linewidth);
return (PSL_BAD_WIDTH);
}
PSL_command (PSL, "%d W\n", psl_ip (PSL, linewidth));
PSL->current.linewidth = linewidth;
return (PSL_NO_ERROR);
}
static void psl_set_real_array (struct PSL_CTRL *PSL, const char *prefix, double *array, int n) {
/* These are raw and not scaled */
int i;
PSL_command (PSL, "/PSL_%s [ ", prefix);
for (i = 0; i < n; i++) {
PSL_command (PSL, "%.2f ", array[i]);
if (((i+1)%10) == 0) PSL_command (PSL, "\n\t");
}
PSL_command (PSL, "] def\n");
}
void psl_set_int_array (struct PSL_CTRL *PSL, const char *prefix, int *array, int n) {
/* These are raw and not scaled */
int i;
PSL_command (PSL, "/PSL_%s [ ", prefix);
for (i = 0; i < n; i++) {
PSL_command (PSL, "%d ", array[i]);
if (((i+1)%10) == 0) PSL_command (PSL, "\n\t");
}
PSL_command (PSL, "] def\n");
}
void psl_set_txt_array (struct PSL_CTRL *PSL, const char *prefix, char *array[], int n) {
int i;
char *outtext = NULL;
PSL_command (PSL, "/PSL_%s [\n", prefix);
for (i = 0; i < n; i++) {
outtext = psl_prepare_text (PSL, array[i]); /* Expand escape codes and fix utf-8 characters */
PSL_command (PSL, "\t(%s)\n", outtext);
PSL_free (outtext);
}
PSL_command (PSL, "] def\n", n);
}
static void psl_set_reducedpath_arrays (struct PSL_CTRL *PSL, double *x, double *y, int npath, int *n, int *m, int *node) {
/* These are used by PSL_plottextline. We make sure there are no point pairs that would yield dx = dy = 0 (repeat point)
* at the resolution we are using (0.01 DPI units), hence a new n (possibly shorter) is returned. */
int i, j, k, p, ii, kk, this_i, this_j, last_i, last_j, i_offset = 0, k_offset = 0, n_skipped, ntot = 0, *new_n = NULL;
char *use = NULL;
if (x == NULL || y == NULL) return; /* No path */
for (p = 0; p < npath; p++) ntot += n[p]; /* Determine total number of points */
/* Since we need dx/dy from these we preprocess to avoid any nasty surprises with repeat points */
use = PSL_memory (PSL, NULL, ntot, char);
new_n = PSL_memory (PSL, NULL, npath, int);
for (p = 0; p < npath; p++) {
this_i = this_j = INT_MAX;
for (ii = j = n_skipped = k = 0; ii < n[p]; ii++) {
last_i = this_i; last_j = this_j;
i = ii + i_offset; /* Index into concatenated x,y arrays */
this_i = 100 * psl_ix (PSL, x[i]); /* Simulates the digits written by a %.2lf format */
this_j = 100 * psl_iy (PSL, y[i]);
if (this_i == last_i && this_j == last_j) /* Repeat point, skip it */
n_skipped++;
else { /* Not a repeat point, use it */
use[i] = true;
j++;
}
kk = k + k_offset; /* Index into concatenated node array */
if (k < m[p] && node[kk] == ii && n_skipped) { /* Adjust node pointer since we are removing points and upsetting the node order */
node[kk++] -= n_skipped;
k++;
}
}
new_n[p] = j;
i_offset += n[p];
k_offset += m[p];
}
/* For curved lines for text placement we use 10 times the precision in the coordinates since we will
* be taking derivatives to compute angles and thus need higher precision than integer PS coordinates */
PSL_comment (PSL, "Set concatenated coordinate arrays for line segments:\n");
PSL_command (PSL, "/PSL_path_x [ ");
for (i = k = 0; i < ntot; i++) {
if (!use[i]) continue;
PSL_command (PSL, "%g ", psl_ix10 (PSL, x[i]));
k++;
if ((k%10) == 0) PSL_command (PSL, "\n\t");
}
PSL_command (PSL, "] def\n");
PSL_command (PSL, "/PSL_path_y [ ");
for (i = k = 0; i < ntot; i++) {
if (!use[i]) continue;
PSL_command (PSL, "%g ", psl_iy10 (PSL, y[i]));
k++;
if ((k%10) == 0) PSL_command (PSL, "\n\t");
}
PSL_command (PSL, "] def\n");
PSL_comment (PSL, "Set array with number of points per line segments:\n");
psl_set_int_array (PSL, "path_n", new_n, npath);
if (k > PSL_MaxOpStack_Size) PSL_message (PSL, PSL_MSG_WARNING, "Warning: PSL array placed has %d items - may exceed gs_init.ps MaxOpStack setting [%d].\n", k, PSL_MaxOpStack_Size);
/* Free up temp arrays */