summaryrefslogtreecommitdiff
path: root/Build/source/texk/xdvik/psnews.c
blob: 9fb9c2a230081a97644cd76846626b1db3a435a6 (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
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
/*========================================================================*\

Copyright (c) 1994-2004  Paul Vojta

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
PAUL VOJTA OR ANY OTHER AUTHOR OF THIS SOFTWARE BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

NOTES:
This code was originally written by Ricardo Telichevesky
(ricardo@rle-vlsi-mit.edu) and Luis Miguel Silveira
(lms@rle-vlsi-mit.edu).
It was largely influenced by similar code in the SeeTeX/XTeX
package by Dirk Grunwald (grunwald@colorado.edu).

\*========================================================================*/

    /* ||| To do:
     *	ALWAYS_CLOSE_SERVER_CONNECTION?
     *	Is there some way of interrupting a process?
     *	fork
     *	extra bytes on input
     */

#ifdef PS_NEWS	/* whole file */

#include <signal.h>
#include <sys/file.h>	/* this defines FASYNC */
#include <X11/X.h>
#include <X11/Xlib.h>
#undef SYSV	/* To avoid defined SYSV_{WAIT,UCONTEXT} in xview/notify.h.  */
#include <NeWS/psio.h>
#include <xvps/pscanvas.h>

    /* Condition for retrying a write */
#include <errno.h>
#include <setjmp.h>

#include "xdvi-config.h"
#include "xdvi.h"
#include "events.h"
#include "dvi-init.h"
#include "dvi-draw.h"

    /* if POSIX O_NONBLOCK is not available, use O_NDELAY */
#if !defined(O_NONBLOCK) && defined(O_NDELAY)
#define	O_NONBLOCK O_NDELAY
#endif

#ifdef	X_NOT_STDC_ENV
    extern int errno;
#endif

#ifdef	EWOULDBLOCK
#ifdef	EAGAIN
#define	AGAIN_CONDITION	(errno == EWOULDBLOCK || errno == EAGAIN)
#else /* EAGAIN */
#define	AGAIN_CONDITION	(errno == EWOULDBLOCK)
#endif /* EAGAIN */
#else /* EWOULDBLOCK */
#ifdef	EAGAIN
#define	AGAIN_CONDITION	(errno == EAGAIN)
#endif /* EAGAIN */
#endif /* EWOULDBLOCK */

#if HAVE_POLL
# include <poll.h>
# define XIO_IN POLLIN
# define XIO_OUT POLLOUT
#else
# define XIO_IN 1
# define XIO_OUT 2
#endif


#if !defined(FLAKY_SIGPOLL) && !HAVE_STREAMS && !defined(FASYNC)
# define FLAKY_SIGPOLL	1
#endif

char *strtok(char *, const char *);

/* define ALWAYS_CLOSE_SERVER_CONNECTION if you want to close the server
   connection all the time */
#undef	ALWAYS_CLOSE_SERVER_CONNECTION


/*
 * Some setup code.
 */
static const char str0[] =
"/OW2? version cvi 2 eq def "
"OW2? "
"{ /setlinewidth { pop } def} "
"{ /NeWS 3 0 findpackage beginpackage "
"  /X11 3 0 findpackage beginpackage} "
"ifelse "
"currentcanvas /Color get "
"currentcanvas /Colormap get getcubedescription null eq and "
"   {8 {{currentcanvas /Colormap get 1 index dup dup dup newcube} stopped "
"    {pop pop pop pop pop} {exit} ifelse "
"    2 div cvi dup 1 eq {exit} if} loop pop} "
"if\n";
/*
 * This string reads chunks (delimited by %%xdvimark).
 * The first character of a chunk tells whether a given chunk
 * is to be done within save/restore or not.
 * The `H' at the end tells it that the first group is a
 * header; i.e., no save/restore.
 */
static const char preamble[] =
"/xdvi$line 81 string def "
"/xdvi$run {$error null ne {$error /newerror false put} if "
" {currentfile cvx stopped "
" $error null eq {false} {$error /newerror get} ifelse and "
" {handleerror} if} stopped pop} def "
"/xdvi$dslen countdictstack def "
"{currentfile read not {exit} if 72 eq "
"    {xdvi$run} "
"    {/xdvi$sav save def xdvi$run "
"      clear countdictstack xdvi$dslen sub {end} repeat xdvi$sav restore} "
"  ifelse "
"  {(%%xdvimark) currentfile xdvi$line {readline} stopped "
"    {clear} {{eq {false exit} if} {true exit} ifelse} ifelse }loop {exit} if "
"  58 tagprint flush "
"}loop\nH";

extern const char psheader[];
extern int psheaderlen;

static const char preamble2[] = " stop\n%%xdvimark\n";
#define	stopstring	preamble2

/* global procedures (besides initNeWS) */

static void toggleNeWS(int flag);
static void destroyNeWS(void);
static void interruptNeWS(void);
static void endpageNeWS(void);
static void drawbeginNeWS(int, int, const char *);
static void drawbeginNeWS_box(int, int, const char *);
static void drawrawNeWS(const char *);
static void drawrawNeWS_box(const char *);
static void drawfileNeWS(const char *, FILE *);
static void drawendNeWS(const char *);
static void beginheaderNeWS(void);
static void endheaderNeWS(void);
static void newdocNeWS(void);

static struct psprocs news_procs = {
    /* toggle */ toggleNeWS,
    /* destroy */ destroyNeWS,
    /* interrupt */ interruptNeWS,
    /* endpage */ endpageNeWS,
    /* drawbegin */ drawbeginNeWS,
    /* drawraw */ drawrawNeWS,
    /* drawfile */ drawfileNeWS,
    /* drawend */ drawendNeWS,
    /* beginheader */ beginheaderNeWS,
    /* endheader */ endheaderNeWS,
    /* newdoc */ newdocNeWS
};

/* define local static variables */
static int NeWS_mag;	/* magnification currently in use */
static int NeWS_shrink;	/* shrink factor currently in use */
static unsigned int NeWS_page_w;	/* how big our current page is */
static unsigned int NeWS_page_h;
static Boolean NeWS_active;	/* if we've started a page yet */
static int NeWS_pending;	/* number of ack's we're expecting */
static const char *NeWS_send_byte;	/* next byte to send to NeWS */
static const char *NeWS_send_end;	/* last + 1 byte to send */
static Boolean NeWS_in_header;	/* if we're sending a header */
static Boolean NeWS_in_doc;	/* if we've sent header information */
static int NeWS_ev_mask;	/* events for which we'll stop */
static Boolean NeWS_destroyed = False;

#define	NEWS_MASK_NORMAL	EV_GE_NEWPAGE
#define	NEWS_MASK_HEADER	EV_GE_PS_TOGGLE
#define	NEWS_MASK_INIT		(EV_GE_TERM | EV_PS_TOGGLE)


/*
 *	NeWS I/O code.  This should send PS code to NeWS,
 *	receive acknowledgements, and receive X events in the meantime.
 *	It also checks for SIGPIPE errors.
 */

static void read_from_NeWS(void);
static void write_to_NeWS(void);

static	struct xio	NeWS_xout	= {NULL, 0, XIO_IN,
#if HAVE_POLL
					   NULL,
#endif
					   read_from_NeWS, write_to_NeWS, NULL};

static	struct xio	NeWS_xin	= {NULL, 0, XIO_IN,
#if HAVE_POLL
					   NULL,
#endif
					   read_from_NeWS, NULL, NULL};


/*---------------------------------------------------------------------------*
  psio_sigpipe_handler  ()

  Arguments: sig, code, scp, addr (see man page for signal)
  Returns: (void)
  Side-Effects: SIGPIPE signal is flagged as sigpipe_error variable is set.

  Description:
  Handler for SIGPIPE error generated by a broken pipe in the connection
  to the NeWS server; this may be duer to some abnormal condition, or some
  hairy PostScript code containing commands not implemented by the server.

  +----------------------------------------------------------------------------*/

static Boolean sigpipe_error = False;

static struct sigaction psio_sigpipe_handler_struct;
/* initialized to {psio_sigpipe_handler, (sigset_t) 0, 0} in initNeWS */

static RETSIGTYPE
psio_sigpipe_handler(int sig, int code, struct sigcontext *scp, char *addr)
{
    sigpipe_error = True;
}


/*
 *	read_from_NeWS - This does the actual retrieving of acknowledgements.
 *	If other bytes appear on the file - tough.
 */

static void
read_from_NeWS(void)
{
    for (;;) {
	int retval;

	retval = ps_checkfor(PostScriptInput, PSIO_FIND_TAG, 58);
	if (retval == 0)
	    break;
	if (retval < 0) {
	    fprintf(stderr, "[xdvik] ps_checkfor: %d\n", retval);
	    return;
	}
	(void)ps_checkfor(PostScriptInput, PSIO_WAIT_TAG, 58);
	--NeWS_pending;
	if (NeWS_pending == 0)
	    globals.ev.flags |= EV_ACK;
	if (globals.debug & DBG_PS)
	    printf("Got NeWS ack; %d pending.\n", NeWS_pending);
    }
}


/*
 *	write_to_NeWS - Write to the PostScript interpreter.
 */

static	void
write_to_NeWS(void)
{
    int	old_flags;
    int	bytes;

    old_flags = fcntl(PostScript->file, F_GETFL, 0);
    if (old_flags < 0) return;
    /* set to be non-blocking */
    if (fcntl(PostScript->file, F_SETFL, old_flags | O_NONBLOCK) < 0)
	return;

    for (;;) {
	bytes = write(PostScript->file, NeWS_send_byte,
		      NeWS_send_end - NeWS_send_byte);
	if (bytes < 0) {
	    if (AGAIN_CONDITION)
		break;
	    perror("xdvi NeWS_send");
	    break;
	}
	NeWS_send_byte += bytes;
	if (NeWS_send_byte == NeWS_send_end) {
	    NeWS_send_byte = NULL;
	    NeWS_xout.xio_events &= ~XIO_OUT;
#if HAVE_POLL
	    /* This check is necessary, since write_to_NeWS can be called
	       directly. */
	    if (NeWS_xout.pfd != NULL)
		NeWS_xout.pfd->events &= ~POLLOUT;
	    globals.ev.flags |= EV_ACK;
	    break;
#endif
	}
    }

    fcntl(PostScript->file, F_SETFL, old_flags);
}


/*
 *	Clean up after NeWS_send()
 */

static void
post_send(void)
{
    if (sigpipe_error) {
	fputs("NeWS died unexpectedly.\n", stderr);
	destroyNeWS();
	draw_bbox();
    }
}


/*
 *	Main routine for writing to the NeWS interpreter.
 */

static	void
NeWS_send(const char *cp, size_t len)
{
    struct sigaction orig;

    if (PostScript == (PSFILE *) NULL || (globals.ev.flags & NeWS_ev_mask))
	return;

    (void) sigaction(SIGPIPE, &psio_sigpipe_handler_struct, &orig);
    sigpipe_error = False;

    NeWS_send_byte = cp;
    NeWS_send_end = cp + len;
    NeWS_xout.xio_events |= XIO_OUT;
#if HAVE_POLL
    if (NeWS_xout.pfd != NULL)
	NeWS_xout.pfd->events |= POLLOUT;
#endif

    write_to_NeWS();
    (void) read_events(NeWS_ev_mask | EV_ACK);

    if (!(globals.ev.flags & EV_ACK)) {	/* if interrupted */
	/* ||| Do somthing more severe here */
    }

    globals.ev.flags &= ~EV_ACK;

    /* put back generic handler for SIGPIPE */
    (void) sigaction(SIGPIPE, &orig, (struct sigaction *) NULL);

    if (!NeWS_in_header)
	post_send();
}

/*
 *	Wait for acknowledgement from NeWS.  With NeWS we have no choice but
 *	to wait (||| I think).
 */

static void
waitack(void)
{
    if (PostScript == (PSFILE *) NULL)
	return;

    if (NeWS_pending > 0)
	(void) read_events(EV_GE_ACK);

    if (globals.ev.flags & EV_ACK) {
	globals.ev.flags &= ~EV_ACK;
	return;
    }

    /* ||| Do something more serious here */
}


/*---------------------------------------------------------------------------*
  initNeWS()

  Arguments: None.
  Returns: True if and only if initialization succeeded
  Side-Effects: Static variables may be set.

  Description:
  Initializes variables for the application main loop.

  +----------------------------------------------------------------------------*/

Boolean initNeWS(void)
{
    static NeWStoken newstoken;

    /* now try to open the connection to the NeWS server */
    if (ps_open_PostScript() == (PSFILE *) NULL)
	return False;

    psio_sigpipe_handler_struct.sa_handler = psio_sigpipe_handler;
    sigemptyset(&psio_sigpipe_handler_struct.sa_mask);

#if !FLAKY_SIGPOLL
    if (fcntl(PostScript->file, F_SETOWN, getpid()) == -1)
	perror("xdvi: fcntl F_SETOWN");
    if (fcntl(PostScript->file, F_SETFL,
	      fcntl(PostScript->file, F_GETFL, 0) | FASYNC) == -1)
	perror("xdvi: fcntl F_SETFL");
#endif /* not FLAKY_SIGPOLL */
    if (PostScriptInput->file != PostScript->file) {
#if !FLAKY_SIGPOLL
	if (fcntl(PostScriptInput->file, F_SETOWN, getpid()) == -1)
	    perror("xdvi: fcntl F_SETOWN");
	if (fcntl(PostScriptInput->file, F_SETFL,
		  fcntl(PostScriptInput->file, F_GETFL, 0) | FASYNC) == -1)
	    perror("xdvi: fcntl F_SETFL");
#endif /* not FLAKY_SIGPOLL */
	NeWS_xout.xio_events &= ~XIO_IN;
	NeWS_xin.fd = PostScriptInput->file;
	set_io(&NeWS_xin);
    }
    NeWS_xout.fd = PostScript->file;
    set_io(&NeWS_xout);

    NeWS_active = False;
    NeWS_in_header = True;
    NeWS_ev_mask = NEWS_MASK_INIT;
    NeWS_pending = 1;

    ps_flush_PostScript();
    NeWS_send(str0, (sizeof str0) - 1);
    /* get xid of window, then make this window the NeWS canvas */
    (void)ps_token_from_xid(mane.win, &newstoken);
    if (newstoken != -1) {
	ps_setcanvas(newstoken);
	ps_flush_PostScript();

	NeWS_send(preamble, (sizeof preamble) - 1);
	NeWS_send(psheader, psheaderlen);
	NeWS_send(preamble2, (sizeof preamble2) - 1);
	NeWS_in_header = False;
	post_send();
	waitack();
    }

    if (NeWS_destroyed)
	return False;

    /* success */

    NeWS_mag = NeWS_shrink = -1;
    NeWS_page_w = globals.page.w;
    NeWS_page_h = globals.page.h;

    psp = news_procs;
    if (!resource.postscript)
	toggleNeWS(0);	/* if we got a 'v' already */

    return True;
}


/*---------------------------------------------------------------------------*
  toggleNeWS(int flag)

  Arguments: flag for toggling PostScript
  Returns: (void)
  Side-Effects: psp.drawbegin is changed

  Description:
  Used to toggle the rendering of PostScript by the NeWS server
  Callable from within read_events().

  +----------------------------------------------------------------------------*/

static void
toggleNeWS(int flag)
{
    if (globals.debug & DBG_PS)
	fprintf(stdout, "Toggling NeWS to %d", flag);

    switch (flag) {
    case 0:
	psp.drawbegin = drawbegin_none;
	break;
    case 1:
	psp.drawbegin = drawbeginNeWS;
	break;
    default:
	psp.drawbegin = drawbeginNeWS_box;
	break;
    }
}


/*---------------------------------------------------------------------------*
  destroyNeWS()

  Arguments: none
  Returns: (void)
  Side-Effects: the pointer to the NeWS file is nulled

  Description:
  Close the connection to the NeWS server; used when rendering is terminated
  in any way.

  +----------------------------------------------------------------------------*/

static void
destroyNeWS(void)
{
    psp = no_ps_procs;
    NeWS_destroyed = True;
    scanned_page = scanned_page_ps = scanned_page_reset;
}


/*---------------------------------------------------------------------------*
  interruptNeWS()

  Arguments: none
  Returns: void

  Description:
  Close the connection to the NeWS server; used when rendering is terminated
  because of an interruption in the viewing of the current page.
  ||| It would be nice if we could asynchronously ``wake up'' a NeWS process
  (preferably by sending something along the X socket); then we could do
  better than just to wait.

  +----------------------------------------------------------------------------*/

static void
interruptNeWS(void)
{
    if (globals.debug & DBG_PS)
	puts("Running interruptNeWS()");
    if (NeWS_pending <= 0) return;	/* if nothing to do */

    if (NeWS_active) {
	NeWS_send(stopstring, (sizeof stopstring) - 1);
	NeWS_active = False;
    }

    for (;;) {
	ps_flush_PostScript();
	if (NeWS_pending <= 0) break;
	waitack();
    }
}


/*---------------------------------------------------------------------------*
  endpageNeWS()

  Arguments: none
  Returns: (void)
  Side-Effects: the NeWS_active variable is cleared.

  Description:
  Should be called at the end of a page to end this chunk for the NeWS server.

  +----------------------------------------------------------------------------*/

static void
endpageNeWS(void)
{
    if (globals.debug & DBG_PS)
	puts("endpage sent to NeWS Server");
    if (NeWS_active) {
	NeWS_send(stopstring, (sizeof stopstring) - 1);
	NeWS_active = False;
	waitack();
    }
}


/*---------------------------------------------------------------------------*
  drawbeginNeWS  ()

  Arguments: xul, yul - coordinates of the upper left corner of the figure
  cp - string with the bounding box line data
  Returns: (void)

  Description:
  Opens a connection to the NeWS server and send in the preamble and the
  bounding box information after correctly computing resolution factors.
  In case no rendering is to be done, outlines the figure.  An outline is
  also generated whenever the PostScript code is too hairy and generates
  a SIGPIPE signal.

  +----------------------------------------------------------------------------*/

static void
drawbeginNeWS(int xul, int yul, const char *cp)
{
    char buf[100];
    static const char str[] = " TeXDict begin\n";
    static const char str2[] = "Hinitgraphics stop\n%%xdvimark\n";

    if (globals.debug & DBG_PS) {
	printf("xul= %d yul= %d\n", xul, yul);
	printf("String = < %s >\n", cp);
    }

    /* catch up on the X side */
    XSync(DISP, False);

    if (!NeWS_active) {
	/* send initialization to NeWS server */
	if (NeWS_page_w < globals.page.w || NeWS_page_h < globals.page.h) {
	    if (globals.ev.flags & NEWS_MASK_NORMAL)
		longjmp(globals.ev.canit, 1);
	    ++NeWS_pending;
	    NeWS_page_w = globals.page.w;
	    NeWS_page_h = globals.page.h;
	    NeWS_send(str2, (sizeof str2) - 1);
	}
	if (magnification != NeWS_mag) {
	    if (globals.ev.flags & NEWS_MASK_NORMAL)
		longjmp(globals.ev.canit, 1);
	    ++NeWS_pending;
	    sprintf(buf, "H TeXDict begin /DVImag %d 1000 div def "
		    "end stop\n%%%%xdvimark\n",
		    NeWS_mag = magnification);
	    NeWS_send(buf, strlen(buf));
	}
	if (mane.shrinkfactor != NeWS_shrink) {
	    if (globals.ev.flags & NEWS_MASK_NORMAL)
		longjmp(globals.ev.canit, 1);
	    ++NeWS_pending;
	    sprintf(buf, "H TeXDict begin %d %d div dup "
		    "/Resolution X /VResolution X "
		    "end stop\n%%%%xdvimark\n",
		    resource.pixels_per_inch,
		    NeWS_shrink = mane.shrinkfactor);
	    NeWS_send(buf, strlen(buf));
	}
	if (globals.ev.flags & NEWS_MASK_NORMAL)
	    longjmp(globals.ev.canit, 1);
	++NeWS_pending;
	NeWS_send(str, (sizeof str) - 1);
	NeWS_active = True;
    }

    sprintf(buf, "%d %d moveto\n", xul, yul);
    NeWS_send(buf, strlen(buf));
    NeWS_send(cp, strlen(cp));
}

static void
drawbeginNeWS_box(int xul, int yul, const char *cp)
{
    drawbeginNeWS(xul, yul, cp);
    draw_bbox();
}


/*---------------------------------------------------------------------------*
  drawrawNeWS()

  Arguments: origcp - the raw string to be sent to the postscript interpreter
  Returns: (void)
  Side-Effects: (none)

  Description:
  If there is a valid connection to the NeWS server, just send the string to
  the interpreter, else leave.

  +----------------------------------------------------------------------------*/

static void
drawrawNeWS(const char *origcp)
{
    const char *pt, *ptm1, *ocp1;
    static char *cp;
    char *cp1;
    static unsigned int cplen = 0;
    unsigned int len;
    double angle;
    Boolean found = False;

    if (!NeWS_active)
	return;

    if (globals.debug & DBG_PS)
	printf("Raw PS sent to context: <%s>\n", origcp);

    /* take a look at the string:  NeWS bums on certain rotations */
    len = strlen(origcp) + 4;
    if (cplen < len) {
	if (cplen != 0)
	    free(cp);
	cplen = len;
	cp = xmalloc(cplen);
    }
    ocp1 = origcp;
    pt = origcp;
    while (*pt == ' ' || *pt == '\t')
	++pt;
    cp1 = cp;
    for (;;) {
	ptm1 = pt;
	while (*pt != '\0' && *pt != ' ' && *pt != '\t')
	    ++pt;
	if (*pt == '\0')
	    break;
	while (*pt == ' ' || *pt == '\t')
	    ++pt;
	if (strncmp(pt, "rotate", 6) == 0
	    && (pt[6] == '\0' || pt[6] == ' ' || pt[6] == '\t')) {
	    /* found rotate; check angle */
	    if (sscanf(ptm1, "%lf", &angle) >= 1) {
		found = True;
		while (angle > 360.0)
		    angle -= 360;
		while (angle < -360.0)
		    angle += 360;
		if (angle == 90.0) {
		    angle = 89.999;
		    (void)memcpy(cp1, ocp1, ptm1 - ocp1);
		    cp1 += ptm1 - ocp1;
		    strcpy(cp1, "89.999 rotate ");
		    cp1 += strlen(cp1);
		    while (*pt != '\0' && *pt != ' ' && *pt != '\t')
			++pt;
		    while (*pt == ' ' || *pt == '\t')
			++pt;
		    ocp1 = pt;
		}
		else if (angle == -90.0) {
		    angle = -89.999;
		    (void)memcpy(cp1, ocp1, ptm1 - ocp1);
		    cp1 += ptm1 - ocp1;
		    strcpy(cp1, "-89.999 rotate ");
		    cp1 += strlen(cp1);
		    while (*pt != '\0' && *pt != ' ' && *pt != '\t')
			++pt;
		    while (*pt == ' ' || *pt == '\t')
			++pt;
		    ocp1 = pt;
		}
		else if (angle == 0.0) {
		    (void)memcpy(cp1, ocp1, ptm1 - ocp1);
		    cp1 += ptm1 - ocp1;
		    while (*pt != '\0' && *pt != ' ' && *pt != '\t')
			++pt;
		    while (*pt == ' ' || *pt == '\t')
			++pt;
		    ocp1 = pt;
		}
	    }
	}
    }
    strcpy(cp1, ocp1);
    if ((globals.debug & DBG_PS) && found) {
	printf("String is now <%s>\n", cp);
	printf("Found rotate string.  Angle is %g degrees.\n", angle);
    }

    len = strlen(cp);
    cp[len] = '\n';
    NeWS_send(cp, len + 1);
}


/*---------------------------------------------------------------------------*
  drawfileNeWS()

  Arguments: cp - string with the postscript file pathname
  psfile - file, already opened
  Returns: (void)
  Side-Effects: none

  Description:
  Postscript file containing the figure is opened and sent to the NeWS server.
  Figure is outlined in case hairy code produces a SIGPIPE signal.

  +----------------------------------------------------------------------------*/

static void
drawfileNeWS(const char *cp, FILE *psfile)
{
    char buffer[1025];
    int blen;
    struct sigaction orig;

    if (!NeWS_active) {
	fclose(psfile);
	return;
    }

    if (globals.debug & DBG_PS)
	printf("printing file %s\n", cp);

    sigpipe_error = False;
    for (;;) {
	blen = fread(buffer, sizeof(char), 1024, psfile);
	if (blen == 0) break;
	NeWS_send(buffer, blen);
	if (sigpipe_error || (globals.ev.flags & NeWS_ev_mask))
	    break;
    }
    fclose(psfile);

    if (sigpipe_error) {
	fputs("NeWS died unexpectedly.\n", stderr);
	destroyNeWS();
	draw_bbox();
    }
}


/*---------------------------------------------------------------------------*
  drawendNeWS()

  Arguments: cp - string with indication of the end of the special
  Returns: (void)

  Description:
  Sends the indication of end of the figure PostScript code.

  +----------------------------------------------------------------------------*/

static void
drawendNeWS(const char *cp)
{
    if (!NeWS_active)
	return;

    if (globals.debug & DBG_PS)
	puts("drawend sent to NeWS Server");
    NeWS_send(cp, strlen(cp));
    NeWS_send("\n", 1);
}


/*---------------------------------------------------------------------------*
  beginheaderNeWS()

  Arguments: none
  Returns: (void)

  Description:
  Prepares the PostScript interpreter for receipt of header code.

  +----------------------------------------------------------------------------*/

static void
beginheaderNeWS(void)
{
    static const char str[] = "Hsave /xdvi$doc exch def\n";

    if (globals.debug & DBG_PS)
	puts("Running beginheaderNeWS()");

    if (NeWS_active) {
	if (!NeWS_in_header)
	    XDVI_FATAL((stderr, "Internal error in beginheaderNeWS()."));
	return;
    }

    if (globals.ev.flags & NEWS_MASK_HEADER)
	longjmp(globals.ev.canit, 1);

    NeWS_in_header = True;
    NeWS_ev_mask = NEWS_MASK_HEADER;
    ++NeWS_pending;
    if (NeWS_in_doc)
	NeWS_send("H", 1);
    else {
	NeWS_send(str, (sizeof str) - 1);
	NeWS_in_doc = True;
    }
    NeWS_active = True;
}


/*---------------------------------------------------------------------------*
  endheaderNeWS()

  Arguments: none
  Returns: (void)

  Description:
  Prepares the PostScript interpreter for receipt of header code.

  +----------------------------------------------------------------------------*/

static void
endheaderNeWS(void)
{
    static const char str[] = "stop\n%%xdvimark\n";

    if (globals.debug & DBG_PS)
	puts("Running endheaderNeWS()");

    if (NeWS_active) {
	NeWS_send(str, (sizeof str) - 1);
	NeWS_active = False;
	post_send();
	waitack();
	NeWS_in_header = False;
	NeWS_ev_mask = NEWS_MASK_NORMAL;
    }
}


/*---------------------------------------------------------------------------*
  newdocNeWS()

  Arguments: none
  Returns: (void)

  Description:
  Clears out headers stored from the previous document.

  +----------------------------------------------------------------------------*/

static void
newdocNeWS(void)
{
    static const char str[] = "H xdvi$doc restore stop\n%%xdvimark\n";

    if (globals.debug & DBG_PS)
	puts("Running newdocNeWS()");

    if (NeWS_in_doc) {
	++NeWS_pending;
	NeWS_send(str, (sizeof str) - 1);
	NeWS_mag = NeWS_shrink = -1;
	NeWS_in_doc = False;
    }
}
#else
/* silence `empty compilation unit' warnings */
static void bar(void); static void foo(void) { bar(); } static void bar(void) { foo(); }
#endif /* PS_NEWS */