Debian Codegraph @

texk/xdvik/psgs.c

raw
1 /*========================================================================*\
2
3 Copyright (c) 1994-2019 Paul Vojta
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to
7 deal in the Software without restriction, including without limitation the
8 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 sell copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 PAUL VOJTA OR ANY OTHER AUTHOR OF THIS SOFTWARE BE LIABLE FOR ANY CLAIM,
19 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21 OTHER DEALINGS IN THE SOFTWARE.
22
23 \*========================================================================*/
24
25 #ifdef PS_GS /* entire file */
26
27
28 #include "xdvi-config.h"
29 #include "xdvi.h"
30 #include "psgs.h"
31
32 #include <setjmp.h>
33 #include <X11/Xatom.h>
34 #include <sys/time.h> /* for timeval */
35
36 #include <signal.h>
37
38 /* Condition for retrying a write */
39 #include <errno.h>
40 #include <string.h>
41
42 #include "kpathsea/c-pathmx.h"
43 #include "dvi-init.h"
44 #include "dvi-draw.h"
45 #include "events.h"
46 #include "statusline.h"
47 #include "special.h"
48 #include "util.h"
49
50
51 #ifdef X_NOT_STDC_ENV
52 extern int errno;
53 #endif
54
55 #ifdef EWOULDBLOCK
56 # ifdef EAGAIN
57 # define AGAIN_CONDITION (errno == EWOULDBLOCK || errno == EAGAIN)
58 # else
59 # define AGAIN_CONDITION (errno == EWOULDBLOCK)
60 # endif
61 #else
62 # ifdef EAGAIN
63 # define AGAIN_CONDITION (errno == EAGAIN)
64 # endif
65 #endif
66
67 #if HAVE_POLL
68 # include <poll.h>
69 # define XIO_IN POLLIN
70 # define XIO_OUT POLLOUT
71 #else
72 # define XIO_IN 1
73 # define XIO_OUT 2
74 #endif
75
76 #ifdef MOTIF
77 # include <Xm/Xm.h>
78 #endif
79
80 extern const char psheader[];
81 extern unsigned psheaderlen;
82
83 Boolean gs_postpone_prescan = False;
84
85 /* global procedures (besides initGS) */
86
87 static void toggle_gs(int flag);
88 static void destroy_gs(void);
89 static void interrupt_gs(void);
90 static void endpage_gs(void);
91 static void drawbegin_gs(int, int, const char *);
92 static void drawbegin_gs_box(int, int, const char *);
93 void drawraw_gs(const char *);
94 static void drawfile_gs(const char *, FILE *);
95 static void drawend_gs(const char *);
96 static void beginheader_gs(void);
97 static void endheader_gs(void);
98 static void newdoc_gs(void);
99
100 static struct psprocs gs_procs = {
101 /* toggle */ toggle_gs,
102 /* destroy */ destroy_gs,
103 /* interrupt */ interrupt_gs,
104 /* endpage */ endpage_gs,
105 /* drawbegin */ drawbegin_gs,
106 /* drawraw */ drawraw_gs,
107 /* drawfile */ drawfile_gs,
108 /* drawend */ drawend_gs,
109 /* beginheader */ beginheader_gs,
110 /* endheader */ endheader_gs,
111 /* newdoc */ newdoc_gs
112 };
113
114 static int std_io[2];
115 Pixmap bpixmap;
116
117 #define GS_fd (std_io[0])
118
119 /* some arguments are filled in later */
120 static char arg4[] = "-dDEVICEWIDTH=xxxxxxxxxx";
121 static char arg5[] = "-dDEVICEHEIGHT=xxxxxxxxxx";
122
123 static const char *argv[] = {
124 NULL, NULL, "-dNOPAUSE", "-q", arg4, arg5,
125 "-dDEVICEXRESOLUTION=72",
126 "-dDEVICEYRESOLUTION=72",
127 "-dNOSAFER", "-dNOEPS", NULL, NULL, NULL, NULL, NULL, NULL
128 };
129
130 static unsigned int GS_page_w; /* how big our current page is */
131 static unsigned int GS_page_h;
132 static Boolean GS_alpha; /* remember if we are using the alpha driver */
133 static unsigned long GS_mag; /* magnification currently in use */
134 static int GS_shrink; /* shrink factor currently in use */
135 static Boolean GS_active; /* if we've started a page yet */
136 static int GS_pending; /* number of ack's we're expecting */
137 static char GS_outb[257]; /* circular output buffer */
138 static char *GS_outb_in; /* next position in output buffer */
139 static char *GS_outb_out; /* next byte to come out of buffer */
140 #define GS_outb_limit (GS_outb + sizeof GS_outb) /* last+1 byte */
141 static int GS_write_ack; /* flag to set when done writing */
142 static Boolean GS_in_header; /* if we're sending a header */
143 static Boolean GS_in_doc; /* if we've sent header information */
144 static Boolean GS_page_dirty = False; /* if we've drawn since last erase */
145 static int GS_ev_mask; /* events for which we'll stop */
146 static int GS_die_ack = 0; /* flags to set when GS dies */
147 static Boolean GS_timer_set; /* if there's a timer set */
148
149 #define GS_MASK_NORMAL EV_GE_NEWPAGE
150 #define GS_MASK_HEADER EV_GE_PS_TOGGLE
151 #define GS_MASK_INIT (EV_GE_TERM | EV_PS_TOGGLE)
152
153 static Atom gs_atom;
154 static Atom gs_colors_atom;
155
156 #define Landscape 90
157
158 #define LINELEN 81
159 static char line[LINELEN + 1];
160 static char *linepos = line;
161 static char ackstr[] = "\347\310\376";
162
163 static void gs_died(int, struct xchild *);
164
165 static char *read_from_gs(int, void *);
166 static void write_to_gs(int, void *);
167
168 static struct xio gs_xio = {NULL, 0, XIO_IN,
169 #if HAVE_POLL
170 NULL,
171 #endif
172 read_from_gs, write_to_gs,
173 NULL /* data */
174 };
175
176 static struct xchild gs_child = { NULL, 0, NULL, NULL, NULL, SIGKILL, gs_died };
177 #define GS_pid (gs_child.pid)
178
179 /* It seems that XtTimers don't work reliably with xdvi's event treatment;
180 so use custom timers for the time being. Search for TIMER_PROBLEM_FIXED
181 to locate the relevant code parts.
182 */
183
184 #if TIMER_PROBLEM_FIXED
185 static XtIntervalId gs_timeout_id = 0;
186 static void gs_timer_proc(XtPointer client_data, XtIntervalId * id);
187 static struct xtimer gs_timer = {NULL, {0, 0}, gs_timer_proc, NULL
188 #if XDVI_XT_TIMER_HACK
189 , NULL, NULL
190 #endif
191 };
192
193 #else
194 static void gs_alarm(struct xtimer *this, void *data);
195 static struct xtimer gs_timer = {NULL, {0, 0}, XTM_DEFAULT, gs_alarm, NULL
196 #if XDVI_XT_TIMER_HACK
197 , NULL, NULL
198 #endif
199 };
200 #endif
201
202
203 static void
204 showto(char *q)
205 {
206 char *p = line;
207 char *p1;
208
209 while (p < q) {
210 p1 = memchr(p, '\n', q - p);
211 if (p1 == NULL)
212 p1 = q;
213 *p1 = '\0';
214 printf("gs: %s\n", p);
215 p = p1 + 1;
216 }
217 }
218
219 static char *
220 read_from_gs(int fd, void *data)
221 {
222 int bytes;
223 char *line_end = NULL;
224 char *p;
225
226 UNUSED(data);
227
228 for (;;) {
229
230 bytes = read(fd, linepos, line + LINELEN - linepos);
231 if (bytes < 0) {
232 if (AGAIN_CONDITION)
233 break;
234 perror("xdvik: read_from_gs");
235 break;
236 }
237 line_end = linepos + bytes;
238
239 if (bytes == 0) {
240 if (GS_pid != 0)
241 XDVI_WARNING((stderr, "Read_from_gs returned 0 bytes"));
242 break;
243 }
244
245 /* Check for ack strings */
246 for (p = line; p < line_end - 2; ++p) {
247 p = memchr(p, '\347', line_end - p - 2);
248 if (p == NULL) break;
249 if (memcmp(p, ackstr, 3) == 0) {
250 --GS_pending;
251 if (GS_pending == 0)
252 globals.ev.flags |= EV_ACK;
253 if (globals.debug & DBG_PS)
254 printf("Got GS ack; %d pending.\n", GS_pending);
255 } else
256 continue;
257
258 showto(p);
259 p += 3;
260 memmove(line, p, line_end - p);
261 line_end -= p - line;
262 linepos = p = line;
263 --p;
264 }
265 *line_end = '\0';
266 p = strrchr(linepos, '\n');
267 if (p != NULL) {
268 ++p;
269 showto(p);
270 memmove(line, p, line_end - p);
271 line_end -= p - line;
272 }
273 linepos = line_end;
274 /*
275 * Normally we'd hold text until a newline character, but the
276 * buffer is full. So we flush it, being careful not to cut up an
277 * ack string.
278 */
279 if (linepos >= line + LINELEN) {
280 p = line + LINELEN;
281 if ((*--p != '\347' && *--p != '\347' && *--p != '\347')
282 || memcmp(p, ackstr, line + LINELEN - p) != 0)
283 p = line + LINELEN;
284 *p = '\0';
285 printf("gs: %s\n", line);
286 *p = '\347';
287 linepos = line;
288 while (p < line + LINELEN)
289 *linepos++ = *p++;
290 }
291 }
292 return line_end; /* dummy */
293 }
294
295 static void
296 write_to_gs(int fd, void *data)
297 {
298 char *send_end;
299 int bytes;
300
301 UNUSED(fd);
302 UNUSED(data);
303
304 for (;;) {
305 send_end = GS_outb_in;
306 if (send_end < GS_outb_out)
307 send_end = GS_outb_limit;
308 bytes = write(GS_fd, GS_outb_out, send_end - GS_outb_out);
309
310 if (bytes < 0) {
311 if (AGAIN_CONDITION)
312 break;
313 perror("xdvik: write_to_gs");
314 break;
315 }
316
317 GS_outb_out += bytes;
318 if (GS_outb_out == GS_outb_limit)
319 GS_outb_out = GS_outb;
320 if (GS_outb_out == GS_outb_in) { /* if buffer is empty */
321 gs_xio.xio_events = XIO_IN;
322 #if HAVE_POLL
323 if (gs_xio.pfd != NULL) /* write_to_gs is called directly */
324 gs_xio.pfd->events = XIO_IN;
325 #endif
326 break;
327 }
328 }
329 globals.ev.flags |= GS_write_ack;
330 GS_write_ack = 0;
331 }
332
333 /*
334 * Main routine for writing to the GS interpreter.
335 */
336
337 static void
338 gs_send(const char *cp, size_t len)
339 {
340 const char *cp_end = cp + len;
341 char *send_end;
342 size_t bytes;
343 char *old_out;
344 Boolean interrupting;
345
346 if (GS_pid == 0 || (globals.ev.flags & GS_ev_mask))
347 return;
348
349 /*
350 * Because cp might reside on the stack, don't return until we've
351 * copied all of it to our circular output buffer.
352 * Note that GS_outb_out == GS_outb_in means that the buffer is empty.
353 */
354
355 GS_timer_set = interrupting = False;
356 for (;;) {
357 send_end = GS_outb_out;
358 if (send_end == GS_outb)
359 send_end = GS_outb_limit;
360 --send_end;
361 if (send_end < GS_outb_in)
362 send_end = GS_outb_limit;
363 bytes = send_end - GS_outb_in;
364 if (bytes > 0) {
365 if (bytes >= (unsigned)(cp_end - cp))
366 bytes = cp_end - cp;
367 memcpy(GS_outb_in, cp, bytes);
368 cp += bytes;
369 GS_outb_in += bytes;
370 if (GS_outb_in == GS_outb_limit)
371 GS_outb_in = GS_outb;
372 if (cp < cp_end)
373 continue;
374 }
375
376 /* The buffer is now full --or-- we've run out of data */
377 old_out = GS_outb_out;
378 if (!(gs_xio.xio_events & XIO_OUT)) { /* restart output */
379 gs_xio.xio_events = XIO_IN | XIO_OUT;
380 #if HAVE_POLL
381 if (gs_xio.pfd != NULL)
382 gs_xio.pfd->events = POLLIN | POLLOUT;
383 #endif
384 write_to_gs(GS_fd, NULL);
385 if (GS_outb_out != old_out) {
386 if (cp == cp_end)
387 break;
388 else
389 continue;
390 }
391 }
392
393 if (cp == cp_end)
394 break;
395
396 GS_die_ack = GS_write_ack = EV_ACK;
397 for (;;) { /* loop because there may be stray ACKs */
398 if (!interrupting) {
399 (void) read_events(GS_ev_mask | EV_ACK);
400 globals.ev.flags &= ~EV_ACK;
401
402 if (GS_pid == 0) { /* if GS died */
403 GS_die_ack = 0;
404 return;
405 }
406
407 if (GS_outb_out != old_out) /* if more room in buffer */
408 break;
409
410 if (globals.ev.flags & GS_ev_mask) { /* if a serious event */
411 if (globals.debug & DBG_PS)
412 puts("Setting timeout in gs_send()");
413
414 set_timer(&gs_timer, resource.gs_timeout);
415 GS_timer_set = interrupting = True;
416 }
417 }
418 else {
419 (void) read_events(EV_GE_TERM | EV_PS_TOGGLE | EV_ACK);
420 globals.ev.flags &= ~EV_ACK;
421
422 if (GS_outb_out != old_out) /* if more room in buffer */
423 break;
424
425 if (GS_timer_set) /* if timer still set */
426 cancel_timer(&gs_timer);
427
428 destroy_gs();
429 GS_die_ack = 0;
430 return;
431 }
432 }
433 }
434
435 if (GS_timer_set) /* if timer still set */
436 cancel_timer(&gs_timer);
437
438 GS_die_ack = GS_write_ack = 0;
439 }
440
441 static void
442 #if TIMER_PROBLEM_FIXED
443 gs_timer_proc(XtPointer client_data, XtIntervalId * id)
444 #else
445 gs_alarm(struct xtimer *this, void *data)
446 #endif
447 {
448 UNUSED(this);
449 UNUSED(data);
450
451 if (globals.debug & DBG_PS)
452 puts("GS timeout expired");
453
454 globals.ev.flags |= EV_ACK;
455 GS_timer_set = False;
456 #if TIMER_PROBLEM_FIXED
457 gs_timeout_id = 0;
458 #endif
459 }
460
461 /*
462 * Wait for acknowledgement from GS.
463 */
464
465 static void
466 waitack(void)
467 {
468 if (GS_pending == 0) {
469 globals.ev.flags &= ~EV_ACK;
470 return;
471 }
472
473 GS_die_ack = EV_ACK;
474
475 for (;;) { /* loop because there might be stray ACKs. */
476 /* fprintf(stderr, "looping for stray ACKs, page %d\n", current_page); */
477 (void) read_events(EV_GE_ACK);
478 globals.ev.flags &= ~EV_ACK;
479
480 if (GS_pending == 0) {
481 GS_die_ack = 0;
482 return;
483 }
484 if (globals.ev.flags & EV_GE_ACK)
485 break;
486 }
487
488 if (globals.debug & DBG_PS)
489 puts("Setting timeout in waitack()");
490
491 #if TIMER_PROBLEM_FIXED
492 if (gs_timeout_id)
493 XtRemoveTimeOut(gs_timeout_id);
494 gs_timeout_id = XtAppAddTimeOut(globals.app, resource.gs_timeout,
495 gs_timer_proc, (XtPointer) NULL);
496 #else
497 set_timer(&gs_timer, resource.gs_timeout);
498 #endif
499 GS_timer_set = True;
500
501 (void) read_events(EV_GE_TERM | EV_PS_TOGGLE | EV_ACK);
502 globals.ev.flags &= ~EV_ACK;
503
504 if (GS_timer_set) {
505 #if TIMER_PROBLEM_FIXED
506 XtRemoveTimeOut(gs_timeout_id);
507 gs_timeout_id = 0;
508 #else
509 cancel_timer(&gs_timer);
510 #endif
511 }
512 GS_die_ack = 0;
513
514 if (GS_pending > 0)
515 destroy_gs();
516 }
517
518
519 /*
520 * Fork a process to run ghostscript. This is done using the
521 * x11 device (which needs to be compiled in). Normally the x11
522 * device uses ClientMessage events to communicate with the calling
523 * program, but we don't do this. The reason for using the ClientMessage
524 * events is that otherwise ghostview doesn't know when a non-conforming
525 * postscript program calls showpage. That doesn't affect us here,
526 * since in fact we disable showpage.
527 *
528 * SAFER mode is handled by providing both the -dNOSAFER and -dSAFER
529 * options. Ghostscript versions 7.04 and earlier ignore -dNOSAFER and use
530 * -dSAFER; the code in strsafe is ignored since .locksafe is not present.
531 * In versions 7.04 and higher, -dNOSAFER overrides -dSAFER; SAFER mode is
532 * optionally turned on by sending the strsafe string. It is possible in some
533 * versions of gs prior to 7.04 to use -dDELAYSAFER instead of -dNOSAFER, but
534 * there's no point in doing that since .locksafe is not defined in those
535 * versions. I don't know where 7.03 fits in on all of this (but it works with
536 * that version as well).
537 */
538
539 Boolean
540 initGS(void)
541 {
542 char buf[100];
543 static Boolean did_putenv = False;
544 /*
545 * This string reads chunks (delimited by %%xdvimark).
546 * The first character of a chunk tells whether a given chunk
547 * is to be done within save/restore or not.
548 * The `H' at the end tells it that the first group is a
549 * header; i.e., no save/restore.
550 * `execute' is unique to ghostscript.
551 */
552
553 static const char strsafe[] =
554 "{ << /PermitFileReading [ (*) ] /PermitFileWriting [ ] /PermitFileControl [ ] "
555 ">> setuserparams .locksafe "
556 "} stopped pop\n";
557 static const char str1[] =
558 "/xdvi$run "
559 "{$error /newerror false put currentfile cvx stopped {handleerror} if} "
560 "def "
561 "/xdvi$ack (\347\310\376) def "
562 "/xdvi$dslen countdictstack def "
563 "{currentfile read pop 72 eq "
564 "{xdvi$run} "
565 "{/xdvi$sav save def xdvi$run "
566 "clear countdictstack xdvi$dslen sub {end} repeat xdvi$sav restore} "
567 "ifelse "
568 "{(%%xdvimark) currentfile =string {readline} stopped "
569 "{clear} {pop eq {exit} if} ifelse }loop "
570 "flushpage xdvi$ack print flush "
571 "}loop\nH";
572
573 static const char str2[] =
574 "[0 1 1 0 0 0] concat\n"
575 "stop\n%%xdvimark\n";
576
577 /*
578 * If we're prescanning *before* setting up the widgets (to get the
579 * page size, for example), then postpone starting up ghostscript.
580 */
581 if (mane.win == (Window)0) {
582 if (globals.debug & DBG_PS)
583 puts("Hit PS header in early prescan; postponing.");
584 psp = no_ps_procs;
585 gs_postpone_prescan = True;
586 return True;
587 }
588
589 if (globals.debug & DBG_PS)
590 puts("Running initGS ...");
591
592 gs_atom = XInternAtom(DISP, "GHOSTVIEW", False);
593 /* send bpixmap, orientation, bbox (in pixels), and h & v resolution */
594 sprintf(buf, "%ld %d 0 0 %u %u 72 72",
595 bpixmap, /* bpixmap */
596 Landscape, /* orientation */
597 GS_page_h = globals.page.h, GS_page_w = globals.page.w);
598
599 XChangeProperty(DISP, mane.win, gs_atom, XA_STRING, 8,
600 PropModeReplace, (unsigned char *)buf, strlen(buf));
601 GS_alpha = resource.gs_alpha;
602
603 gs_colors_atom = XInternAtom(DISP, "GHOSTVIEW_COLORS", False);
604 sprintf(buf, "%s %ld %ld", resource.gs_palette,
605 color_data[0].pixel, color_data[1].pixel);
606
607 XChangeProperty(DISP, mane.win, gs_colors_atom, XA_STRING, 8,
608 PropModeReplace, (unsigned char *)buf, strlen(buf));
609
610 if (!did_putenv) {
611 sprintf(buf, "%ld", mane.win);
612 xputenv("GHOSTVIEW", buf);
613 did_putenv = True;
614 }
615
616 XSync(DISP, False); /* update the window */
617
618 if (xpipe(std_io) != 0) {
619 perror("[xdvik] pipe");
620 return False;
621 }
622 fflush(stderr); /* to avoid double flushing */
623 GS_pid = vfork();
624 if (GS_pid == 0) { /* child */
625 const char **argvp = argv + 10;
626
627 argv[1] = resource.gs_alpha ? "-sDEVICE=x11alpha" : "-sDEVICE=x11";
628 sprintf(arg4 + 14, "%u", GS_page_w);
629 sprintf(arg5 + 15, "%u", GS_page_h);
630 if (resource.gs_safer)
631 *argvp++ = "-dSAFER";
632
633 #if 0
634 if (resource.gs_alpha) {
635 *argvp++ = "-dGraphicsAlphaBits=4";
636 *argvp++ = "-dTextAlphaBits=4";
637 *argvp++ = "-dMaxBitmap=0";
638 }
639 #endif
640
641 *argvp = "-";
642 (void) close(std_io[0]);
643 (void) dup2(std_io[1], 0);
644 (void) dup2(std_io[1], 1);
645 (void) dup2(std_io[1], 2);
646 (void) close(std_io[1]);
647
648 (void)execvp(argv[0] = resource.gs_path, (char *const *)argv);
649 /*TODO: use fork_process here?? */
650 XDVI_ERROR((stderr, "Execvp of %s failed: %s", argv[0], strerror(errno)));
651 _exit(EXIT_FAILURE);
652 }
653
654 (void)close(std_io[1]);
655
656 if (GS_pid == -1) { /* error */
657 GS_pid = 0;
658 perror("[xdvik] vfork");
659 (void)close(GS_fd);
660
661 return False;
662 }
663
664 prep_fd(GS_fd, True); /* Set file descriptor for non-blocking I/O */
665
666 gs_child.name = xstrdup("gs");
667 gs_child.io = &gs_xio;
668 set_chld(&gs_child);
669
670 psp = gs_procs;
671 GS_active = False;
672 GS_in_header = True;
673 GS_page_dirty = False;
674 GS_pending = 1;
675 GS_mag = GS_shrink = -1;
676 gs_xio.fd = GS_fd;
677 gs_xio.xio_events = XIO_IN;
678 GS_write_ack = 0;
679 GS_outb_in = GS_outb_out = GS_outb;
680 set_io(&gs_xio);
681 GS_ev_mask = GS_MASK_INIT;
682 (void) signal(SIGPIPE, SIG_IGN);
683
684 if (resource.gs_safer)
685 gs_send(strsafe, (sizeof strsafe) - 1);
686 gs_send(str1, (sizeof str1) - 1);
687 gs_send(psheader, psheaderlen);
688 gs_send(str2, (sizeof str2) - 1);
689 waitack();
690 GS_in_header = False;
691 GS_ev_mask = GS_MASK_NORMAL;
692
693 if (GS_pid == 0) { /* if something happened */
694 destroy_gs();
695 return False;
696 }
697 if (resource.postscript == 0)
698 toggle_gs(0); /* if we got a 'v' already */
699 else {
700 scanned_page = scanned_page_ps = scanned_page_reset;
701 globals.ev.flags |= EV_NEWPAGE; /* ||| redraw the page */
702 longjmp(globals.ev.canit, 1);
703 }
704 return True;
705 }
706
707 static void
708 toggle_gs(int flag) /* this routine is callable from within read_events(). */
709 {
710 if (globals.debug & DBG_PS)
711 fprintf(stdout, "Toggling GS to %d", flag);
712
713 switch (flag) {
714 case 0:
715 psp.drawbegin = drawbegin_none;
716 break;
717 case 1:
718 psp.drawbegin = drawbegin_gs;
719 break;
720 default:
721 psp.drawbegin = drawbegin_gs_box;
722 break;
723 }
724 }
725
726 void
727 gs_resume_prescan(void)
728 {
729 if (globals.debug & DBG_PS)
730 puts("Resuming prescan");
731
732 gs_postpone_prescan = False;
733 if (!initGS()) /* this may not return */
734 psp = no_ps_procs;
735 }
736
737 void
738 gs_erase_page(void)
739 {
740 static const char str[] = " erasepage stop\n%%xdvimark\n";
741
742 if (!GS_page_dirty) return;
743
744 if (globals.debug & DBG_PS)
745 puts("Erasing gs page");
746
747 if (GS_active)
748 XDVI_FATAL((stderr, "Internal error in gs_erase_page()."));
749
750 ++GS_pending;
751 gs_send(str, sizeof(str) - 1);
752 waitack();
753 }
754
755 static void
756 gs_died(int status, struct xchild *child)
757 {
758 UNUSED(status);
759 if (globals.debug & DBG_PS)
760 fprintf(stderr, "process %s died\n", child->name);
761 GS_pid = 0;
762 (child->io->read_proc)(child->io->fd, NULL);
763 if (linepos > line) {
764 *linepos = '\0';
765 printf("%s: %s\n", child->name, line);
766 linepos = line;
767 }
768 clear_io(child->io);
769 (void)close(child->io->fd);
770
771 scanned_page = scanned_page_ps = scanned_page_reset;
772 GS_active = GS_in_doc = GS_page_dirty = False;
773 GS_pending = 0;
774 globals.ev.flags |= GS_die_ack;
775 }
776
777 static void
778 destroy_gs(void)
779 {
780 if (globals.debug & DBG_PS)
781 puts("Destroying GS process");
782 if (GS_pid != 0) {
783 if (kill(GS_pid, SIGKILL) < 0 && errno != ESRCH)
784 perror("xdvik: destroy_gs");
785 GS_pid = 0;
786 clear_chld(&gs_child);
787 read_from_gs(GS_fd, NULL);
788 if (linepos > line) {
789 *linepos = '\0';
790 printf("gs: %s\n", line);
791 linepos = line;
792 }
793 clear_io(&gs_xio);
794 (void) close(GS_fd);
795
796 scanned_page = scanned_page_ps = scanned_page_reset;
797 }
798 GS_active = GS_in_doc = GS_page_dirty = False;
799 GS_pending = 0;
800 }
801
802 static void
803 deactivate(void)
804 {
805 static const char str[] = " stop\n%%xdvimark\n";
806 int saved_mask;
807
808 saved_mask = GS_ev_mask;
809 GS_ev_mask = 0;
810 gs_send(str, (sizeof str) - 1);
811 GS_ev_mask = saved_mask;
812
813 GS_active = False;
814 }
815
816 static void
817 interrupt_gs(void)
818 {
819 if (globals.debug & DBG_PS)
820 puts("Running interrupt_gs()");
821 /*
822 FIXME: added this special case, since otherwise EV_ACK might not get
823 reset at all, and hang xdvi forever when scrolling quickly through
824 a file that should be reloaded.
825 */
826 if (GS_pending == 0) {
827 /* fprintf(stderr, "+++++++++ 1st case; waitack: %d\n", globals.ev.flags & EV_ACK); */
828 globals.ev.flags &= ~EV_ACK;
829 return;
830 }
831 else if (GS_pending < 0) {
832 /* fprintf(stderr, "GS_pending: %d; waitack: %d\n", GS_pending, globals.ev.flags & EV_ACK); */
833 return; /* nothing to do */
834 }
835
836 /*
837 * ||| what I'd really like to do here is cause gs to execute
838 * the interrupt routine in errordict. But so far (gs 2.6.1)
839 * that has not been implemented in ghostscript.
840 */
841
842 if (GS_active)
843 deactivate();
844 waitack();
845 }
846
847 static void
848 endpage_gs(void)
849 {
850 if (globals.debug & DBG_PS)
851 puts("Running endpage_gs()");
852 if (GS_active) {
853 deactivate();
854 waitack();
855 }
856 }
857
858 /*
859 * Checks that the GS interpreter is running correctly.
860 */
861
862 static void
863 checkgs(Boolean in_header)
864 {
865 char buf[150];
866
867 /*
868 * For geometry changes, we pretty much have to restart Ghostscript.
869 * This is what Ghostview does (for example, in gv-3.7.4
870 * this occurs in Setup() in Ghostview.c).
871 */
872 if (globals.page.w > GS_page_w || globals.page.h > GS_page_h
873 || GS_alpha != resource.gs_alpha)
874 destroy_gs();
875
876 if (GS_pid == 0)
877 (void)initGS();
878
879 if (!GS_active) {
880 if (magnification != GS_mag) {
881 if (globals.ev.flags & GS_ev_mask)
882 longjmp(globals.ev.canit, 1);
883 ++GS_pending;
884 sprintf(buf,
885 "H TeXDict begin /DVImag %ld 1000 div def end stop\n"
886 "%%%%xdvimark\n",
887 GS_mag = magnification);
888 gs_send(buf, strlen(buf));
889 }
890
891 if (mane.shrinkfactor != GS_shrink) {
892 if (globals.ev.flags & GS_ev_mask)
893 longjmp(globals.ev.canit, 1);
894 ++GS_pending;
895 sprintf(buf,
896 "H TeXDict begin %d %d div dup /Resolution X /VResolution X end stop\n"
897 "%%%%xdvimark\n",
898 resource.pixels_per_inch,
899 GS_shrink = mane.shrinkfactor);
900 gs_send(buf, strlen(buf));
901 }
902 }
903 }
904
905 static void
906 drawbegin_gs(int xul, int yul, const char *cp)
907 {
908 char buf[32];
909 static const char str[] = " TeXDict begin\n";
910
911 checkgs(False);
912
913 if (!GS_active) {
914 if (globals.ev.flags & GS_ev_mask)
915 longjmp(globals.ev.canit, 1);
916 ++GS_pending;
917 gs_send(str, (sizeof str) - 1);
918 GS_active = True;
919 }
920
921 /* This allows the X side to clear the page */
922 XSync(DISP, False);
923
924 sprintf(buf, "%d %d moveto\n", xul, yul);
925 gs_send(buf, strlen(buf));
926 /* gs_send(clear_bg, strlen(clear_bg)); */
927 if (globals.debug & DBG_PS)
928 printf("drawbegin at %d,%d: sending `%s'\n", xul, yul, cp);
929
930 /*
931 * added SU 2000/12/18:
932 * Try to detect some simple PS rotating commands, and warn about them.
933 * There are surely more than that ...
934 */
935 if (strstr(cp, "rotate") != NULL /* used by graphics.sty */
936 || strstr(cp, "RotBegin") != NULL /* used by pstricks */
937 ) {
938 statusline_error(STATUS_SHORT,
939 "Warning: PS code on page %d may contain rotation, "
940 "which is not supported by xdvi", current_page + 1);
941 }
942
943 gs_send(cp, strlen(cp));
944 }
945
946 static void
947 drawbegin_gs_box(int xul, int yul, const char *cp)
948 {
949 drawbegin_gs(xul, yul, cp);
950 }
951
952
953 void
954 drawraw_gs(const char *cp)
955 {
956 if (!GS_active)
957 return;
958 if (globals.debug & DBG_PS)
959 printf("raw ps sent to context: %s\n", cp);
960 GS_page_dirty = True;
961 gs_send(cp, strlen(cp));
962 gs_send("\n", 1);
963 }
964
965 static void
966 drawfile_gs(const char *cp, FILE *f)
967 {
968 char canonical_path[MAXPATHLEN + 1];
969 char *ret;
970
971 fclose(f); /* don't need it */
972
973 if (!GS_active)
974 return;
975
976 if (globals.debug & DBG_PS)
977 printf("original path: |%s|\n", cp);
978 /* drawraw_gs("newpath 0 0 moveto 0 1000 rlineto 1000 0 rlineto 0 -1000 rlineto closepath 1 setgray fill"); */
979 #if 0
980 /* if expand_symlinks or remove_dots from kpathsea were public,
981 we could use the following: */
982 ret = remove_dots(expand_symlinks(cp));
983 #endif
984
985 ret = REALPATH(cp, canonical_path);
986 if (ret == NULL)
987 XDVI_WARNING((stderr, "Couldn't canonicalize path \"%s\": %s. Sending to gs unchanged.",
988 cp, strerror(errno)));
989 else
990 cp = canonical_path;
991
992 if (globals.debug & DBG_PS)
993 printf("expanded path: |%s|\n", cp);
994
995 GS_page_dirty = True;
996 gs_send("(", 1);
997 gs_send(cp, strlen(cp));
998 gs_send(")run\n", 5);
999 /* { */
1000 /* char *clear_bg = "newpath 0 0 moveto 0 1000 rlineto 1000 0 rlineto 0 -1000 rlineto closepath .4 setgray fill\n"; */
1001 /* gs_send(clear_bg, strlen(clear_bg)); */
1002 /* } */
1003 }
1004
1005 static void
1006 drawend_gs(const char *cp)
1007 {
1008 if (!GS_active)
1009 return;
1010 if (globals.debug & DBG_PS)
1011 printf("end ps: %s\n", cp);
1012 gs_send(cp, strlen(cp));
1013 gs_send("\n", 1);
1014 save_bbox();
1015 }
1016
1017 static void
1018 beginheader_gs(void)
1019 {
1020 static const char str[] = "Hsave /xdvi$doc exch def\n";
1021
1022 if (globals.debug & DBG_PS)
1023 puts("Running beginheader_gs()");
1024
1025 checkgs(True);
1026
1027 if (GS_active) {
1028 if (!GS_in_header)
1029 XDVI_FATAL((stderr, "Internal error in beginheader_gs()."));
1030 return;
1031 }
1032
1033 if (globals.ev.flags & GS_ev_mask) {
1034 /* fprintf(stderr, "longjmp!"); */
1035 longjmp(globals.ev.canit, 1);
1036 }
1037
1038 GS_in_header = True;
1039 GS_ev_mask = GS_MASK_HEADER;
1040 ++GS_pending;
1041 if (GS_in_doc)
1042 gs_send("H", 1);
1043 else {
1044 gs_send(str, (sizeof str) - 1);
1045 GS_in_doc = True;
1046 }
1047 GS_active = True;
1048 }
1049
1050 static void
1051 endheader_gs(void)
1052 {
1053 if (globals.debug & DBG_PS)
1054 puts("Running endheader_gs()");
1055
1056 if (GS_active) {
1057 deactivate();
1058 waitack();
1059 GS_in_header = False;
1060 GS_ev_mask = GS_MASK_NORMAL;
1061 }
1062 }
1063
1064 static void
1065 newdoc_gs(void)
1066 {
1067 static const char str[] = "Hxdvi$doc restore stop\n%%xdvimark\n";
1068
1069 if (globals.debug & DBG_PS)
1070 puts("Running newdoc_gs()");
1071
1072 if (GS_in_doc) {
1073 ++GS_pending;
1074 gs_send(str, (sizeof str) - 1);
1075 GS_mag = GS_shrink = -1;
1076 GS_in_doc = False;
1077
1078 GS_page_w = GS_page_h = 0;
1079 }
1080 }
1081
1082 #else
1083 /* silence `empty compilation unit' warnings */
1084 static void bar(void); static void foo(void) { bar(); } static void bar(void) { foo(); }
1085 #endif /* PS_GS */