summaryrefslogtreecommitdiff
path: root/Build/source/texk/dvipng/special.c
blob: d1f55b5b79e00853e037e816f1a0865b073c1e15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
/* special.c */

/************************************************************************

  Part of the dvipng distribution

  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/>.

  Copyright (C) 2002-2009 Jan-Åke Larsson

************************************************************************/

#include "dvipng.h"

#define SKIPSPACES(s) while(s && *s==' ' && *s!='\0') s++

/* PostScript can come as a string (headers and raw specials) or 
   a memory-mapped file (headers and included EPS figures). */

struct pscode {
  struct pscode*  next;
  char*           special;  /* complete special */
  char*           code;     /* PS string, null if a file */
  char*           filename; /* file name, null if a string */
  char*           postcode; /* post PS string */
  struct filemmap fmmap;    /* file mmap */
};

struct pscode* psheaderp=NULL; /* static, DVI-specific header list */

static void PSCodeInit(struct pscode *entry, char *special)
{
  entry->next=NULL;
  entry->special=special;
  entry->code=NULL;
  entry->filename=NULL;
  entry->postcode=NULL;
  entry->fmmap.data=NULL;
  if (special==NULL)
    return;
  if (strncmp(special,"header=",7)==0)
    entry->filename=special+7;
  else if (strncmp(special,"ps:: plotfile ",14)==0)
    entry->filename=special+14;
  else if (special[0]=='"' || special[0]=='!')
    entry->code=special+1;
  else if (strncmp(special,"ps::[begin]",11)==0)
    entry->code=special+11;
  else if (strncmp(special,"ps::[end]",9)==0)
    entry->code=special+9;
  else if (strncmp(special,"ps::",4)==0)
    entry->code=special+4;
  else if (strncmp(special,"ps:",3)==0)
    entry->code=special+3;
  else
    entry->code=special;
#ifdef DEBUG
  if (entry->code!=NULL)
    DEBUG_PRINT(DEBUG_GS,(" '%s'",entry->code));
  if (entry->filename!=NULL)
    DEBUG_PRINT(DEBUG_GS,(" {%s}",entry->filename));
  if (entry->postcode!=NULL)
    DEBUG_PRINT(DEBUG_GS,(" '%s'",entry->postcode));
#endif
}



void ClearPSHeaders(void)
{
  struct pscode *temp=psheaderp;

  while(temp!=NULL) {
    psheaderp=psheaderp->next;
    if (temp->fmmap.data!=NULL)
      UnMmapFile(&(temp->fmmap));
    free(temp);
    temp=psheaderp;
  }
}

static void writepscode(struct pscode* pscodep, FILE* psstream)
{
  while (pscodep!=NULL) {
    if (pscodep->code!=NULL) {
      fputs(pscodep->code,psstream);
      putc('\n',psstream);
      DEBUG_PRINT(DEBUG_GS,("\n  PS CODE:\t%s",pscodep->code));
    }
    if (pscodep->filename!=NULL && pscodep->fmmap.data==NULL) {
      char* filepath=
	kpse_find_file(pscodep->filename,kpse_tex_ps_header_format,false);
      if (filepath==NULL) {
	Warning("Cannot find PostScript file %s, ignored", pscodep->filename);
	page_flags |= PAGE_GAVE_WARN;
      } else if (MmapFile(filepath,&(pscodep->fmmap))) {
	Warning("PostScript file %s unusable, ignored", pscodep->filename);
	page_flags |= PAGE_GAVE_WARN;
      }
    }
    if (pscodep->fmmap.data!=NULL) {
      unsigned char* position;

      DEBUG_PRINT(DEBUG_GS,("\n  PS FILE:\t%s",pscodep->filename));
      position=(unsigned char*)pscodep->fmmap.data;
      while(position 
	    < (unsigned char*)pscodep->fmmap.data + pscodep->fmmap.size) {
	putc(*position,psstream);
	position++;
      }
    }
    if (pscodep->postcode!=NULL) {
      fputs(pscodep->postcode,psstream);
      putc('\n',psstream);
      DEBUG_PRINT(DEBUG_GS,("\n  PS POST CODE:\t%s",pscodep->postcode));
    }
    pscodep=pscodep->next;
  }
}


static gdImagePtr
ps2png(struct pscode* pscodep, char *device, int hresolution, int vresolution, 
       int llx, int lly, int urx, int ury, int bgred, int bggreen, int bgblue)
{
#ifndef MIKTEX
  int downpipe[2], uppipe[2];
  pid_t pid;
#else
  HANDLE hPngStream;
  HANDLE hPsStream;
  HANDLE hStdErr;
  PROCESS_INFORMATION pi;
  _TCHAR szCommandLine[2048];
  _TCHAR szGsPath[_MAX_PATH];
#define GS_PATH szGsPath
  int fd;
#endif
  FILE *psstream=NULL, *pngstream=NULL;
  char resolution[STRSIZE]; 
  /*   char devicesize[STRSIZE];  */
  gdImagePtr psimage=NULL;
  static bool showpage=false;

  sprintf(resolution, "-r%dx%d",hresolution,vresolution);
  /* Future extension for \rotatebox
  status=sprintf(devicesize, "-g%dx%d",
		 //(int)((sin(atan(1.0))+1)*
		 (urx - llx)*hresolution/72,//), 
		 //(int)((sin(atan(1.0))+1)*
		 (ury - lly)*vresolution/72);//);
  */
  DEBUG_PRINT(DEBUG_GS,
	      ("\n  GS CALL:\t%s %s %s %s %s %s %s %s %s %s %s",/* %s", */
	       GS_PATH, device, resolution, /*devicesize,*/
	       "-dBATCH", "-dNOPAUSE", "-q", "-sOutputFile=-", 
	       "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
	       (option_flags & NO_GSSAFER) ? "-": "-dSAFER", 
	       (option_flags & NO_GSSAFER) ? "": "- "));
#ifndef MIKTEX
  if (pipe(downpipe) || pipe(uppipe)) return(NULL);
  /* Ready to fork */
  pid = fork ();
  if (pid == 0) { /* Child process.  Execute gs. */       
    close(downpipe[1]);
    dup2(downpipe[0], STDIN_FILENO);
    close(downpipe[0]);
    close(uppipe[0]);
    dup2(uppipe[1], STDOUT_FILENO);
    close(uppipe[1]);
    execlp(GS_PATH, GS_PATH, device, resolution, /*devicesize,*/
	   "-dBATCH", "-dNOPAUSE", "-q", "-sOutputFile=-", 
	   "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
	   (option_flags & NO_GSSAFER) ? "-": "-dSAFER", 
	   (option_flags & NO_GSSAFER) ? NULL: "-",
	   NULL);
    _exit (EXIT_FAILURE);
  }
  /* Parent process. */
  
  close(downpipe[0]);
  psstream=fdopen(downpipe[1],"wb");
  /* fclose(psstream);  psstream=fopen("test.ps","wb"); */
  if (psstream == NULL) 
    close(downpipe[1]);
  close(uppipe[1]);
  pngstream=fdopen(uppipe[0],"rb");
  if (pngstream == NULL) 
    close(uppipe[0]);
#else /* MIKTEX */
  if (! miktex_find_miktex_executable("mgs.exe", szGsPath)) {
      Warning("Ghostscript could not be found");
      return(NULL);
  }
  sprintf(szCommandLine,"\"%s\" %s %s %s %s %s %s %s %s %s %s",/* %s",*/
	  szGsPath, device, resolution, /*devicesize,*/
	  "-dBATCH", "-dNOPAUSE", "-q", "-sOutputFile=-", 
	  "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
	  (option_flags & NO_GSSAFER) ? "-": "-dSAFER", 
	  (option_flags & NO_GSSAFER) ? "": "-");
  if (! miktex_start_process_3(szCommandLine, &pi, INVALID_HANDLE_VALUE,
			       &hPsStream, &hPngStream, &hStdErr, 0)) {
      Warning("Ghostscript could not be started");
      return(NULL);
  }
  CloseHandle (pi.hThread);
  fd = _open_osfhandle((intptr_t)hPsStream, _O_WRONLY);
  if (fd >= 0) { 
    psstream = _tfdopen(fd, "wb");
    if (psstream == NULL) 
      _close (fd);
  }
  fd = _open_osfhandle((intptr_t)hPngStream, _O_RDONLY);
  if (fd >= 0) {
    pngstream = _tfdopen(fd, "rb");
    if (pngstream == NULL) 
      _close (fd);
  }
#endif 
  if (psstream) {
    writepscode(psheaderp,psstream);
    DEBUG_PRINT(DEBUG_GS,("\n  PS CODE:\t<</PageSize[%d %d]/PageOffset[%d %d[1 1 dtransform exch]{0 ge{neg}if exch}forall]>>setpagedevice",
			  urx - llx, ury - lly,llx,lly));
    fprintf(psstream, "<</PageSize[%d %d]/PageOffset[%d %d[1 1 dtransform exch]{0 ge{neg}if exch}forall]>>setpagedevice\n",
	    urx - llx, ury - lly,llx,lly);
    if ( bgred < 255 || bggreen < 255 || bgblue < 255 ) {
      DEBUG_PRINT(DEBUG_GS,("\n  PS CODE:\tgsave %f %f %f setrgbcolor clippath fill grestore",
			    bgred/255.0, bggreen/255.0, bgblue/255.0));
      fprintf(psstream, "gsave %f %f %f setrgbcolor clippath fill grestore",
	      bgred/255.0, bggreen/255.0, bgblue/255.0);
    }
    writepscode(pscodep,psstream);
    if (showpage) {
      DEBUG_PRINT(DEBUG_GS,("\n  PS CODE:\tshowpage"));
      fprintf(psstream, " showpage ");
    }
    fclose(psstream);
  }
  if (pngstream) {
    psimage = gdImageCreateFromPng(pngstream);
    fclose(pngstream);
  }
#ifdef MIKTEX
  CloseHandle(pi.hProcess);
#endif
  if (psimage == NULL) {
    DEBUG_PRINT(DEBUG_GS,("\n  GS OUTPUT:\tNO IMAGE "));
    if (!showpage) {
      showpage=true;
      DEBUG_PRINT(DEBUG_GS,("(will try adding \"showpage\") "));
      psimage=ps2png(pscodep,
		     device, hresolution, vresolution, llx, lly, urx, ury,
		     bgred,bggreen,bgblue);
      showpage=false;
    }
#ifdef DEBUG
  } else {
    DEBUG_PRINT(DEBUG_GS,("\n  GS OUTPUT:\t%dx%d image ",
			  gdImageSX(psimage),gdImageSY(psimage)));
#endif
  }
  return psimage;
}

static gdImagePtr
rescale(gdImagePtr psimage, int pngwidth, int pngheight)
{
  gdImagePtr scaledimage=psimage;
  /* Rescale unless correct size */
  if (psimage!=NULL
      && gdImageSX(psimage)!=pngwidth 
      && gdImageSY(psimage)!=pngheight) {
    DEBUG_PRINT(DEBUG_DVI,
		("\n  RESCALE INCLUDED BITMAP \t(%d,%d) -> (%d,%d)",
		 gdImageSX(psimage),gdImageSY(psimage),
		 pngwidth,pngheight));
#ifdef HAVE_GDIMAGECREATETRUECOLOR
    scaledimage=gdImageCreateTrueColor(pngwidth,pngheight);
    /* Copy with overwrite, remember that this is the rescaled source
       image. The real target has alpha blending on. */
    gdImageAlphaBlending(scaledimage,0);
    gdImageCopyResampled(scaledimage,psimage,0,0,0,0,
			 pngwidth,pngheight,
			 gdImageSX(psimage),gdImageSY(psimage));
#else
    scaledimage=gdImageCreate(pngwidth,pngheight);
    gdImageCopyResized(scaledimage,psimage,0,0,0,0,
		       pngwidth,pngheight,
		       gdImageSX(psimage),gdImageSY(psimage));
#endif
    gdImageDestroy(psimage);
  }
  return(scaledimage);
}

static void newpsheader(char* special) {
  struct pscode* tmp;
  char* txt;

  if (psheaderp==NULL && strcmp(special,"header=tex.pro")!=0) {
    newpsheader("header=tex.pro");
    newpsheader("header=color.pro");
    newpsheader("header=special.pro");
  }
  if (strcmp(special+strlen(special)-4,".xcp")==0
      && strncmp(special,"header=",7)==0) 
    InitXColorPrologue(special+7);
  if (strncmp(special,"! /pgfH",7)==0)
    newpsheader("! TeXDict begin");
  if (psheaderp==NULL) {
    if ((tmp=psheaderp=malloc(sizeof(struct pscode)))==NULL)
      Fatal("cannot allocate space for PostScript header struct");
  } else {
    /* No duplicates. This still misses pre=..., because we still
       change that. To be fixed */
    tmp=psheaderp;
    if (strcmp(tmp->special,special)==0)
      return;
    while(tmp->next!=NULL) {
      tmp=tmp->next;
      if (strcmp(tmp->special,special)==0)
	return;
    }
    if ((tmp->next=malloc(sizeof(struct pscode)))==NULL)
      Fatal("cannot allocate space for PostScript header struct");
    tmp=tmp->next;
  }
  DEBUG_PRINT(DEBUG_GS,("\n  PS HEADER "));
  if ((txt=malloc(strlen(special)+1))==NULL)
    Fatal("cannot malloc space for PostScript header");
  strcpy(txt,special);
  PSCodeInit(tmp,txt);
}

/*********************************************************************/
/****************************  SetSpecial  ***************************/
/*********************************************************************/

void SetSpecial(char * special, int32_t hh, int32_t vv)
/* interpret a \special command, made up of keyword=value pairs,
 * or !header or ps:literal_PostScript
 */
{
  DEBUG_PRINT(DEBUG_DVI,(" '%s'",special));
  SKIPSPACES(special);
  /********************** Color specials ***********************/
  if (strncmp(special,"background ",11)==0) {
    background(special+11);
    return;
  }
  if (strncmp(special,"color ",6)==0) {
    special+=6;
    SKIPSPACES(special);
    if (strncmp(special,"push ",5)==0) {
      pushcolor(special+5);
    } else {
      if (strcmp(special,"pop")==0)
	popcolor();
      else 
	resetcolorstack(special);
    }
    return;
  }

  /******************* Image inclusion ********************/

  /* Needed tests for regression: PNG, GIF, JPEG and EPS inclusion,
   * for different gd versions */

  if (strncmp(special,"PSfile=",7)==0) { /* PSfile */
    char* psname = special+7;
    int llx=0,lly=0,urx=0,ury=0,rwi=0,rhi=0;
    bool clip=false;
    int hresolution,vresolution;
    int pngheight,pngwidth;

    /* Remove quotation marks around filename. If no quotation marks,
       use first word as filename */
    if (*psname=='"') {
      psname++;
      special=strrchr(psname,'"');
    } else {
      special=strchr(psname,' ');
    }
    if (special!=NULL) {
      *special='\0';
      special++;
    }
    
    /* Retrieve parameters */
    SKIPSPACES(special);
    while(special && *special) {
      if (strncmp(special,"llx=",4)==0)
	llx = strtol(special+4,&special,10);
      else if (strncmp(special,"lly=",4)==0)
	lly = strtol(special+4,&special,10);
      else if (strncmp(special,"urx=",4)==0)
	urx = strtol(special+4,&special,10);
      else if (strncmp(special,"ury=",4)==0)
	ury = strtol(special+4,&special,10);
      else if (strncmp(special,"rwi=",4)==0)
	rwi = strtol(special+4,&special,10);
      else if (strncmp(special,"rhi=",4)==0)
	rhi = strtol(special+4,&special,10);
      else if (strncmp(special,"clip",4)==0)
	{clip = true; special=special+4;}
      while (*special && *special!=' ') special++;
      SKIPSPACES(special);
    }
    
    /* Calculate resolution, and use our base resolution as a fallback. */
    /* The factor 10 is magic, the dvips graphicx driver needs this.    */
    hresolution = ((dpi*rwi+urx-llx-1)/(urx - llx)+9)/10;
    vresolution = ((dpi*rhi+ury-lly-1)/(ury - lly)+9)/10;
    if (vresolution==0) vresolution = hresolution;
    if (hresolution==0) hresolution = vresolution;
    if (hresolution==0) hresolution = vresolution = dpi;
      
    /* Convert from postscript 72 dpi resolution to our given resolution */
    pngwidth  = (dpi*rwi+719)/720; /* +719: round up */
    pngheight = (dpi*rhi+719)/720;
    if (pngwidth==0)  
      pngwidth  = ((dpi*rhi*(urx-llx)+ury-lly-1)/(ury-lly)+719)/720;
    if (pngheight==0) 
      pngheight = ((dpi*rwi*(ury-lly)+urx-llx-1)/(urx-llx)+719)/720;
    if (pngheight==0) {
      pngwidth  = (dpi*(urx-llx)+71)/72;
      pngheight = (dpi*(ury-lly)+71)/72;
    }    
    if (page_imagep != NULL) { /* Draw into image */
      struct pscode image;
      gdImagePtr psimage=NULL;
#ifndef HAVE_GDIMAGECREATEFROMPNGPTR
      FILE* psstream;
#endif

      PSCodeInit(&image, NULL);
      TEMPSTR(image.filename,kpse_find_file(psname,kpse_pict_format,0));
      if (MmapFile(image.filename,&(image.fmmap)) || image.fmmap.size==0) {
	Warning("Image file %s unusable, image will be left blank",
		image.filename);
	page_flags |= PAGE_GAVE_WARN;
	return;
      } 
      Message(BE_NONQUIET," <%s",psname);
      switch ((unsigned char)*image.fmmap.data) {
      case 0x89: /* PNG magic: "\211PNG\r\n\032\n" */
	DEBUG_PRINT(DEBUG_DVI,("\n  INCLUDE PNG \t%s",image.filename));
#ifdef HAVE_GDIMAGECREATEFROMPNGPTR
	psimage=gdImageCreateFromPngPtr(image.fmmap.size,image.fmmap.data);
#else
	psstream=fopen(image.filename,"rb");
	psimage=gdImageCreateFromPng(psstream);
	fclose(psstream);
#endif
	psimage=rescale(psimage,pngwidth,pngheight);
	break;
      case 'G': /* GIF magic: "GIF87" or "GIF89" */
	DEBUG_PRINT(DEBUG_DVI,("\n  INCLUDE GIF \t%s",image.filename));
#ifdef HAVE_GDIMAGEGIF
	psimage=rescale(gdImageCreateFromGifPtr(image.fmmap.size,
						image.fmmap.data),
			pngwidth,pngheight);
#else
	DEBUG_PRINT(DEBUG_DVI,(" (NO GIF DECODER)"));
#endif
	break;
      case 0xff: /* JPEG magic: 0xffd8 */
	DEBUG_PRINT(DEBUG_DVI,("\n  INCLUDE JPEG \t%s",image.filename));
#ifdef HAVE_GDIMAGECREATEFROMJPEG
#ifdef HAVE_GDIMAGECREATEFROMPNGPTR
	psimage=gdImageCreateFromJpegPtr(image.fmmap.size,image.fmmap.data);
#else
	psstream=fopen(image.filename,"rb");
	psimage=gdImageCreateFromJpeg(psstream);
	fclose(psstream);
#endif
	psimage=rescale(psimage,pngwidth,pngheight);
#else
	DEBUG_PRINT(DEBUG_DVI,(" (NO JPEG DECODER)"));
#endif
	break;
      default:  /* Default, PostScript magic: "%!PS-Adobe" */
	if (option_flags & NO_GHOSTSCRIPT) {
	  Warning("GhostScript calls disallowed by --noghostscript" );
	  page_flags |= PAGE_GAVE_WARN;
	} else {
	  /* Use alpha blending, and render transparent postscript
	     images. The alpha blending works correctly only from
	     libgd 2.0.12 upwards */
#ifdef HAVE_GDIMAGEPNGEX
	  if (page_imagep->trueColor) {
	    int tllx=llx,tlly=lly,turx=urx,tury=ury;

	    DEBUG_PRINT((DEBUG_DVI | DEBUG_GS),
			("\n  GS RENDER \t%s -> pngalpha ",image.filename));
	    if (!clip) {
	      /* Render across the whole image */ 
	      tllx=llx-(hh+1)*72/hresolution;
	      tlly=lly-(gdImageSY(page_imagep)-vv-1)*72/vresolution;
	      turx=llx+(gdImageSX(page_imagep)-hh)*72/hresolution;
	      tury=lly+(vv+1)*72/vresolution;
	      DEBUG_PRINT((DEBUG_DVI | DEBUG_GS),
			  ("\n  EXPAND BBOX \t%d %d %d %d -> %d %d %d %d",
			   llx,lly,urx,ury,tllx,tlly,turx,tury));
#ifdef DEBUG
	    } else {
	      DEBUG_PRINT((DEBUG_DVI | DEBUG_GS),(", CLIPPED TO BBOX"));
#endif
	    }
	    psimage = ps2png(&image, "-sDEVICE=pngalpha", 
			     hresolution, vresolution, 
			     tllx, tlly, turx, tury,
			     255,255,255);
	    if (psimage==NULL)
	      Warning("No GhostScript pngalpha output, opaque image inclusion");
	  } else
	    Warning("Palette output, opaque image inclusion");
#endif
	  if (psimage==NULL) {
	    /* png256 gives inferior result */
	    DEBUG_PRINT((DEBUG_DVI | DEBUG_GS),
			("\n  GS RENDER \t%s -> png16m", image.filename));
	    psimage = ps2png(&image, "-sDEVICE=png16m",
			     hresolution, vresolution, 
			     llx, lly, urx, ury,
			     cstack[0].red,cstack[0].green,cstack[0].blue);
	    clip=true;
	    page_flags |= PAGE_GAVE_WARN;
	  }
	  if (!clip) {
	    /* Rendering across the whole image */
	    hh=0;
	    vv=gdImageSY(psimage)-1;
	  }
	}
      }
      UnMmapFile(&(image.fmmap));
      if (psimage!=NULL) {
	DEBUG_PRINT(DEBUG_DVI,
		    ("\n  GRAPHIC(X|S) INCLUDE \t%s (%d,%d) res %dx%d at (%d,%d)",
		     psname,gdImageSX(psimage),gdImageSY(psimage),
		     hresolution,vresolution,hh,vv));
#ifdef HAVE_GDIMAGECREATETRUECOLOR
	if (psimage->trueColor && !page_imagep->trueColor)
	  gdImageTrueColorToPalette(psimage,0,256);
#endif
#ifdef HAVE_GDIMAGEPNGEX
	gdImageAlphaBlending(page_imagep,1);
#else
	Warning("Using libgd < 2.0.12, opaque image inclusion");
	page_flags |= PAGE_GAVE_WARN;
#endif
	gdImageCopy(page_imagep, psimage, 
		    hh, vv-gdImageSY(psimage)+1,
		    0,0,
		    gdImageSX(psimage),gdImageSY(psimage));
#ifdef HAVE_GDIMAGEPNGEX
	gdImageAlphaBlending(page_imagep,0);
#endif
	gdImageDestroy(psimage);
      } else {
        Warning("Unable to load %s, image will be left blank",image.filename);
        page_flags |= PAGE_GAVE_WARN;
      } 
      Message(BE_NONQUIET,">");
    } else { /* Don't draw */
      page_flags |= PAGE_TRUECOLOR;
      DEBUG_PRINT(DEBUG_DVI,
		  ("\n  GRAPHIC(X|S) INCLUDE \t%s (%d,%d) res %dx%d at (%d,%d)",
		   psname,pngheight,pngwidth,
		   hresolution,vresolution,hh,vv));
      min(x_min,hh);
      min(y_min,vv-pngheight+1);
      max(x_max,hh+pngwidth);
      max(y_max,vv+1);
    }
    return;
  }

  /******************* Raw PostScript ********************/

  if (strncmp(special,"!/preview@version(",18)==0) { 
    int length=0;
    special+=18;
    while (special[length]!='\0' && special[length]!=')') 
      length++;
    if (page_imagep==NULL) 
      Message(BE_NONQUIET," (preview-latex version %.*s)",length,special);
    return;
  }

  /* preview-latex' tightpage option */
  if (strncmp(special,"!/preview@tightpage",19)==0) { 
    special+=19;
    SKIPSPACES(special);
    if (strncmp(special,"true",4)==0) {
      if (page_imagep==NULL) 
	Message(BE_NONQUIET," (preview-latex tightpage option detected, will use its bounding box)");
      dvi->flags |= DVI_PREVIEW_LATEX_TIGHTPAGE;
    }
    return;
  }
  if (strncmp(special,"!userdict",9)==0 
      && strstr(special+10,"7{currentfile token not{stop}if 65781.76 div")!=NULL) {
    if (page_imagep==NULL && ~dvi->flags & DVI_PREVIEW_LATEX_TIGHTPAGE) 
      Message(BE_NONQUIET," (preview-latex <= 0.9.1 tightpage option detected, will use its bounding box)");
    dvi->flags |= DVI_PREVIEW_LATEX_TIGHTPAGE;
    return;
  }

  /* preview-latex' dvips bop-hook redefinition */
  if (strncmp(special,"!userdict",9)==0 
      && strstr(special+10,"preview-bop-")!=NULL) {
    dvi->flags |= DVI_PREVIEW_BOP_HOOK;
    if (page_imagep==NULL) 
      Message(BE_VERBOSE," (preview-latex beginning-of-page-hook detected)");
    return;
  }

  if (dvi->flags & DVI_PREVIEW_BOP_HOOK && ~page_flags & PAGE_PREVIEW_BOP 
      && strncmp(special,"ps::",4)==0) {
    dviunits adj_llx,adj_lly,adj_urx,adj_ury,ht,dp,wd;
    page_flags |= PAGE_PREVIEW_BOP;
    /* Hokay, decode bounding box */
    adj_llx = strtol(special+4,&special,10);
    adj_lly = strtol(special,&special,10);
    adj_urx = strtol(special,&special,10);
    adj_ury = strtol(special,&special,10);
    ht = strtol(special,&special,10);
    dp = strtol(special,&special,10);
    wd = strtol(special,&special,10);
    if (wd>0) {
      x_offset_tightpage = 
	(-adj_llx+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor;
      x_width_tightpage  = x_offset_tightpage
	+(wd+adj_urx+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor;
    } else {
      x_offset_tightpage = 
	(-wd+adj_urx+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor;
      x_width_tightpage  = x_offset_tightpage
	+(-adj_llx+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor;
    }
    /* y-offset = height - 1 */
    y_offset_tightpage = 
      (((ht>0)?ht:0)+adj_ury+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor-1;
    y_width_tightpage  = y_offset_tightpage+1
      +(((dp>0)?dp:0)-adj_lly+dvi->conv*shrinkfactor-1)/dvi->conv/shrinkfactor;
    return;
  }

  if (special[0]=='"' || strncmp(special,"ps:",3)==0) { /* Literal PostScript */
    if (page_imagep != NULL) { /* Draw into image */
      static struct pscode *pscodep=NULL;
      static bool psenvironment=false;
      bool nextisps;
      struct pscode *tmp;
      gdImagePtr psimage=NULL;
      char *txt;
      
      /* Some packages split their literal PostScript code into
	 several specials. Check for those, and concatenate them so
	 that they're given to one and the same invocation of gs */
      if (pscodep==NULL) {
	Message(BE_NONQUIET," <literal PS");
	if ((tmp=pscodep=malloc(sizeof(struct pscode)))==NULL)
	  Fatal("cannot allocate space for raw PostScript struct");
      } else {
	tmp=pscodep;
	while(tmp->next != NULL)
	  tmp=tmp->next;
	if ((tmp->next=malloc(sizeof(struct pscode)))==NULL)
	  Fatal("cannot allocate space for raw PostScript struct");
	tmp=tmp->next;
      }
      if (strncmp(special,"ps::[begin]",11)==0)
	psenvironment=true;
      else if (strncmp(special,"ps::[end]",9)==0)
	psenvironment=false;
      else if (strcmp(special,"ps:: pgfo")==0)
	/* PostScript code to start page for pgf PostScript
	   specials. The first numbers are generally valid for the bop
	   instruction, and the latter code is to move the origin to
	   the right place. */
	special="ps:: 39139632 55387786 1000 600 600 (tikzdefault.dvi) @start 1 0 bop pgfo 0 0 matrix defaultmatrix transform itransform translate";
      else if (strcmp(special,"ps:: pgfc")==0)
	special="ps:: pgfc eop end";
      nextisps=DVIIsNextPSSpecial(dvi);
      if (psenvironment || nextisps) {
	if (!nextisps) {
	  Warning("PostScript environment contains DVI commands");
	  page_flags |= PAGE_GAVE_WARN;
	}
	/* Don't use alloca, we do not want to run out of stack space */
	DEBUG_PRINT(DEBUG_GS,("\n  PS SPECIAL "));
	txt=malloc(strlen(special)+1);
	strcpy(txt,special);
	PSCodeInit(tmp,txt);
	return;
      }
      DEBUG_PRINT(DEBUG_DVI,("\n  LAST PS SPECIAL "));
      PSCodeInit(tmp,special);
      /* Now, render image */
      if (option_flags & NO_GHOSTSCRIPT)
	Warning("GhostScript calls disallowed by --noghostscript" );
      else {
	/* Use alpha blending, and render transparent postscript
	   images. The alpha blending works correctly only from
	   libgd 2.0.12 upwards */
#ifdef HAVE_GDIMAGEPNGEX
	if (page_imagep->trueColor) {
	  /* Render across the whole image */ 
	  psimage = ps2png(pscodep, "-sDEVICE=pngalpha", 
			   dpi,dpi, 
			   -(hh+1)*72/dpi,
			   -(gdImageSY(page_imagep)-vv-1)*72/dpi,
			   (gdImageSX(page_imagep)-hh)*72/dpi,
			   (vv+1)*72/dpi,
			   255,255,255);
	  if (psimage!=NULL) {
	    gdImageAlphaBlending(page_imagep,1);
	    gdImageCopy(page_imagep, psimage, 
			0,0,0,0,
			gdImageSX(psimage),gdImageSY(psimage));
	    gdImageAlphaBlending(page_imagep,0);
	    gdImageDestroy(psimage);
	  } else
	    Warning("No GhostScript pngalpha output, cannot render raw PostScript");
	} else
	  Warning("Palette output, cannot include raw PostScript");
#else
	Warning("Using libgd < 2.0.12, unable to include raw PostScript");
#endif
      }
      while(pscodep->next != NULL) {
	tmp=pscodep->next;
	free(pscodep->special);
	free(pscodep);
	pscodep=tmp;
      }
      free(pscodep);
      pscodep=NULL;
      if (psimage==NULL) 
	page_flags |= PAGE_GAVE_WARN;
      Message(BE_NONQUIET,">");
    } else { /* Don't draw */
      page_flags |= PAGE_TRUECOLOR;
    }
    return;
  }

  if (strncmp(special,"papersize=",10)==0) { /* papersize spec, ignored */
    return;
  }

  if (special[0]=='!' || strncmp(special,"header=",7)==0) { /* PS header */
    newpsheader(special);
    return;
  }

  if (strncmp(special,"src:",4)==0) { /* source special */
    if ( page_imagep != NULL )
      Message(BE_NONQUIET," at (%ld,%ld) source \\special{%s}",
	      hh, vv, special);
    return;
  }
  if ( page_imagep != NULL ) {
    Warning("at (%ld,%ld) unimplemented \\special{%s}",
	    hh, vv, special);
    page_flags |= PAGE_GAVE_WARN;
  }
}