forked from Sharpie/RTikZDevice
-
Notifications
You must be signed in to change notification settings - Fork 26
/
tikzDevice.c
2420 lines (1925 loc) · 71 KB
/
tikzDevice.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
/*
* tikzDevice, (C) 2009-2011 Charlie Sharpsteen and Cameron Bracken
*
* A graphics device for R :
* A Computer Language for Statistical Data Analysis
*
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 2001-8 The R Development Core Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* http://www.r-project.org/Licenses/
*
* The C code in this project started as a fork of:
* A PicTeX Device, (C) 1996 Valerio Aimale
*
*
* "If I have seen further, it is only by standing on
* the shoulders of giants."
*
* -I. Newton
*
*/
/********************************************************************/
/*
* NOTE:
* This is the first effort of dyed-in-the-wool Fortran programmers
* to write C code. Hence the comments in this file will make many
* observations that may seem obvious or inane. There also may be a
* generous amount of snide comments concerning the syntax of the
* C language.
*/
/*
* Function prototypes are defined in here. Apparently in C
* it is absolutely necessary for function definitions to appear
* BEFORE they are called by other functions. Hence many source code
* files do not present code in the order in which that code
* is used. Using a header file with function declarations allows
* the programmer to order the code in any sequence they choose.
*/
/*
* This header also includes other header files describing functions
* provided by the R language.
*/
#include "tikzDevice.h"
// We are writing to files so we need stdio.h
#include <stdio.h>
/*
* Main entry point from the R environment, called by the R function
* tikz() to open a new TikZ graphics device.
*/
SEXP TikZ_StartDevice ( SEXP args ){
/*
* Make sure the version number of the R running this
* routine is compatible with the version number of
* the R that compiled this routine.
*/
R_GE_checkVersionOrDie(R_GE_version);
/* Declare local variabls for holding the components of the args SEXP */
const char *fileName, *colorFileName;
const char *bg, *fg;
double width, height;
Rboolean standAlone, bareBones;
const char *documentDeclaration, *packages, *footer;
double baseSize, lwdUnit;
Rboolean console, sanitize, onefile, symbolicColors;
/*
* pGEDevDesc is a variable provided by the R Graphics Engine
* that represents a graphics device to the rest of the R system.
* It contains one important componant of type pDevDesc
* which contains information specific to the implementation of
* the TikZ Device. The creation and initialization of this component
* is the main task of this routine.
*/
pGEDevDesc tikzDev;
/* Retrieve function arguments from input SEXP. */
/*
* Skip first argument. It holds the name of the R function
* that called this C routine.
*/
args = CDR(args);
/* Recover file name. */
fileName = translateChar(asChar(CAR(args)));
/* Advance to next argument stored in the args SEXP. */
args = CDR(args);
/* Recover figure dimensions. */
/* For now these are assumed to be in inches. */
width = asReal(CAR(args)); args = CDR(args);
height = asReal(CAR(args)); args = CDR(args);
onefile = asLogical(CAR(args)); args = CDR(args);
/* Recover initial background and foreground colors. */
bg = CHAR(asChar(CAR(args))); args = CDR(args);
fg = CHAR(asChar(CAR(args))); args = CDR(args);
/* Recover the base fontsize */
baseSize = asReal(CAR(args)); args = CDR(args);
/* Recover the lwd-to-pt ratio */
lwdUnit = asReal(CAR(args)); args = CDR(args);
/*
* Set the standAlone parameter which specifies if the TikZ
* pictures generated by this device should be wrapped in their
* own LaTeX Document
*/
standAlone = asLogical(CAR(args)); args = CDR(args);
/*
* Set the bareBones parameter which specifies if TikZ code
* should be output directly without wrapping it a LaTeX document
* or the tikzpicture environment.
*/
bareBones = asLogical(CAR(args)); args = CDR(args);
/* Grab the latex header and footers*/
documentDeclaration = CHAR(asChar(CAR(args))); args = CDR(args);
packages = CHAR(asChar(CAR(args))); args = CDR(args);
footer = CHAR(asChar(CAR(args))); args = CDR(args);
/*
* Should the output be sent to the R console? An null file name also
* indicates console output.
*/
console = asLogical(CAR(args)); args = CDR(args);
if ( fileName[0] == '\0' )
console = TRUE;
/*
* Should text strings passed to the plotting device be sent
* to a sanitization function- i.e. to provide automatic
* escaping of TeX special characters such as %,_,\, etc?
*/
sanitize = asLogical(CAR(args)); args = CDR(args);
/*
* See the definition of tikz_engine in tikzDevice.h
*/
int engine = asInteger(CAR(args)); args = CDR(args);
/*
* Should symbolic names be used (red instead of 1.0, 1.0, 1.0)
*/
symbolicColors = asLogical(CAR(args)); args = CDR(args);
colorFileName = translateChar(asChar(CAR(args))); args = CDR(args);
int maxSymbolicColors = asInteger(CAR(args)); args = CDR(args);
Rboolean timestamp = asLogical(CAR(args)); args = CDR(args);
Rboolean verbose = asLogical(CAR(args)); args = CDR(args);
/* Ensure there is an empty slot avaliable for a new device. */
R_CheckDeviceAvailable();
BEGIN_SUSPEND_INTERRUPTS{
/*
* The pDevDesc variable specifies the funtions and components
* that describe the specifics of this graphics device. After
* setup, this information will be incorporated into the pGEDevDesc
* variable tikzDev.
*/
pDevDesc deviceInfo;
/*
* Create the deviceInfo variable. If this operation fails,
* a 0 is returned in order to cause R to shut down due to the
* possibility of corrupted memory.
*/
if( !( deviceInfo = (pDevDesc) calloc(1, sizeof(DevDesc))) ) {
return 0;
}
/*
* Call setup routine to initialize deviceInfo and associate
* R graphics function hooks with the appropriate C routines
* in this file.
*/
if( !TikZ_Setup( deviceInfo, fileName, width, height, onefile, bg, fg, baseSize, lwdUnit,
standAlone, bareBones, documentDeclaration, packages,
footer, console, sanitize, engine, symbolicColors, colorFileName,
maxSymbolicColors, timestamp, verbose ) ){
/*
* If setup was unsuccessful, destroy the device and return
* an error message.
*/
free( deviceInfo );
error("TikZ device setup was unsuccessful!");
}
/* Create tikzDev as a Graphics Engine device using deviceInfo. */
tikzDev = GEcreateDevDesc( deviceInfo );
/*
* Register the device as an avaiable graphics device in the R
* Session. The user will now see a device labeled "tikz output"
* when running functions such as dev.list().
*/
GEaddDevice2( tikzDev, "tikz output" );
} END_SUSPEND_INTERRUPTS;
return R_NilValue;
}
/*
* This function is responsible for initializing device parameters
* contained in the variable deviceInfo. It returns a true or false
* value depending on the success of initialization operations.
*/
Rboolean TikZ_Setup(
pDevDesc deviceInfo,
const char *fileName,
double width, double height, Rboolean onefile,
const char *bg, const char *fg, double baseSize, double lwdUnit,
Rboolean standAlone, Rboolean bareBones,
const char *documentDeclaration,
const char *packages, const char *footer,
Rboolean console, Rboolean sanitize, int engine,
Rboolean symbolicColors, const char* colorFileName,
int maxSymbolicColors, Rboolean timestamp, Rboolean verbose){
/*
* Create tikzInfo, this variable contains information which is
* unique to the implementation of the TikZ Device. The deviceInfo
* variable contains a slot into which tikzInfo can be placed so that
* this information persists and is retrievable during the lifespan
* of this device.
*
* More information on the components of the deviceInfo structure,
* which is a pointer to a DevDesc variable, can be found under
* struct _DevDesc in the R header file GraphicsDevice.h
*
* tikzInfo is a structure which is defined in the file tikzDevice.h
*/
tikzDevDesc *tikzInfo;
/*
* Initialize tikzInfo, return false if this fails. A false return
* value will cause the whole device initialization routine to fail.
*/
if( !( tikzInfo = (tikzDevDesc *) malloc(sizeof(tikzDevDesc)) ) ){
return FALSE;
}
/* Copy TikZ-specific information to the tikzInfo variable. */
if ( onefile == FALSE ) {
/*
* Hopefully 10 extra digits will be enough for storing incrementing file
* numbers.
*/
tikzInfo->outFileName = calloc_x_strlen(fileName, 10);
tikzInfo->originalFileName = calloc_strcpy(fileName);
} else {
tikzInfo->outFileName = calloc_strcpy(fileName);
}
tikzInfo->outputFile= NULL;
tikzInfo->outColorFileName = NULL;
tikzInfo->originalColorFileName = calloc_strcpy(colorFileName);
tikzInfo->ncolors = 0;
tikzInfo->colorFile = NULL;
tikzInfo->maxSymbolicColors = maxSymbolicColors;
tikzInfo->colors = calloc(maxSymbolicColors, sizeof(int));
tikzInfo->excessWarningPrinted = FALSE;
tikzInfo->engine = engine;
tikzInfo->rasterFileCount = 1;
tikzInfo->pageNum = 1;
tikzInfo->lwdUnit = lwdUnit;
tikzInfo->debug = DEBUG;
tikzInfo->standAlone = standAlone;
tikzInfo->bareBones = bareBones;
tikzInfo->oldFillColor = 0;
tikzInfo->oldDrawColor = 0;
tikzInfo->stringWidthCalls = 0;
tikzInfo->documentDeclaration = calloc_strcpy(documentDeclaration);
tikzInfo->packages = calloc_strcpy(packages);
tikzInfo->footer = calloc_strcpy(footer);
tikzInfo->symbolicColors = symbolicColors;
tikzInfo->console = console;
tikzInfo->sanitize = sanitize;
tikzInfo->clipState = TIKZ_NO_CLIP;
tikzInfo->pageState = TIKZ_NO_PAGE;
tikzInfo->onefile = onefile;
tikzInfo->timestamp = timestamp;
tikzInfo->verbose = verbose;
/* initialize strings, just to be on the safe side */
strscpy(tikzInfo->drawColor, "drawColor");
strscpy(tikzInfo->fillColor, "fillColor");
/* Incorporate tikzInfo into deviceInfo. */
deviceInfo->deviceSpecific = (void *) tikzInfo;
/*
* These next statements define the capabilities of the device.
* These capabilities include:
* -Device/user interaction
* -Gamma correction
* -Clipping abilities
* -UTF8 support
* -Text justification/alignment abilities
*/
/*
* Define the gamma factor- used to adjust the luminosity of an image.
* Set to 1 since there is no gamma correction in the TikZ device. Also,
* canChangeGamma is set to FALSE to disallow user adjustment of this
* default.
*/
deviceInfo->startgamma = 1;
deviceInfo->canChangeGamma = FALSE;
/*
* canHAdj is an integer specifying the level of horizontal adjustment
* or justification provided by this device. Currently set to 1 as this
* is implemented by having the device insert /raggedleft, /raggedright
* and /centering directives.
*
* Level 2 represents support for continuous variation between left aligned
* and right aligned- this is certainly possible in TeX but would take some
* thought to implement.
*/
deviceInfo->canHAdj = 1;
/*
* useRotatedTextInContour specifies if the text function along with
* rotation parameters should be used over Hershey fonts when printing
* contour plot labels. As one of the primary goals of this device
* is to unify font choices, this value is set to true.
*/
deviceInfo->useRotatedTextInContour = TRUE;
/*
* canClip specifies whether the device implements routines for trimming
* plotting output such that it falls within a rectangular clipping area.
*/
deviceInfo->canClip = TRUE;
/*
* These next parameters speficy if the device reacts to keyboard and
* mouse events. Since this device outputs to a file, not a screen window,
* these actions are disabled.
*/
deviceInfo->canGenMouseDown = FALSE;
deviceInfo->canGenMouseMove = FALSE;
deviceInfo->canGenMouseUp = FALSE;
deviceInfo->canGenKeybd = FALSE;
/*
* This parameter specifies whether the device is set up to handle UTF8
* characters. This makes a difference in the complexity of the text
* handling functions that must be built into the device. If set to true
* both hook functions textUTF8 and strWidthUTF8 must be implemented.
* Compared to ASCII, which only has 128 character values, UTF8 has
* thousands.
*
* Version 0.6.0 of tikzDevice gained the ability to calculate metrics for
* UTF8 encoded strings and characters. Those calculations are not done here
* in the C code but implemented through the magical callback to R. On the R
* level, we determine automatically is a string contains multibyte UTF8
* characters and then use XeLaTeX. Bottom line is, even though hasTextUTF8
* is FALSE we can still print UTF8 characters and we dont need a separate
* text handling function for UTF8 characters (thank god).
*
* wantSymbolUTF8 indicates if mathematical symbols should be sent to
* the device as UTF8 characters. These can be handled in the same way as
* normal UTF8 text and so wantSymbolUTF8 is TRUE.
*/
deviceInfo->hasTextUTF8 = FALSE;
switch (tikzInfo->engine) {
case pdftex:
deviceInfo->wantSymbolUTF8 = FALSE;
break;
case xetex:
case luatex:
deviceInfo->wantSymbolUTF8 = TRUE;
break;
}
#if R_GE_version >= 9
/* Added in 2.14.0 for `dev.capabilities`. In all cases 0 means NA (unset). */
deviceInfo->haveTransparency = 2; /* 1 = no, 2 = yes */
deviceInfo->haveTransparentBg = 2; /* 1 = no, 2 = fully, 3 = semi */
deviceInfo->haveRaster = 2; /* 1 = no, 2 = yes, 3 = except for missing values */
deviceInfo->haveCapture = 1; /* 1 = no, 2 = yes */
deviceInfo->haveLocator = 1; /* 1 = no, 2 = yes */
#endif
#if R_GE_version >= 13
deviceInfo->deviceVersion = R_GE_definitions;
#endif
/*
* Initialize device parameters. These concern properties such as the
* plotting canvas size, the initial foreground and background colors and
* the initial clipping area. Other parameters related to fonts and text
* output are also included.
*/
/*
* Set canvas size. The bottom left corner is considered the origin and
* assigned the value of 0pt, 0pt. The upper right corner is assigned by
* converting the specified height and width of the device to points.
*/
deviceInfo->bottom = 0;
deviceInfo->left = 0;
deviceInfo->top = dim2dev( height );
deviceInfo->right = dim2dev( width );
/* Set default character size in pixels. */
deviceInfo->cra[0] = 0.9 * baseSize;
deviceInfo->cra[1] = 1.2 * baseSize;
/* Set initial font. */
deviceInfo->startfont = 1;
/* Set base font size. */
deviceInfo->startps = baseSize;
/*
* Apparently these are supposed to center text strings over the points at
* which they are plotted.
*
* Values cribbed from devPS.c in the R source. In paticular, setting
* `yLineBias` to 0 causes text in the margins of an x axis to recieve more
* leading that text in the margins of a y axis.
*/
deviceInfo->xCharOffset = 0.4900;
deviceInfo->yCharOffset = 0.3333;
deviceInfo->yLineBias = 0.2;
/* Specify the number of inches per pixel in the x and y directions. */
deviceInfo->ipr[0] = 1/dim2dev(1);
deviceInfo->ipr[1] = 1/dim2dev(1);
/* Set initial foreground and background colors. */
deviceInfo->startfill = R_GE_str2col( bg );
deviceInfo->startcol = R_GE_str2col( fg );
/* Set initial line type. */
deviceInfo->startlty = 0;
/*
* Connect R graphic function hooks to TikZ Routines implemented in this
* file. Each routine performs a specific function such as adding text,
* drawing a line or reporting/adjusting the status of the device.
*/
/* Utility routines. */
deviceInfo->close = TikZ_Close;
deviceInfo->newPage = TikZ_NewPage;
deviceInfo->clip = TikZ_Clip;
deviceInfo->size = TikZ_Size;
/* Text routines. */
deviceInfo->metricInfo = TikZ_MetricInfo;
deviceInfo->strWidth = TikZ_StrWidth;
deviceInfo->text = TikZ_Text;
/* Drawing routines. */
deviceInfo->line = TikZ_Line;
deviceInfo->circle = TikZ_Circle;
deviceInfo->rect = TikZ_Rectangle;
deviceInfo->polyline = TikZ_Polyline;
deviceInfo->polygon = TikZ_Polygon;
deviceInfo->path = TikZ_Path;
/*
* Raster Routines. Currently implemented as stub functions to
* avoid nasty crashes.
*/
deviceInfo->raster = TikZ_Raster;
deviceInfo->cap = TikZ_Cap;
#if R_GE_version >= 13
deviceInfo->setPattern = TikZ_setPattern;
deviceInfo->releasePattern = TikZ_releasePattern;
deviceInfo->setClipPath = TikZ_setClipPath;
deviceInfo->releaseClipPath = TikZ_releaseClipPath;
deviceInfo->setMask = TikZ_setMask;
deviceInfo->releaseMask = TikZ_releaseMask;
#endif
/* Dummy routines. These are mainly used by GUI graphics devices. */
deviceInfo->activate = TikZ_Activate;
deviceInfo->deactivate = TikZ_Deactivate;
deviceInfo->locator = TikZ_Locator;
deviceInfo->mode = TikZ_Mode;
/*
* If outputting to a single file, call TikZ_Open to create and initialize
* the output. For multiple files, each call to TikZ_NewPage will set up a
* new file.
*/
if( tikzInfo->onefile )
if( !TikZ_Open(deviceInfo) )
return FALSE;
return TRUE;
}
void TikZ_WriteColorDefinition( tikzDevDesc *tikzInfo, void (*printOut)(tikzDevDesc *tikzInfo, const char *format, ...), int color, const char* colorname, const char* colorstr )
{
debug_print_empty();
if ( strncmp(colorstr, "gray", 4) == 0 && strlen(colorstr) > 4)
{
int perc = atoi(colorstr+4);
printOut(tikzInfo,
"\\definecolor{%s}{gray}{%4.2f}\n",
colorname,
perc/100.0);
}
/* define aliased colors with RGB values */
else
printOut(tikzInfo,
"\\definecolor{%s}{RGB}{%d,%d,%d}\n",
colorname,
R_RED(color),
R_GREEN(color),
R_BLUE(color));
}
void TikZ_WriteColorDefinitions( tikzDevDesc *tikzInfo )
{
debug_print_empty();
int i;
for( i = 0; i < tikzInfo->ncolors; ++i)
{
const char* colorstr = col2name(tikzInfo->colors[i]);
if(colorstr[0] == '#')
colorstr = colorstr+1;
TikZ_WriteColorDefinition(tikzInfo, printColorOutput, tikzInfo->colors[i], colorstr, colorstr);
}
}
void TikZ_WriteColorFile(tikzDevDesc *tikzInfo)
{
debug_print_empty();
if ( tikzInfo->outColorFileName && tikzInfo->symbolicColors )
{
tikzInfo->colorFile = fopen(R_ExpandFileName(tikzInfo->outColorFileName), "w");
if( tikzInfo->colorFile)
{
TikZ_WriteColorDefinitions(tikzInfo);
fclose(tikzInfo->colorFile);
}
else
{
warning( "Color definition file could not be opened and is missing.\n" );
}
/* delete all colors used up till now */
tikzInfo->ncolors = 0;
tikzInfo->excessWarningPrinted = FALSE;
}
}
/*==============================================================================
Core Graphics Routines
Implementaion of an R Graphics Device as Defined by:
GraphicsDevice.h
==============================================================================*/
/*
* Routines for handling device state:
*
* - Open
* - Close
* - Newpage
* - Clip
* - Size
*/
Rboolean TikZ_Open( pDevDesc deviceInfo )
{
debug_print_empty();
/*
* Shortcut pointers to variables of interest. It seems like there HAS to be
* a more elegent way of accesing these...
*/
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
/* If creating multiple files, add the page number to the filename. */
if ( !tikzInfo->onefile )
snprintf(tikzInfo->outFileName,
strlen(tikzInfo->originalColorFileName)+floor(log10(tikzInfo->pageNum))+1,
tikzInfo->originalFileName,
tikzInfo->pageNum);
if( strlen(tikzInfo->originalColorFileName) > 0 )
{
tikzInfo->outColorFileName = calloc_x_strlen(tikzInfo->originalColorFileName, strlen(tikzInfo->outFileName));
/* deal with the extension */
const char *ext = strrchr(tikzInfo->outFileName, '.');
if( ext != NULL && strcmp(ext, ".tex") == 0)
{
char *fname = calloc_strcpy(tikzInfo->outFileName);
size_t extposition = ext - tikzInfo->outFileName;
fname[extposition] = '\0';
snprintf(tikzInfo->outColorFileName, strlen(tikzInfo->originalColorFileName)+strlen(tikzInfo->outFileName), tikzInfo->originalColorFileName, fname);
free(fname);
}
else
snprintf(tikzInfo->outColorFileName, strlen(tikzInfo->originalColorFileName)+strlen(tikzInfo->outFileName), tikzInfo->originalColorFileName, tikzInfo->outFileName);
}
else
tikzInfo->outColorFileName = NULL;
if ( !tikzInfo->console )
if ( !(tikzInfo->outputFile = fopen(R_ExpandFileName(tikzInfo->outFileName), "w")) )
return FALSE;
/* Print header comment */
Print_TikZ_Header( tikzInfo );
/* Header for a standalone LaTeX document*/
if ( tikzInfo->standAlone == TRUE ){
printOutput(tikzInfo,"%s",tikzInfo->documentDeclaration);
printOutput(tikzInfo,"%s",tikzInfo->packages);
printOutput(tikzInfo,"\\begin{document}\n\n");
}
return TRUE;
}
void TikZ_Close( pDevDesc deviceInfo)
{
debug_print_empty();
/* Shortcut pointers to variables of interest. */
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
if ( tikzInfo->clipState == TIKZ_FINISH_CLIP ) {
printOutput(tikzInfo, "\\end{scope}\n");
tikzInfo->clipState = TIKZ_NO_CLIP;
}
/* End the tikz environment if we're not doing a bare bones plot. */
if( tikzInfo->bareBones != TRUE && tikzInfo->pageState == TIKZ_FINISH_PAGE ) {
printOutput(tikzInfo, "\\end{tikzpicture}\n");
tikzInfo->pageState = TIKZ_NO_PAGE;
}
/* Close off the standalone document*/
if ( tikzInfo->standAlone == TRUE ) {
printOutput(tikzInfo, tikzInfo->footer);
printOutput(tikzInfo,"\n\\end{document}\n");
}
if ( tikzInfo->debug == TRUE )
printOutput(tikzInfo,
"%% Calculated string width %d times\n",
tikzInfo->stringWidthCalls);
/* Close the file and destroy the tikzInfo structure. */
if(tikzInfo->console == FALSE && tikzInfo->outputFile)
{
fclose(tikzInfo->outputFile);
tikzInfo->outputFile = NULL;
}
/* write symbolic color names to the corresponding file */
TikZ_WriteColorFile(tikzInfo);
/* Deallocate pointers */
free(tikzInfo->outFileName);
if ( !tikzInfo->onefile )
free(tikzInfo->originalFileName);
free(tikzInfo->colors);
free(tikzInfo->outColorFileName);
free(tikzInfo->originalColorFileName);
const_free(tikzInfo->documentDeclaration);
const_free(tikzInfo->packages);
const_free(tikzInfo->footer);
free(tikzInfo);
}
void TikZ_NewPage( const pGEcontext plotParams, pDevDesc deviceInfo )
{
debug_print_empty();
/* Shortcut pointers to variables of interest. */
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
if ( tikzInfo->clipState == TIKZ_FINISH_CLIP ) {
printOutput(tikzInfo, "\\end{scope}\n");
tikzInfo->clipState = TIKZ_NO_CLIP;
}
if ( tikzInfo->pageState == TIKZ_FINISH_PAGE ) {
if ( !tikzInfo->bareBones )
printOutput(tikzInfo, "\\end{tikzpicture}\n");
if ( !tikzInfo->onefile ) {
if( tikzInfo->standAlone )
printOutput(tikzInfo,"\n\\end{document}\n");
if( !tikzInfo->console )
fclose(tikzInfo->outputFile);
}
/* write symbolic color names to the corresponding file */
TikZ_WriteColorFile(tikzInfo);
}
/*
* Color definitions do not persist accross tikzpicture environments. Set the
* cached colors to "impossible" values so that the first drawing operation
* inside the next environment will trigger a re-definition of colors.
*/
tikzInfo->oldFillColor = -999;
tikzInfo->oldDrawColor = -999;
/*
* Setting this flag will cause the `TikZ_CheckState` function to emit the
* code required to begin a new `tikzpicture` enviornment. `TikZ_CheckState`
* is called by every graphics function that generates visible output.
*/
tikzInfo->pageState = TIKZ_START_PAGE;
}
void TikZ_Clip( double x0, double x1,
double y0, double y1, pDevDesc deviceInfo )
{
debug_print_empty();
/* Shortcut pointers to variables of interest. */
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
deviceInfo->clipBottom = y0;
deviceInfo->clipLeft = x0;
deviceInfo->clipTop = y1;
deviceInfo->clipRight = x1;
if ( tikzInfo->clipState == TIKZ_FINISH_CLIP )
printOutput(tikzInfo, "\\end{scope}\n");
/*
* Color definitions do not persist accross scopes. Set the cached colors to
* "impossible" values so that the first drawing operation inside the scope
* will trigger a re-definition of colors.
*/
tikzInfo->oldFillColor = -999;
tikzInfo->oldDrawColor = -999;
/*
* Setting this flag will cause the `TikZ_CheckState` function to emit the
* code required to begin a new clipping scope. `TikZ_CheckState` is called
* by every graphics function that generates visible output.
*/
tikzInfo->clipState = TIKZ_START_CLIP;
}
void TikZ_Size( double *left, double *right,
double *bottom, double *top, pDevDesc deviceInfo){
debug_print_empty();
/* Return canvas size. */
*bottom = deviceInfo->bottom;
*left = deviceInfo->left;
*top = deviceInfo->top;
*right = deviceInfo->right;
}
/*
* Routines for calculating text metrics:
*
* - MetricInfo
* - StrWidth
*/
/*
* This function is supposed to calculate character metrics (such as raised
* letters, stretched letters, ect). Currently the TikZ device does not
* perform such functions, so this function returns the default metrics
* the Quartz device uses when it can't think of anything else.
*
* The fact that this function is not implemented is the most likely cause
* for the *vertical* alignment of text strings being off. This shortcoming
* is most obvious when plot legends are created.
*
*/
void TikZ_MetricInfo(int c, const pGEcontext plotParams,
double *ascent, double *descent, double *width, pDevDesc deviceInfo ){
debug_print_empty();
/* Shortcut pointers to variables of interest. */
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
if (tikzInfo->engine == pdftex) {
/*
* PdfTeX can only deal with ASCII characters, check the character code c
* to see if it falls outside the range of printable characters which are:
* 32-126
*/
if( c < 32 || c > 126 ){
/* Non-printable character. Set metrics to zero and return. */
*ascent = 0.0;
*descent = 0.0;
*width = 0.0;
return;
}
}
// Calculate font scaling factor.
double fontScale = ScaleFont( plotParams, deviceInfo );
// Prepare to call back to R in order to retrieve character metrics.
SEXP namespace;
PROTECT( namespace = TIKZ_NAMESPACE );
// Call out to R to retrieve the latexParseCharForMetrics function.
// Note: this code will eventually call a different function that provides
// caching of the results. Right now we're directly calling the function
// that activates LaTeX.
SEXP metricFun = PROTECT(findFun(install("getLatexCharMetrics"), namespace));
SEXP RCallBack;
PROTECT( RCallBack = allocVector(LANGSXP, 8) );
// Place the function into the first slot of the SEXP.
SETCAR( RCallBack, metricFun );
// Place the character code into the second slot of the SEXP.
SETCADR( RCallBack, ScalarInteger( c ) );
SET_TAG( CDR( RCallBack ), install("charCode") );
// Pass graphics parameters cex and fontface.
SETCADDR( RCallBack, ScalarReal( fontScale ) );
SET_TAG( CDDR( RCallBack ), install("cex") );
SETCADDDR( RCallBack, ScalarInteger( plotParams->fontface ) );
SET_TAG( CDR(CDDR( RCallBack )), install("face") );
/*
* Set the TeX engine based on tikzInfo
*/
switch (tikzInfo->engine) {
case pdftex:
SETCAD4R(RCallBack, mkString("pdftex"));
break;
case xetex:
SETCAD4R(RCallBack, mkString("xetex"));
break;
case luatex:
SETCAD4R(RCallBack, mkString("luatex"));
break;
}
SET_TAG(CDDR(CDDR(RCallBack)), install("engine"));
SETCAD4R(CDR(RCallBack), mkString(tikzInfo->documentDeclaration));
SET_TAG(CDR(CDDR(CDDR(RCallBack))), install("documentDeclaration"));
SETCAD4R(CDDR(RCallBack), mkString(tikzInfo->packages));
SET_TAG(CDDR(CDDR(CDDR(RCallBack))), install("packages"));
SETCAD4R(CDR(CDDR(RCallBack)), ScalarLogical(tikzInfo->verbose));
SET_TAG(CDR(CDDR(CDDR(CDDR(RCallBack)))), install("verbose"));
SEXP RMetrics;
PROTECT( RMetrics = eval(RCallBack, namespace) );
// Recover the metrics.
*ascent = REAL(RMetrics)[0];
*descent = REAL(RMetrics)[1];
*width = REAL(RMetrics)[2];
if( tikzInfo->debug == TRUE ) {
printOutput( tikzInfo, "%% Calculated character metrics. ascent: %f, descent: %f, width: %f\n",
*ascent, *descent, *width);
}
UNPROTECT(4);
return;
}
/*
* This function is supposed to calculate the plotted with, in device raster
* units of an arbitrary string. This is perhaps the most difficult function
* that a device needs to implement. Calculating the exact with of a string
* is especially tricky because this device is designed to print characters
* in whatever font is being used in the the TeX document. The end font that
* the user decides to typeset their document in may also be unknown to the
* device. The problem is further complicated by the fact that TeX strings
* can be used directly in annotations. For example the string \textit{x}
* literaly has 10 characters but when it is actually typeset it only has
* one. Given this difficulty the function currently writes the string
* to a temporary file and calls LaTeX in order to obtain an authoratative
* measure of the string width.
*
* There is a rediculous amount of overhead involved with this process and
* the number of calls required to obtion widths for common things such as
* all the number s on a plot axes can easily add up to several seconds.
*
* However, if we do not perform string width calculation R is unable to
* properly align text in the plots R. This is something that LaTeX and
* TikZ should actually be taking care of by themselves but the current
* graphics system does not allow for this.
*
* Given that we need text strings to be aligned for good output, we are
* stuck using this inefficient hybrid system untill we think of something
* better.
*
*/
double TikZ_StrWidth( const char *str,
const pGEcontext plotParams, pDevDesc deviceInfo ){
debug_print_empty();
/* Shortcut pointers to variables of interest. */
tikzDevDesc *tikzInfo = (tikzDevDesc *) deviceInfo->deviceSpecific;
// Calculate font scaling factor.
double fontScale = ScaleFont( plotParams, deviceInfo );
/*
* New string width calculation method: call back to R
* and run the R function getLatexStrWidth.
*
* This used to be implemented as a C function, but
* the nuts and bolts were re-implemented back
* on the R side of this package. There seems to
* have been no major performance penalty associated
* with doing this.
*
* Why was it done?
*
* - Windows and Linux did not suppress the output
* of the C system call to LaTeX which resulted
* in spam and lag. In the case of Windows, a
* whole mess of CMD windows were spawned which
* eventually crashed the system.
*
* - Using R's system() call we gain a level of
* abstraction that works accross all platforms.
* We can also use functions like tempdir() to
* do the dirty work somewhere where the user
* won't have to clean it up.
*
* - If a LaTeX parser ever gets implemented, it
* will probably be easiest to implement it in
* R. If a LaTeX parser ever gets stolen from
* something like python's matplotlib, R will
* probably provide the interface. Therefore