Debian Codegraph @

texk/xdvik/dvi-init.c

raw
1 /*========================================================================*\
2
3 Copyright (c) 1990-2022 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 NOTE:
24 xdvi is based on prior work, as noted in the modification history
25 in xdvi.c.
26
27 \*========================================================================*/
28
29 #include "xdvi-config.h"
30 #include "xdvi.h"
31
32 #include "dvi-init.h"
33 #include "dvi-draw.h"
34 #include "util.h"
35 #include "x_util.h"
36 #include "exit-handlers.h"
37 #include "mime.h"
38 #include "pagesel.h"
39 #include "special.h"
40 #include "hypertex.h"
41 #include "kpathsea/c-fopen.h"
42 #include "kpathsea/c-stat.h"
43 #include "kpathsea/magstep.h"
44 #include "kpathsea/tex-glyph.h"
45 #include "dvi.h"
46 #include "string-utils.h"
47 #include "browser.h"
48 #include "sfSelFile.h"
49 #include "xm_toolbar.h"
50 #include "pagehist.h"
51 #include "message-window.h"
52 #include "search-internal.h"
53 #include "statusline.h"
54 #include "events.h"
55 #include "font-open.h"
56
57 #if FREETYPE
58 # include FT_SIZES_H
59 #endif
60
61 #define PK_PRE 247
62 #define PK_ID 89
63 #define PK_MAGIC ((PK_PRE << 8) | PK_ID)
64 #define GF_PRE 247
65 #define GF_ID 131
66 #define GF_MAGIC ((GF_PRE << 8) | GF_ID)
67 #define VF_PRE 247
68 #define VF_ID_BYTE 202
69 #define VF_MAGIC ((VF_PRE << 8) | VF_ID_BYTE)
70
71 /* font stuff */
72 struct font *tn_table[TNTABLELEN];
73 struct font *font_head = NULL;
74 struct tn *tn_head = NULL;
75 wide_ubyte maxchar;
76 unsigned short current_timestamp = 0;
77
78
79 unsigned long magnification;
80 double dimconv;
81 double tpic_conv;
82
83 /* Curently processed page number (starting at 0). */
84 int current_page = 0;
85 int total_pages = 0;
86
87 /* postamble offset is saved in this global variable */
88 long g_postamble_offset;
89
90
91 static struct stat fstatbuf;
92
93 static FILE *m_dvi_fp = NULL; /* original user's file */
94
95
96 static Boolean open_dvi_file(const char *filename, Boolean open_new_instance);
97
98 /*
99 * DVI preamble and postamble information.
100 */
101 static unsigned long numerator, denominator;
102 static unsigned int dvi_unshrunk_page_w, dvi_unshrunk_page_h;
103 static unsigned int m_paper_unshrunk_w, m_paper_unshrunk_h;
104
105
106 /*
107 * Offset in DVI file of last page, set in read_postamble().
108 */
109 static long m_last_page_offset;
110
111 static const char *dvi_err_list[] = {
112 /* NO_ERROR */ "No Error",
113 /* WRONG_DVI_VERSION */ "Wrong version of DVI output for this program",
114 /* DVI_CORRUPTED */ "DVI file corrupted",
115 /* NOT_A_DVI_FILE */ "Not a DVI file",
116 /* POSTAMBLE_NO_POST */ "Postamble doesn't begin with POST",
117 /* POSTAMBLE_NO_MATCH */ "Postamble doesn't match preamble",
118 /* POSTAMBLE_NON_FNTDEF */ "Non-fntdef command found in postamble",
119 /* NOT_ALL_PIXEL_FILES_FOUND */ "Not all pixel files were found",
120 /* NO_BOP_AT_PAGEDESC */ "Page description doesn't begin with BOP",
121 /* FILE_HAS_ZERO_SIZE */ "File has zero size",
122 /* FILE_DOESNT_EXIST */ "No such file",
123 /* FILE_IS_DIRECTORY */ "Is a directory",
124 /* UNKNOWN_ERROR */ "An unknown error occurred"
125 };
126
127 /*
128 * access method for above list
129 */
130 const char *
131 get_dvi_error(dviErrFlagT flag) {
132 ASSERT(flag < XtNumber(dvi_err_list), "Flag out of range");
133 return dvi_err_list[flag];
134 }
135
136
137 /*
138 * Extract the unit used in paper size specification. This information is used
139 * to decide the initial grid separation.
140 */
141 static int
142 atopixunit(const char *arg)
143 {
144 int len = strlen(arg);
145
146 /* check if the unit 'mm' or 'cm' occurs in the arg string */
147 return (len > 2 && (arg[len - 2] == 'c' || arg[len - 2] == 'm') && arg[len - 1] == 'm' ?
148 1.0 / 2.54 : 1.0) * resource.pixels_per_inch + 0.5;
149 }
150
151 /*
152 * free_vf_chain frees the vf_chain structure.
153 */
154
155 static void
156 free_vf_chain(struct tn *tnp)
157 {
158 while (tnp != NULL) {
159 struct tn *tnp1 = tnp->next;
160 free((char *)tnp);
161 tnp = tnp1;
162 }
163 }
164
165 /*
166 * delete glyph information in a font.
167 */
168
169 static void
170 delete_glyphs(struct font *fontp)
171 {
172 struct glyph *g;
173
174 for (g = fontp->glyph; g <= fontp->glyph + fontp->maxchar; ++g) {
175 if (g->bitmap2.bits) {
176 free(g->bitmap2.bits);
177 g->bitmap2.bits = NULL;
178 }
179 #ifdef GREY
180 if (g->pixmap2) {
181 XDestroyImage(g->image2);
182 g->pixmap2 = NULL;
183 if (g->pixmap2_gc2 != NULL) {
184 free(g->pixmap2_gc2);
185 g->pixmap2_gc2 = NULL;
186 }
187 }
188 #if COLOR
189 g->fg = NULL;
190 #endif
191 #endif
192 }
193 }
194
195 /*
196 * Release all shrunken bitmaps for all fonts.
197 */
198
199 void
200 reset_fonts(void)
201 {
202 struct font *f;
203
204 for (f = font_head; f != NULL; f = f->next) {
205 if ((f->flags & FONT_LOADED) && !(f->flags & FONT_VIRTUAL)) {
206 delete_glyphs(f);
207 }
208 }
209 }
210
211 /*
212 * free up fonts no longer in use.
213 */
214 static void
215 free_unused_fonts(void)
216 {
217 struct font *fontp;
218 struct font **fontpp;
219
220 fontpp = &font_head;
221 while ((fontp = *fontpp) != NULL) {
222 if (fontp->flags & FONT_IN_USE)
223 fontpp = &fontp->next;
224 else {
225 if (globals.debug & DBG_PK)
226 printf("xdvi: Discarding font \"%s\" at %d dpi\n",
227 fontp->fontname, (int)(fontp->fsize + 0.5));
228 *fontpp = fontp->next; /* remove from list */
229 free(fontp->fontname);
230 if (fontp->flags & FONT_LOADED) {
231 #if FREETYPE
232 if (fontp->ft != NULL) { /* if FreeType font */
233 struct ftfont *ft;
234
235 ft = fontp->ft;
236 if (fontp->size != NULL)
237 FT_Done_Size(fontp->size);
238 if (fontp == ft->first_size) {
239 if (fontp->next_size == NULL) {
240 /* if this is the only size of this font face */
241 FT_Done_Face(ft->face);
242 ft->t1->ft = NULL;
243 free(ft);
244 }
245 else {
246 struct font *fp2;
247
248 ft->first_size = fp2 = fontp->next_size;
249 fp2->file = fontp->file;
250 fontp->file = NULL;
251 fp2->filename = fontp->filename;
252 fontp->filename = NULL;
253 fp2->timestamp = fontp->timestamp;
254 }
255 }
256 else {
257 struct font *fp2;
258
259 fp2 = ft->first_size;
260 while (fp2->next_size != fontp)
261 fp2 = fp2->next_size;
262 fp2->next_size = fontp->next_size;
263 }
264 }
265 #endif
266 if (fontp->file != NULL) {
267 fclose(fontp->file);
268 }
269 #if FREETYPE
270 if (fontp->filename != NULL)
271 #endif
272 free((char *) fontp->filename);
273
274 if (fontp->flags & FONT_VIRTUAL) {
275 struct macro *m;
276
277 for (m = fontp->macro;
278 m <= fontp->macro + fontp->maxchar; ++m)
279 if (m->free_me) free((char *)m->pos);
280 free((char *)fontp->macro);
281 free((char *)fontp->vf_table);
282 free_vf_chain(fontp->vf_chain);
283 }
284 else {
285 delete_glyphs(fontp);
286 free((char *)fontp->glyph);
287 }
288 free((char *)fontp);
289 }
290 }
291 }
292 }
293
294 #if COLOR
295
296 /*
297 * Release all allocated pixels, and (in greyscale mode) invalidate
298 * all shrunken glyphs.
299 */
300
301 void
302 reset_colors(void)
303 {
304 if (color_list_len != 0) {
305 XFreeColors(DISP, G_colormap, color_list, color_list_len, 0);
306 color_list_len = 0;
307 }
308 while (bg_head != NULL) {
309 struct bgrec *bgp;
310 struct fgrec *fgp;
311
312 for (fgp = bg_head->fg_head; fgp != NULL;) {
313 struct fgrec *fgp1 = fgp->next;
314 free(fgp);
315 fgp = fgp1;
316 }
317 bgp = bg_head->next;
318 free(bg_head);
319 bg_head = bgp;
320 }
321 #if GREY
322 if (resource.use_grey) {
323 struct font *f;
324 struct glyph *g;
325
326 for (f = font_head; f != NULL; f = f->next)
327 if ((f->flags & FONT_LOADED) && !(f->flags & FONT_VIRTUAL))
328 for (g = f->glyph; g <= f->glyph + f->maxchar; ++g)
329 g->fg = NULL;
330 }
331 #endif /* GREY */
332 bg_current = NULL;
333 fg_active = NULL;
334 color_warned = False;
335 }
336
337 /*
338 * All of the above, plus discard all scanned information.
339 */
340
341 void
342 full_reset_colors(void)
343 {
344 if (page_colors.stack != NULL) {
345 size_t i;
346 struct rgb *last_freed = &fg_initial;
347
348 /* fprintf(stderr, "i: %d; last freed: %p\n", page_colors.size, &fg_initial); */
349 for (i = 0; i < page_colors.size; ++i) {
350 if (page_colors.stack[i].colorstack != last_freed) {
351 last_freed = page_colors.stack[i].colorstack;
352 /* BUG ALERT: don't free &fg_initial, else segfault with changing
353 foreground in xm_colorsel.c! */
354 if (last_freed != NULL && last_freed != &fg_initial) {
355 /* fprintf(stderr, "freeing %d: %p\n", i, last_freed); */
356 free(last_freed);
357 }
358 }
359 }
360 free(page_colors.stack);
361 page_colors.stack = NULL;
362 }
363 reset_colors();
364 }
365
366 #endif /* COLOR */
367
368
369
370 /*
371 * realloc_font allocates the font structure to contain (newsize + 1)
372 * characters.
373 */
374
375 void
376 realloc_font(struct font *fontp, wide_ubyte newsize)
377 {
378 struct glyph *glyph;
379
380 glyph = fontp->glyph = xrealloc(fontp->glyph,
381 (unsigned int)(newsize + 1) * sizeof(struct glyph));
382 if (newsize > fontp->maxchar)
383 memset((char *)(glyph + fontp->maxchar + 1), 0,
384 (int)(newsize - fontp->maxchar) * sizeof(struct glyph));
385 maxchar = fontp->maxchar = newsize;
386 }
387
388
389 /*
390 * realloc_virtual_font does the same thing for virtual fonts.
391 */
392
393 void
394 realloc_virtual_font(struct font *fontp, wide_ubyte newsize)
395 {
396 struct macro *macro;
397
398 macro = fontp->macro = xrealloc(fontp->macro,
399 (unsigned int)(newsize + 1) * sizeof(struct macro));
400 if (newsize > fontp->maxchar)
401 memset((char *)(macro + fontp->maxchar + 1), 0,
402 (int)(newsize - fontp->maxchar) * sizeof(struct macro));
403 maxchar = fontp->maxchar = newsize;
404 }
405
406
407 /*
408 * load_font locates the t1 font or raster file and reads the index of
409 * characters, plus whatever other preprocessing is done (depending on
410 * the format).
411 *
412 * Returns True if sucessful, False if not.
413 */
414
415 Boolean
416 load_font(struct font *fontp
417 #if DELAYED_MKTEXPK
418 , Boolean load_font_now
419 #endif
420 )
421 {
422 double fsize = fontp->fsize;
423 int dpi = fsize + 0.5;
424 char *font_found;
425 int size_found;
426 int magic;
427 Boolean hushcs = resource.hush_chk;
428
429 fontp->file = NULL;
430
431 /* BUG ALERT: This used to be:
432 *
433 * if (--globals.ev.ctr == 0) {
434 * read_events(EV_GE_IDLE);
435 * }
436 * force_statusline_update();
437 * XSync(DISP, False);
438 *
439 * The idea was to update the `loading fonts ...' popup. However,
440 * calling read_events() here may call dvi_file_changed() if the
441 * user clicks on the window, which calls file_exists_p(), and
442 * that changes m_dvi_fp while it's still being used to read the
443 * postamble (where load_font() is called from), which will cause
444 * xdvi to crash! (bug #968127).
445 *
446 * Sadly, without this update, the `loading fonts' popup doesn't
447 * appear before the main window comes up ...
448 */
449
450 fontp->file = font_open(
451 #if DELAYED_MKTEXPK
452 load_font_now,
453 #endif
454 fontp,
455 (const char **) &font_found,
456 &size_found);
457
458 #if DELAYED_MKTEXPK
459 if (!load_font_now)
460 return True;
461 #endif
462
463 #if FREETYPE
464 if (fontp->ft != NULL) { /* if freetype font */
465 fontp->timestamp = ++current_timestamp;
466 fontp->maxchar = maxchar = 255;
467 fontp->set_char_p = set_ft_char;
468 fontp->glyph = xmalloc (256 * sizeof (struct glyph));
469 memset((char *) fontp->glyph, 0, 256 * sizeof (struct glyph));
470 fontp->flags |= FONT_LOADED;
471 if (font_found != NULL) {
472 statusline_error(STATUS_MEDIUM,
473 "Error: Can't find font %s; using %s instead. Expect ugly output.",
474 fontp->fontname, font_found);
475 force_statusline_update();
476 free(fontp->fontname);
477 fontp->fontname = font_found; /* this has been allocated by font_open */
478 }
479 return True;
480 }
481 #endif /* FREETYPE */
482
483 /* when it's not a freetype font, fontp->file == NULL means total failure */
484 if (fontp->file == NULL) {
485 if (globals.ev.flags & EV_GE_NEWDOC)
486 return False;
487 fontp->flags |= FONT_LOADED; /* as loaded as it'll get */
488 XDVI_ERROR((stderr, "Can't find font %s.%dpk", fontp->fontname, dpi));
489 return False;
490 }
491 fontp->flags |= FONT_LOADED;
492
493 if (font_found != NULL && strcmp(fontp->fontname, font_found) != 0) {
494 /* some other font used - FIXME: is there a more efficient way than strcmp() for checking this? */
495 statusline_error(STATUS_MEDIUM,
496 "Can't find pixel font %s; using %s instead at %d dpi.",
497 fontp->fontname, font_found, dpi);
498 force_statusline_update();
499 free(fontp->fontname);
500 fontp->fontname = font_found; /* this has been allocated by font_open */
501 hushcs = True;
502 }
503 else if (!kpse_bitmap_tolerance((double)size_found, fsize)) { /* a different size used */
504 statusline_error(STATUS_MEDIUM,
505 "Can't find pixel font %s at %d dpi; using %d dpi instead.",
506 fontp->fontname, dpi, size_found);
507 force_statusline_update();
508 }
509
510 /* PK version of some font found */
511 fontp->fsize = size_found;
512 fontp->timestamp = ++current_timestamp;
513 fontp->maxchar = maxchar = 255;
514 fontp->set_char_p = set_char;
515 magic = get_bytes(fontp->file, 2);
516
517 switch(magic) {
518 case PK_MAGIC:
519 read_PK_index(fontp, (wide_bool)hushcs);
520 break;
521 #ifdef USE_GF
522 case GF_MAGIC:
523 read_GF_index(fontp, (wide_bool)hushcs);
524 break;
525 #endif
526 case VF_MAGIC:
527 if (resource.omega)
528 maxchar = read_VF_index(fontp, (wide_bool)hushcs);
529 else
530 (void)read_VF_index(fontp, (wide_bool)hushcs);
531 break;
532 default:
533 XDVI_FATAL((stderr, "Cannot recognize format for font file %s",
534 fontp->filename));
535 break;
536 }
537
538 if (fontp->flags & FONT_VIRTUAL) {
539 if (!resource.omega) {
540 while (maxchar > 0 && fontp->macro[maxchar].pos == NULL) {
541 --maxchar;
542 }
543 if (maxchar < 255) {
544 realloc_virtual_font(fontp, (wide_ubyte)maxchar);
545 }
546 }
547 }
548 else {
549 while (maxchar > 0 && fontp->glyph[maxchar].addr == 0)
550 --maxchar;
551 if (maxchar < 255) {
552 realloc_font(fontp, (wide_ubyte)maxchar);
553 }
554 }
555 return True;
556 }
557
558
559 /*
560 * MAGSTEPVALUE - If the given magnification is close to a \magstep
561 * or a \magstephalf, then return twice the number of \magsteps.
562 * Otherwise return NOMAGSTP.
563 */
564
565 #define NOMAGSTP (-29999)
566 #define NOBUILD 29999
567
568 static int
569 magstepvalue(float *mag)
570 {
571 int m = 0;
572 double fmag = *mag;
573 double xmag = resource.pixels_per_inch;
574 float margin = fmag * 0.002;
575
576 if (fmag < resource.pixels_per_inch)
577 for (;;) {
578 if (xmag - fmag < margin && -(xmag - fmag) < margin) {
579 *mag = xmag;
580 return m;
581 }
582 if (xmag < fmag)
583 break;
584 xmag *= 0.9128709292;
585 --m;
586 }
587 else
588 for (;;) {
589 if (xmag - fmag < margin && -(xmag - fmag) < margin) {
590 *mag = xmag;
591 return m;
592 }
593 if (xmag > fmag)
594 break;
595 xmag *= 1.095445115;
596 ++m;
597 }
598 return NOMAGSTP;
599 }
600
601 /*
602 * reuse_font recursively sets the flags for font structures being reused.
603 */
604
605 static void
606 reuse_font(struct font *fontp)
607 {
608 struct font **fp;
609 struct tn *tnp;
610
611 if (fontp->flags & FONT_IN_USE)
612 return;
613
614 fontp->flags |= FONT_IN_USE;
615 if (resource.list_fonts)
616 printf("xdvi: (reusing) %s at %d dpi\n", fontp->fontname,
617 (int)(fontp->fsize + 0.5));
618 if (fontp->flags & FONT_VIRTUAL) {
619 for (fp = fontp->vf_table; fp < fontp->vf_table + VFTABLELEN; ++fp)
620 if (*fp != NULL)
621 reuse_font(*fp);
622 for (tnp = fontp->vf_chain; tnp != NULL; tnp = tnp->next)
623 reuse_font(tnp->fontp);
624 }
625 }
626
627
628 /*
629 * define_font reads the rest of the fntdef command and then reads in
630 * the specified pixel file, adding it to the global linked-list holding
631 * all of the fonts used in the job.
632 */
633 struct font *
634 define_font(
635 #if DELAYED_MKTEXPK
636 Boolean read_fonts, /* reading font definitions */
637 Boolean initialize_fonts, /* also initializing internal data structures for fonts */
638 #else
639 Boolean load_font_now, /* only scanning, or also loading the font? */
640 #endif
641 FILE *file,
642 wide_ubyte cmnd,
643 struct font *vfparent, /* vf parent of this font, or NULL */
644 struct font **tntable, /* table for low TeXnumbers */
645 unsigned int tn_table_len, /* length of table for TeXnumbers */
646 struct tn **tn_headpp, /* addr of head of list of TeXnumbers */
647 Boolean *not_found_flag) /* signal that font hasn't been found */
648 {
649 unsigned int TeXnumber;
650 struct font *fontp;
651 float fsize;
652 double scale_dimconv;
653 long checksum;
654 int scale;
655 int design;
656 int magstepval;
657 int len;
658 char *fontname;
659 int size;
660
661 TeXnumber = get_bytes(file, (int)cmnd - FNTDEF1 + 1);
662 checksum = get_bytes(file, 4);
663 scale = get_bytes(file, 4);
664 design = get_bytes(file, 4);
665 len = get_byte(file);
666 len += get_byte(file); /* sequence point in the middle */
667
668 #if DELAYED_MKTEXPK
669 if (!read_fonts) {
670 get_bytes(file, len);
671 return NULL;
672 }
673 #else
674 if (!load_font_now)
675 return NULL;
676 #endif
677
678 fontname = xmalloc((unsigned)len + 1);
679 (void)fread(fontname, sizeof(char), len, file);
680 fontname[len] = '\0';
681
682 if (globals.debug & DBG_PK)
683 printf("xdvi: Define font \"%s\" scale=%d design=%d number=%d\n",
684 fontname, scale, design, TeXnumber);
685 if (vfparent == NULL) {
686 fsize = 0.001 * scale / design * magnification * resource.pixels_per_inch;
687 scale_dimconv = dimconv;
688 }
689 else {
690 /*
691 * The scaled size is given in units of vfparent->scale * 2 ** -20
692 * SPELL units, so we convert it into SPELL units by multiplying by
693 * vfparent->dimconv.
694 * The design size is given in units of 2 ** -20 pt, so we convert
695 * into SPELL units by multiplying by
696 * (resource.pixels_per_inch * 2**16) / (72.27 * 2**20).
697 */
698 fsize = (72.27 * (1 << 4)) * vfparent->dimconv * scale / design;
699 scale_dimconv = vfparent->dimconv;
700 }
701 magstepval = magstepvalue(&fsize);
702 size = fsize + 0.5;
703 /*
704 * reuse font if possible
705 */
706 for (fontp = font_head;; fontp = fontp->next) {
707 if (fontp == NULL) { /* if font doesn't exist yet */
708 if (resource.list_fonts)
709 printf("xdvi: %s at %d dpi\n", fontname, (int)(fsize + 0.5));
710 fontp = xmalloc((unsigned)sizeof(struct font));
711 fontp->fontname = fontname;
712 fontp->fsize = fsize;
713 fontp->magstepval = magstepval;
714 fontp->file = NULL; /* needed for virtual/freetype fonts */
715 fontp->filename = NULL; /* needed for freetype fonts */
716 fontp->checksum = checksum;
717 fontp->flags = FONT_IN_USE;
718 fontp->dimconv = scale * scale_dimconv / (1 << 20);
719 fontp->set_char_p = load_n_set_char;
720 #if FREETYPE
721 fontp->ft = NULL;
722 /* pixsize = scaled size of the font in pixels,
723 * = scale * [vfparent->]dimconv / (1 << 16).
724 */
725 fontp->pixsize =
726 (vfparent != NULL ? vfparent->dimconv : dimconv) * scale
727 / (1 << 16);
728 #endif
729 if (vfparent == NULL)
730 if (!load_font(fontp
731 #if DELAYED_MKTEXPK
732 , initialize_fonts
733 #endif
734 )) {
735 if (globals.ev.flags & EV_GE_NEWDOC) { /* if aborting */
736 free(fontname);
737 free(fontp);
738 return NULL;
739 }
740 *not_found_flag = True;
741 }
742 fontp->next = font_head;
743 font_head = fontp;
744 break;
745 }
746 if (strcmp(fontname, fontp->fontname) == 0
747 && size == (int)(fontp->fsize + 0.5)) {
748 /* if font already in use */
749 reuse_font(fontp);
750 free(fontname);
751 break;
752 }
753 }
754 if (TeXnumber < tn_table_len)
755 tntable[TeXnumber] = fontp;
756 else {
757 struct tn *tnp;
758 tnp = xmalloc((unsigned)sizeof(struct tn));
759 tnp->next = *tn_headpp;
760 *tn_headpp = tnp;
761 tnp->TeXnumber = TeXnumber;
762 tnp->fontp = fontp;
763 }
764 return fontp;
765 }
766
767
768
769 /*
770 * process_preamble reads the information in the preamble and stores
771 * it into global variables for later use.
772 */
773 Boolean
774 process_preamble(FILE *fp, dviErrFlagT *errflag)
775 {
776 ubyte k;
777 static char job_id[300];
778
779 TRACE_FILES((stderr, "process_preamble: fp = %p, errflag = %d", (void *)fp, *errflag));
780
781 if (get_byte(fp) != PRE) {
782 *errflag = NOT_A_DVI_FILE;
783 TRACE_FILES((stderr, "process_preamble: fp = %p, errflag = %d, returning False", (void *)fp, *errflag));
784 return False;
785 }
786 if (get_byte(fp) != 2) {
787 *errflag = WRONG_DVI_VERSION;
788 TRACE_FILES((stderr, "process_preamble: fp = %p, errflag = %d, returning False", (void *)fp, *errflag));
789 return False;
790 }
791 numerator = get_bytes(fp, 4);
792 denominator = get_bytes(fp, 4);
793 magnification = get_bytes(fp, 4);
794 dimconv = (((double)numerator * magnification)
795 / ((double)denominator * 1000.));
796 dimconv = dimconv * (((long)resource.pixels_per_inch) << 16) / 254000;
797 tpic_conv = resource.pixels_per_inch * magnification / 1000000.0;
798 k = get_byte(fp);
799 (void)fread(job_id, sizeof(char), (int)k, fp);
800 job_id[k] = '\0';
801
802 TRACE_FILES((stderr, "process_preamble: fp = %p, errflag = %d, returning True", (void *)fp, *errflag));
803
804 return True;
805 }
806
807 /*
808 * find_postamble locates the beginning of the postamble
809 * and leaves the file ready to start reading at that location.
810 */
811 #define TMPSIZ 516 /* 4 trailer bytes + 512 junk bytes allowed */
812 Boolean
813 find_postamble(FILE *fp, dviErrFlagT *errflag)
814 {
815 long pos;
816 ubyte temp[TMPSIZ];
817 ubyte *p;
818 ubyte *p1;
819 ubyte byte;
820
821 TRACE_FILES((stderr, "find_postamble on fp: %p", (void *)fp));
822
823 fseek(fp, 0L, SEEK_END);
824 pos = ftell(fp) - TMPSIZ;
825 if (pos < 0)
826 pos = 0;
827 fseek(fp, pos, SEEK_SET);
828 p = temp + fread((char *)temp, sizeof(char), TMPSIZ, fp);
829 for (;;) {
830 p1 = p;
831 while (p1 > temp && *(--p1) != TRAILER);
832 p = p1;
833 while (p > temp && *(--p) == TRAILER);
834 if (p <= p1 - 4)
835 break; /* found 4 TRAILER bytes */
836 if (p <= temp) {
837 *errflag = DVI_CORRUPTED;
838 TRACE_FILES((stderr, "find_postamble: returning FALSE"));
839 return False;
840 }
841 }
842 pos += p - temp;
843 byte = *p;
844 while (byte == TRAILER) {
845 fseek(fp, --pos, SEEK_SET);
846 byte = get_byte(fp);
847 }
848 if (byte != 2) {
849 *errflag = WRONG_DVI_VERSION;
850 TRACE_FILES((stderr, "find_postamble: returning FALSE"));
851 return False;
852 }
853 fseek(fp, pos - 4, SEEK_SET);
854 fseek(fp, get_lbytes(fp, 4), SEEK_SET);
855 TRACE_FILES((stderr, "find_postamble: returning TRUE"));
856 return True;
857 }
858
859
860
861 Boolean
862 set_paper_type(const char *arg)
863 {
864 const char *arg1;
865 char temp[21];
866 const char **p;
867 char *q;
868 const char **paper_types = get_paper_types();
869 size_t paper_types_size = get_paper_types_size();
870
871 if (*arg == '+') {
872 ++arg;
873 ignore_papersize_specials = True;
874 }
875 if (strlen(arg) > sizeof(temp) - 1)
876 return False;
877 q = temp;
878 for (;;) { /* convert to lower case */
879 char c = *arg++;
880 if (c >= 'A' && c <= 'Z')
881 c ^= ('a' ^ 'A');
882 *q++ = c;
883 if (c == '\0')
884 break;
885 }
886 arg = temp;
887 /* perform substitutions */
888 for (p = paper_types; p < paper_types + paper_types_size; p += 2) {
889 if (strcmp(temp, *p) == 0) {
890 arg = p[1];
891 break;
892 }
893 }
894 arg1 = strchr(arg, 'x');
895 if (arg1 == NULL)
896 return False;
897 m_paper_unshrunk_w = atopix(arg);
898 m_paper_unshrunk_h = atopix(arg1 + 1);
899
900 globals.grid_paper_unit = atopixunit(arg);
901
902 return (m_paper_unshrunk_w != 0 && m_paper_unshrunk_h != 0);
903 }
904
905 /*
906 * read_postamble reads the information in the postamble from fp,
907 * storing it into global variables.
908 * It also takes care of reading in all of the pixel files for the fonts
909 * used in the job.
910 *
911 * FIXME: Would be better (speed up initialization when needing to generate fonts,
912 * and allow to open window on first page) if the font loading was done on-demand later!
913 */
914 Boolean
915 read_postamble(FILE *fp, dviErrFlagT *errflag,
916 #if DELAYED_MKTEXPK
917 Boolean read_fonts, Boolean initialize_fonts
918 #else
919 Boolean load_fonts
920 #endif
921 )
922 {
923 ubyte cmnd;
924 Boolean font_not_found = False;
925 struct font *fontp;
926
927 #if DELAYED_MKTEXPK
928 int tmp_total_pages;
929 unsigned long tmp_numerator = numerator;
930 unsigned long tmp_denominator = denominator;
931 unsigned long tmp_magnification = magnification;
932 unsigned int tmp_dvi_unshrunk_page_w, tmp_dvi_unshrunk_page_h;
933 long tmp_last_page_offset;
934
935 TRACE_FILES((stderr, "read_postamble: reading %p (%d, %d)", (void *)fp, read_fonts, initialize_fonts));
936
937 if (read_fonts && initialize_fonts) {
938 /* clear existing font table */
939 memset((char *)tn_table, 0, (int)sizeof tn_table);
940 free_vf_chain(tn_head);
941 tn_head = NULL;
942 for (fontp = font_head; fontp != NULL; fontp = fontp->next)
943 fontp->flags &= ~FONT_IN_USE;
944 }
945 #else /* DELAYED_MKTEXPK */
946 TRACE_FILES((stderr, "read_postamble: reading %p (%d)", (void *)fp, load_fonts));
947
948 /* clear existing font table */
949 memset((char *)tn_table, 0, (int)sizeof tn_table);
950 free_vf_chain(tn_head);
951 tn_head = NULL;
952 for (fontp = font_head; fontp != NULL; fontp = fontp->next)
953 fontp->flags &= ~FONT_IN_USE;
954 #endif /* DELAYED_MKTEXPK */
955
956 if (get_byte(fp) != POST) {
957 *errflag = POSTAMBLE_NO_POST;
958 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
959 return False;
960 }
961 #if DELAYED_MKTEXPK
962 tmp_last_page_offset = get_bytes(fp, 4);
963 if (read_fonts && initialize_fonts)
964 m_last_page_offset = tmp_last_page_offset;
965
966 if (tmp_numerator != get_bytes(fp, 4)
967 || tmp_denominator != get_bytes(fp, 4)
968 || tmp_magnification != get_bytes(fp, 4)) {
969 *errflag = POSTAMBLE_NO_MATCH;
970 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
971 return False;
972 }
973 else if (read_fonts && initialize_fonts) {
974 numerator = tmp_numerator;
975 denominator = tmp_denominator;
976 magnification = tmp_magnification;
977 }
978
979 /* read largest box height and width */
980 tmp_dvi_unshrunk_page_h = (spell_conv(get_lbytes(fp, 4)) >> 16) + resource.yoffset_int;
981 tmp_dvi_unshrunk_page_w = (spell_conv(get_lbytes(fp, 4)) >> 16) + resource.xoffset_int;
982 (void)get_bytes(fp, 2); /* max stack size */
983 tmp_total_pages = get_bytes(fp, 2);
984
985 if (read_fonts && initialize_fonts) {
986 dvi_unshrunk_page_h = tmp_dvi_unshrunk_page_h;
987 if (dvi_unshrunk_page_h < m_paper_unshrunk_h)
988 dvi_unshrunk_page_h = m_paper_unshrunk_h;
989 dvi_unshrunk_page_w = tmp_dvi_unshrunk_page_w;
990 if (dvi_unshrunk_page_w < m_paper_unshrunk_w)
991 dvi_unshrunk_page_w = m_paper_unshrunk_w;
992 total_pages = tmp_total_pages;
993 }
994 #else /* DELAYED_MKTEXPK */
995 m_last_page_offset = get_bytes(fp, 4);
996 if (numerator != get_bytes(fp, 4)
997 || denominator != get_bytes(fp, 4)
998 || magnification != get_bytes(fp, 4)) {
999 *errflag = POSTAMBLE_NO_MATCH;
1000 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
1001 return False;
1002 }
1003
1004 /* read largest box height and width */
1005 dvi_unshrunk_page_h = (spell_conv(get_lbytes(fp, 4)) >> 16) + resource.yoffset_int;
1006 if (dvi_unshrunk_page_h < m_paper_unshrunk_h)
1007 dvi_unshrunk_page_h = m_paper_unshrunk_h;
1008 dvi_unshrunk_page_w = (spell_conv(get_lbytes(fp, 4)) >> 16) + resource.xoffset_int;
1009 if (dvi_unshrunk_page_w < m_paper_unshrunk_w)
1010 dvi_unshrunk_page_w = m_paper_unshrunk_w;
1011 (void)get_bytes(fp, 2); /* max stack size */
1012 total_pages = get_bytes(fp, 2);
1013 #endif /* DELAYED_MKTEXPK */
1014
1015 /* read font definitions */
1016 while ((cmnd = get_byte(fp)) >= FNTDEF1 && cmnd <= FNTDEF4) {
1017 struct font *f = define_font(
1018 #if DELAYED_MKTEXPK
1019 read_fonts, initialize_fonts,
1020 #else
1021 load_fonts,
1022 #endif
1023 fp, cmnd, (struct font *)NULL, tn_table,
1024 TNTABLELEN, &tn_head, &font_not_found);
1025 if (
1026 #if DELAYED_MKTEXPK
1027 read_fonts && initialize_fonts
1028 #else
1029 load_fonts
1030 #endif
1031 && f == NULL) {
1032 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
1033 return False;
1034 }
1035 #if !DELAYED_MKTEXPK
1036 else if (!load_fonts) { /* return early */
1037 TRACE_FILES((stderr, "read_postamble: returning TRUE"));
1038 return True;
1039 }
1040 #endif
1041 }
1042
1043 if (cmnd != POSTPOST) {
1044 *errflag = POSTAMBLE_NON_FNTDEF;
1045 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
1046 return False;
1047 }
1048 if (
1049 #if DELAYED_MKTEXPK
1050 read_fonts && initialize_fonts &&
1051 #endif
1052 font_not_found) {
1053 *errflag = NOT_ALL_PIXEL_FILES_FOUND;
1054 TRACE_FILES((stderr, "read_postamble: returning FALSE"));
1055 return False;
1056 }
1057 #if DELAYED_MKTEXPK
1058 if (read_fonts && initialize_fonts)
1059 free_unused_fonts();
1060 #else
1061 free_unused_fonts();
1062 #endif
1063
1064 TRACE_FILES((stderr, "read_postamble: returning TRUE"));
1065 return True;
1066 }
1067
1068
1069 static Boolean
1070 prepare_pages(dviErrFlagT *errflag)
1071 {
1072 int i;
1073 long offset;
1074
1075 TRACE_FILES((stderr, "calling pageinfo_deallocate"));
1076 pageinfo_deallocate();
1077
1078 TRACE_FILES((stderr, "pageinfo_allocate for %d pages", total_pages + 1));
1079 pageinfo_allocate(total_pages + 1);
1080 pageinfo_set_page_width(total_pages, m_paper_unshrunk_w);
1081 pageinfo_set_page_height(total_pages, m_paper_unshrunk_h);
1082 pageinfo_set_window_width(total_pages, dvi_unshrunk_page_w);
1083 pageinfo_set_window_height(total_pages, dvi_unshrunk_page_h);
1084
1085 pageinfo_set_offset(total_pages - 1, m_last_page_offset);
1086 /*
1087 * Follow back pointers through pages in the DVI file,
1088 * storing the offsets in the pageinfo table.
1089 */
1090 for (offset = m_last_page_offset, i = total_pages; i > 0; i--) {
1091 fseek(globals.dvi_file.bak_fp, offset, SEEK_SET);
1092 if (get_byte(globals.dvi_file.bak_fp) != BOP) {
1093 *errflag = NO_BOP_AT_PAGEDESC;
1094 return False;
1095 }
1096 pageinfo_set_offset(i-1, offset);
1097 /* from c_0, read count0, the TeX page number */
1098 pageinfo_set_number(i-1, get_bytes(globals.dvi_file.bak_fp, 4));
1099
1100 /* skip c_1 to c_9 */
1101 fseek(globals.dvi_file.bak_fp, 9*4L, SEEK_CUR);
1102
1103 /* next 4 byte contain offset to previous bop */
1104 offset = get_bytes(globals.dvi_file.bak_fp, 4);
1105 }
1106 /* If not prescanning, initialize page sizes. */
1107 if (!resource.prescan) {
1108 for (i = 0; i < total_pages; ++i) {
1109 pageinfo_set_page_width(i, m_paper_unshrunk_w);
1110 pageinfo_set_page_height(i, m_paper_unshrunk_h);
1111 pageinfo_set_window_width(i, dvi_unshrunk_page_w);
1112 pageinfo_set_window_height(i, dvi_unshrunk_page_h);
1113 }
1114 }
1115 return True;
1116 }
1117
1118 void
1119 init_page(void)
1120 {
1121 if (globals.dvi_file.bak_fp == NULL)
1122 return;
1123 globals.page.unshrunk_w = pageinfo_get_page_width(current_page);
1124 globals.page.unshrunk_h = pageinfo_get_page_height(current_page);
1125 globals.page.w = ROUNDUP(globals.page.unshrunk_w, mane.shrinkfactor) + 2;
1126 globals.page.h = ROUNDUP(globals.page.unshrunk_h, mane.shrinkfactor) + 2;
1127 TRACE_FILES((stderr, "init_page: setting globals.page.w = %d, globals.page.h = %d", globals.page.w, globals.page.h));
1128 }
1129
1130 #ifndef S_ISDIR
1131 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1132 #endif
1133
1134 static char *m_tmp_dvi_name = NULL; /* name of backup file for useTempFp */
1135
1136 /* access function for backup file name */
1137 char *get_tmp_dvi_name(void) {
1138 return m_tmp_dvi_name;
1139 }
1140
1141 static void
1142 remove_tmp_dvi_file(void *dummy)
1143 {
1144 UNUSED(dummy);
1145 if (m_tmp_dvi_name != NULL) {
1146 unlink(m_tmp_dvi_name);
1147 free(m_tmp_dvi_name);
1148 }
1149 m_tmp_dvi_name = NULL;
1150 }
1151
1152
1153 static FILE *
1154 make_backup_fp(FILE *source_fp, FILE *target_fp)
1155 {
1156 static Boolean first_time = True;
1157 static int tmp_fd = 0;
1158
1159 #if !HAVE_FTRUNCATE
1160 /* in this case, we can't use ftruncate() on the existing temp file -
1161 just close the existing one, and set flag to open a new one */
1162 remove_tmp_dvi_file(NULL);
1163 if (target_fp != NULL)
1164 fclose(target_fp);
1165 /* make sure we use a new temp file, else we'd have a race condition
1166 after closing it */
1167 first_time = True;
1168 #endif
1169
1170 if (first_time) { /* doesn't exist yet, create it */
1171 if ((tmp_fd = xdvi_temp_fd(&m_tmp_dvi_name)) == -1) {
1172 XDVI_ERROR((stderr, "error creating temporary file - disabling `useTempFp'."));
1173 goto fail;
1174 }
1175 /* fprintf(stderr, "temporary file name: |%s|, %d\n", m_tmp_dvi_name, tmp_fd); */
1176 TRACE_EVENTS((stderr, "Created temp file: |%s|\n", m_tmp_dvi_name));
1177 if ((target_fp = try_fdopen(tmp_fd, "wb+")) == NULL) {
1178 XDVI_ERROR((stderr, "error opening temporary file (%s) - disabling `useTempFp'.", strerror(errno)));
1179 goto fail;
1180 }
1181 first_time = False;
1182 }
1183 else { /* if not first time, truncate the existing file,
1184 and position both files at beginning */
1185 ASSERT(target_fp != NULL, "");
1186 ASSERT(source_fp != NULL, "");
1187
1188 tmp_fd = try_dup(fileno(target_fp));
1189 if (tmp_fd == -1) {
1190 XDVI_ERROR((stderr, "Couldn't duplicate descriptor of file %s: %s - disabling `useTempFp'; target_fp: %p.",
1191 m_tmp_dvi_name, strerror(errno), target_fp));
1192 goto fclose_and_fail;
1193 }
1194
1195 fclose(target_fp);
1196
1197 if (lseek(tmp_fd, 0L, SEEK_SET) == -1) {
1198 XDVI_ERROR((stderr, "Couldn't seek to start of file %s: %s - disabling `useTempFp'; target_fp: %p.",
1199 m_tmp_dvi_name, strerror(errno), target_fp));
1200 goto fail;
1201 }
1202 #if HAVE_FTRUNCATE
1203 if (ftruncate(tmp_fd, 0) < 0) {
1204 XDVI_ERROR((stderr, "Couldn't truncate file %s: %s - disabling `useTempFp'; target_fp: %p.",
1205 m_tmp_dvi_name, strerror(errno), target_fp));
1206 goto fail;
1207 }
1208 #endif
1209
1210 if ((target_fp = try_fdopen(tmp_fd, "wb+")) == NULL) {
1211 XDVI_ERROR((stderr, "error opening temporary file (%s) - disabling `useTempFp'.", strerror(errno)));
1212 goto fail;
1213 }
1214
1215 if (fseek(source_fp, 0L, SEEK_SET)) {
1216 perror("fseek of source_fp");
1217 goto fclose_and_fail;
1218 }
1219 }
1220
1221 /* copy the file */
1222 if (!copy_fp(source_fp, target_fp)) {
1223 XDVI_ERROR((stderr,
1224 "Error creating temporary file: %s\n"
1225 "- disabling `useTempFp'.",
1226 strerror(errno)));
1227 goto fclose_and_fail;
1228 }
1229
1230 /* rewind both files, else DVI parsing will fail! */
1231 if (target_fp != NULL) {
1232 fflush(target_fp);
1233 }
1234 if (fseek(source_fp, 0L, SEEK_SET)) {
1235 perror("fseek of source_fp after rewind");
1236 }
1237 if (target_fp != NULL) {
1238 if (fseek(target_fp, 0L, SEEK_SET)) {
1239 perror("fseek of target_fp again");
1240 }
1241 }
1242
1243 return target_fp;
1244
1245 fclose_and_fail:
1246 fclose(target_fp);
1247 /* FALLTHROUGH */
1248 fail:
1249 resource.use_temp_fp = False;
1250 remove_tmp_dvi_file(NULL);
1251 return NULL;
1252
1253 }
1254
1255 static Boolean
1256 file_exists_p(const char *path, dviErrFlagT *errflag)
1257 {
1258 TRACE_FILES((stderr, "file_exists_p for |%s|", path));
1259 *errflag = UNKNOWN_ERROR;
1260 if ((m_dvi_fp = XFOPEN(path, OPEN_MODE)) == NULL) {
1261 /* fprintf(stderr, "after internal_open_dvi1: xfopen\n"); */
1262 *errflag = FILE_DOESNT_EXIST;
1263 return False;
1264 }
1265 TRACE_FILES((stderr, "m_dvi_fp for |%s| = %p", path, (void *)m_dvi_fp));
1266 /* fprintf(stderr, "after internal_open_dvi2: xfopen\n"); */
1267
1268 /* shouldn't happen */
1269 if (fstat(fileno(m_dvi_fp), &fstatbuf) == -1) {
1270 perror("xdvi: file_exists_p: fstat");
1271 fclose(m_dvi_fp);
1272 m_dvi_fp = NULL;
1273 return False;
1274 }
1275 if (S_ISDIR(fstatbuf.st_mode)) { /* if it's a directory */
1276 *errflag = FILE_IS_DIRECTORY;
1277 fclose(m_dvi_fp);
1278 m_dvi_fp = NULL;
1279 return False;
1280 }
1281 /* If file has zero size, something has gone wrong with downloading
1282 it, and the user should already have been warned about that;
1283 just return in this case.
1284 TODO: can it still happen that we try to load such a file as .dvi
1285 file? (Will exit with `draw_part: unknown op-code xyz' or some such).
1286 In this case, it would be better to look at the preamble before
1287 entering the drawing loop.
1288 */
1289 if (fstatbuf.st_size == 0) {
1290 *errflag = FILE_HAS_ZERO_SIZE;
1291 fclose(m_dvi_fp);
1292 m_dvi_fp = NULL;
1293 return False;
1294 }
1295 return True;
1296 }
1297
1298 /*
1299 * internal_init_dvi is the main subroutine for reading the startup
1300 * information from the dvi file.
1301 */
1302
1303 static Boolean
1304 internal_init_dvi(dviErrFlagT *errflag,
1305 #if DELAYED_MKTEXPK
1306 Boolean read_fonts, Boolean initialize_fonts
1307 #else
1308 Boolean load_fonts
1309 #endif
1310 )
1311 {
1312 char *icon_name = NULL, *title_name = NULL;
1313
1314 have_src_specials = False;
1315
1316 TRACE_FILES((stderr, "internal_init_dvi, globals.dvi_file.bak_fp = %p", (void *)globals.dvi_file.bak_fp));
1317
1318 if (!process_preamble(globals.dvi_file.bak_fp, errflag)
1319 || !find_postamble(globals.dvi_file.bak_fp, errflag)
1320 #if DELAYED_MKTEXPK
1321 || !read_postamble(globals.dvi_file.bak_fp, errflag, read_fonts, initialize_fonts)
1322 #else
1323 || !read_postamble(globals.dvi_file.bak_fp, errflag, load_fonts)
1324 || !prepare_pages(errflag)
1325 #endif
1326 ) {
1327 return False;
1328 }
1329 #if DELAYED_MKTEXPK
1330 if (!read_fonts || !initialize_fonts) /* return early */
1331 return True;
1332
1333 if (!prepare_pages(errflag))
1334 return False;
1335 #endif
1336
1337 if (current_page >= total_pages)
1338 current_page = total_pages - 1;
1339
1340 globals.warn_spec_now = resource.warn_spec;
1341 globals.src.fwd_box_page = -1;
1342 search_reset_info();
1343
1344 if (globals.pausing.num_save != NULL) {
1345 free(globals.pausing.num_save);
1346 globals.pausing.num_save = NULL;
1347 }
1348 if (resource.pause && total_pages > 0) {
1349 globals.pausing.num_save = xmalloc(total_pages * sizeof *globals.pausing.num_save);
1350 memset(globals.pausing.num_save, 0, total_pages * sizeof *globals.pausing.num_save);
1351 }
1352
1353 init_prescan();
1354 /* this allocates icon_name and title_name */
1355 get_icon_and_title(globals.dvi_name, &icon_name, &title_name);
1356 set_icon_and_title(icon_name, title_name);
1357 free(icon_name);
1358 free(title_name);
1359 icon_name = title_name = NULL;
1360
1361 #if defined(MOTIF) && HAVE_XPM
1362 tb_check_navigation_sensitivity(current_page);
1363 #endif
1364 refresh_pagelist(total_pages, current_page);
1365
1366 return True;
1367 }
1368
1369 /*
1370 * internal_open_dvi does the real opening of the dvi file, and sets
1371 * globals.dvi_file.time. It returns True on success, and sets m_dvi_fp and globals.dvi_file.bak_fp.
1372 */
1373
1374 Boolean
1375 internal_open_dvi(const char *path, dviErrFlagT *errflag,
1376 #if DELAYED_MKTEXPK
1377 Boolean read_fonts, Boolean initialize_fonts
1378 #else
1379 Boolean load_fonts
1380 #endif
1381 )
1382 {
1383 /* FILE *tmp_fp = NULL; */
1384 /* static FILE *bak_fp = NULL; /\* re-use the temporary backup fp *\/ */
1385 /* fprintf(stderr, "------------ opening: |%s|\n", path); */
1386
1387 #if DELAYED_MKTEXPK
1388 TRACE_FILES((stderr, "internal_open_dvi for |%s|; loading fonts: %d, %d", path, read_fonts, initialize_fonts));
1389 #else
1390 TRACE_FILES((stderr, "internal_open_dvi for |%s|", path));
1391 #endif
1392 close_old_filep();
1393
1394 if (!file_exists_p(path, errflag)) { /* this should set fstatbuf.st_mtime */
1395 return False;
1396 }
1397
1398 if (!resource.use_temp_fp || (globals.dvi_file.bak_fp = make_backup_fp(m_dvi_fp, globals.dvi_file.bak_fp)) == NULL) {
1399 globals.dvi_file.bak_fp = m_dvi_fp;
1400 }
1401
1402 register_exit_handler(remove_tmp_dvi_file, NULL);
1403
1404 globals.dvi_file.time = fstatbuf.st_mtime;
1405
1406 if (!internal_init_dvi(errflag,
1407 #if DELAYED_MKTEXPK
1408 read_fonts, initialize_fonts
1409 #else
1410 load_fonts
1411 #endif
1412 )) {
1413 return False;
1414 }
1415
1416 #if COLOR
1417 full_reset_colors();
1418 #endif /* COLOR */
1419 reset_papersize_special();
1420
1421 TRACE_FILES((stderr, "internal_open_dvi: SUCCESS!"));
1422
1423 return True;
1424 }
1425
1426 /*
1427 check whether `filename' is a DVI file, by checking if it exists, and if so,
1428 opening it and trying to read a DVI preamble from it:
1429 */
1430 static char *
1431 is_dvi_file(const char *filename)
1432 {
1433 FILE *fp;
1434 struct stat statbuf;
1435 char *full_pathname;
1436 dviErrFlagT unused_error;
1437
1438 TRACE_FILES((stderr, "is_dvi_file %s", filename));
1439 TRACE_HTEX((stderr, "filename: |%s|", filename));
1440
1441 /* used to append `.dvi' if not already present, but that was a
1442 bad idea - if we have both foo.2 and foo.2.dvi, user will want
1443 to open `foo.2' (with some appropriate application) if the link
1444 points to that filename. This means that we need to have
1445 different semantics for filenames on the command-line and
1446 filenames in hyperlinks; the latter *must* specify an
1447 extension, the former may omit the extension and default to DVI
1448 files.
1449 */
1450 /* if ((full_filename = filename_append_dvi(filename)) == NULL) { */
1451 /* free(full_filename); */
1452 /* return NULL; */
1453 /* } */
1454 /* TRACE_HTEX((stderr, "full_filename: |%s|\n", full_filename)); */
1455
1456 if ((full_pathname = find_file(filename, &statbuf, kpse_program_text_format)) == NULL) {
1457 return NULL;
1458 }
1459 else {
1460 char *tmp = canonicalize_path(full_pathname);
1461 free(full_pathname);
1462 full_pathname = tmp;
1463 }
1464
1465 TRACE_HTEX((stderr, "is_dvi_file: full_pathname: |%s|", full_pathname));
1466
1467 if ((fp = XFOPEN(full_pathname, OPEN_MODE)) == NULL) {
1468 free(full_pathname);
1469 return NULL;
1470 }
1471
1472 if (!process_preamble(fp, &unused_error)) {
1473 free(full_pathname);
1474 fclose(fp);
1475 return NULL;
1476 }
1477
1478 fclose(fp);
1479 return full_pathname;
1480 }
1481
1482 static void
1483 report_open_error(const char *msg, const char *filename, dviErrFlagT errflag)
1484 {
1485 const char *errmsg;
1486 switch(errflag) {
1487 case FILE_HAS_ZERO_SIZE:
1488 errmsg = "File has zero size";
1489 break;
1490 case FILE_DOESNT_EXIST:
1491 errmsg = "No such file";
1492 break;
1493 case FILE_IS_DIRECTORY:
1494 errmsg = "Is a directory";
1495 break;
1496 default:
1497 errmsg = "An unknown error occurred";
1498 break;
1499 }
1500 XDVI_ERROR((stderr, "%s: %s: %s", msg, filename, errmsg));
1501 }
1502
1503 /*
1504 Implements the algorithm for opening a DVI file from the command line.
1505 This is similar to `open_dvi_file()' in non-k xdvi.
1506
1507 If the file does not already have `.dvi' extension, append `.dvi'
1508 and set tried_dvi_ext to True. Try to open this file. If the file
1509 doesn't exist, try the original file name. If this file doesn't
1510 exist either, exit with an error message `No such file or directory'.
1511 If tried_dvi_ext == True, also report that file.dvi didn't exist
1512 either.
1513
1514 (A later function will check if the file really is a DVI file, and
1515 will use tried_dvi_ext for the same purpose).
1516 */
1517 char *
1518 find_dvi_file(const char *filename, Boolean *tried_dvi_ext, Boolean from_file_history)
1519 {
1520 char *new_filename;
1521 size_t len;
1522 dviErrFlagT errflag;
1523
1524 ASSERT(filename != NULL, "Filename argument in find_dvi_file() musn't be NULL");
1525 len = strlen(filename);
1526
1527 if (len < sizeof(".dvi") || strcmp(filename + len - sizeof(".dvi") + 1, ".dvi") != 0) {
1528 /* doesn't already have .dvi extension */
1529 TRACE_HTEX((stderr, "|%s| doesn't have .dvi extension, appending ...", filename));
1530 new_filename = xstrdup(filename);
1531 new_filename = xstrcat(new_filename, ".dvi");
1532 *tried_dvi_ext = True;
1533
1534 if (file_exists_p(new_filename, &errflag)) { /* file exists */
1535 char *expanded_filename = expand_filename(new_filename, USE_CWD_PATH);
1536 free(new_filename);
1537 return expanded_filename;
1538 }
1539 else { /* don't report an error; will try verbatim filename next */
1540 free(new_filename);
1541 }
1542 }
1543
1544 /* try verbatim filename (might be strange things like `foo.wdvi') */
1545 if (file_exists_p(filename, &errflag)) {
1546 char *expanded_filename = expand_filename(filename, USE_CWD_PATH);
1547 return expanded_filename;
1548 }
1549 else {
1550 if (*tried_dvi_ext) {
1551 if (!from_file_history) {
1552 XDVI_FATAL((stderr, "%s: %s, and %s.dvi doesn't exist either.",
1553 filename, get_dvi_error(errflag), filename));
1554 }
1555 else {
1556 popup_message(globals.widgets.top_level,
1557 MSG_ERR,
1558 NULL,
1559 "Could not open \"%s\": %s.\n", filename, get_dvi_error(errflag));
1560 }
1561 }
1562 else {
1563 if (!from_file_history) {
1564 XDVI_FATAL((stderr, "%s: %s.", filename, get_dvi_error(errflag)));
1565 }
1566 /* else: file is from history; this is at startup, where we may
1567 loop through the history until we find a usable file. Don't report
1568 an error in this case. */
1569 }
1570 }
1571 return NULL;
1572 }
1573
1574
1575
1576 /*
1577 * A wrapper for open_dvi_file that can also deal with remote files/URLs, and other
1578 * file types. Returns the (newly malloc'ed) new dvi file name if it succeeds, NULL else.
1579 */
1580 char *
1581 open_dvi_file_wrapper(const char *filename,
1582 Boolean from_command_line,
1583 Boolean open_new_instance,
1584 Boolean *tried_dvi_ext,
1585 Boolean from_file_history)
1586 {
1587 char *real_filename = NULL;
1588 char *new_dvi_name = NULL;
1589 char canonical_path[MAXPATHLEN + 1];
1590
1591 if (from_command_line) {
1592 TRACE_HTEX((stderr, "filename IS from commandline"));
1593 /*
1594 if filename is from command-line, we want to treat the file as a DVI file
1595 always (and NOT launch the browser or other programs; that'd just confuse
1596 people, who meant to launch *xdvi*). `find_dvi_file' tries to locate the
1597 file and does all error handling; on success, it returns a fully expanded
1598 filename.
1599 */
1600 real_filename = find_dvi_file(filename, tried_dvi_ext, from_file_history); /* this allocates real_filename */
1601 if (real_filename == NULL)
1602 return False;
1603
1604 TRACE_HTEX((stderr, "filename |%s| %p from commandline;\ndvi_name: |%s|,\nfilename: |%s|%p",
1605 real_filename, real_filename, globals.dvi_name, filename, (void *)filename));
1606 new_dvi_name = xstrdup(REALPATH(real_filename, canonical_path));
1607 free(real_filename);
1608 TRACE_FILES((stderr, "new_dvi_name: |%s|", new_dvi_name));
1609 return new_dvi_name;
1610 }
1611 else {
1612 /*
1613 if it's not from the command line (e.g. result of clicking Mouse-1 on a link);
1614 in this case we might fall back to using the browser.
1615 Check whether it's a local file:
1616 */
1617 const char *filename_no_prefix;
1618 char *expanded_filename;
1619 TRACE_HTEX((stderr, "filename NOT from commandline"));
1620 if ((filename_no_prefix = is_local_file(filename)) != NULL) {
1621 /* if it's a local file, check whether it's a DVI file: */
1622 if ((expanded_filename = is_dvi_file(filename_no_prefix)) != NULL) {
1623 /* yes, open it */
1624 if (open_dvi_file(expanded_filename, open_new_instance)) {
1625 TRACE_FILES((stderr, "success: %p |%s|", expanded_filename, expanded_filename));
1626 if (!open_new_instance) {
1627 new_dvi_name = expand_filename_append_dvi(expanded_filename, USE_DVI_PATH, True);
1628 TRACE_FILES((stderr, "new_dvi_name: %p |%s|", (void*)new_dvi_name, new_dvi_name));
1629 }
1630 }
1631 free(expanded_filename);
1632 return new_dvi_name;
1633 }
1634 else {
1635 /*
1636 local file, but not a DVI file;
1637 try other viewers for this MIME type:
1638 */
1639 TRACE_HTEX((stderr, "%s is NOT a DVI file", filename_no_prefix));
1640 launch_program(filename);
1641 return NULL;
1642 }
1643 }
1644 else {
1645 /* not a local file, retrieve it with the browser: */
1646 launch_browser(filename);
1647 return NULL;
1648 }
1649 }
1650 }
1651
1652
1653 static Boolean
1654 open_dvi_file(const char *filename, Boolean open_new_instance)
1655 {
1656 Boolean retval = True;
1657
1658 char *anchor_name = resource.anchor_pos;
1659
1660 TRACE_HTEX((stderr, "open_dvi_file: |%s| + |%s|",
1661 filename, anchor_name == NULL ? "<no anchor>" : anchor_name));
1662
1663 if (open_new_instance) {
1664 launch_xdvi(filename, anchor_name);
1665 }
1666 else {
1667 dviErrFlagT errflag = NO_ERROR;
1668 TRACE_HTEX((stderr, "internal_open_dvi: |%s|", filename));
1669 if (!internal_open_dvi(filename, &errflag, True
1670 #if DELAYED_MKTEXPK
1671 , TRUE
1672 #endif
1673 )) {
1674 report_open_error("Cannot open DVI file", filename, errflag);
1675 retval = False;
1676 }
1677 }
1678 return retval;
1679 }
1680
1681 /**
1682 ** form_dvi_property forms the property used to exhibit the dvi file name
1683 ** used as a window property (used for source specials).
1684 **/
1685
1686 void
1687 form_dvi_property(void)
1688 {
1689 #if 0
1690 size_t len;
1691 unsigned long ino;
1692 int i;
1693 #endif
1694
1695 if (m_dvi_fp == NULL)
1696 return;
1697
1698 if (dvi_property != NULL)
1699 free(dvi_property);
1700
1701 dvi_property_length = strlen(globals.dvi_name) + 1; /* also copy the terminating 0 */
1702 dvi_property = xmalloc(dvi_property_length);
1703
1704 /* NOTE: we don't use dvi_inode like non-k xdvi, since xdvik keeps closer
1705 track of when the path points to a different inode. */
1706 strcpy(dvi_property, globals.dvi_name);
1707 }
1708
1709
1710 /* access for m_dvi_fp */
1711 void
1712 close_old_filep(void)
1713 {
1714 if (m_dvi_fp != NULL) {
1715 fclose(m_dvi_fp);
1716 m_dvi_fp = NULL;
1717 if (!resource.use_temp_fp)
1718 globals.dvi_file.bak_fp = NULL;
1719 }
1720 }
1721
1722
1723
1724 /**
1725 ** Check for changes in dvi file.
1726 ** Return True if file has changed, False else.
1727 **/
1728
1729 Boolean
1730 dvi_file_changed(void)
1731 {
1732 TRACE_FILES((stderr, "dvi_file_changed: fp = %p?", (void *)m_dvi_fp));
1733
1734 /* fprintf(stderr, "m_dvi_fp3: %p (%s)\n", m_dvi_fp, globals.dvi_name); */
1735 if (m_dvi_fp == NULL) {
1736 TRACE_FILES((stderr, "m_dvi_fp == NULL"));
1737 if (stat(globals.dvi_name, &fstatbuf) == 0 && fstatbuf.st_mtime != globals.dvi_file.time) {
1738 TRACE_FILES((stderr, "file changed"));
1739 if (resource.use_temp_fp) {
1740 dviErrFlagT errflag = NO_ERROR;
1741 #if !DELAYED_MKTEXPK
1742 if (resource.watch_file == 0.0)
1743 statusline_info(STATUS_MEDIUM, "File changed ...");
1744 TRACE_FILES((stderr, "returning FALSE"));
1745 #endif
1746 if (file_exists_p(globals.dvi_name, &errflag)
1747 && process_preamble(m_dvi_fp, &errflag)
1748 && find_postamble(m_dvi_fp, &errflag)
1749 && read_postamble(m_dvi_fp, &errflag, False
1750 #if DELAYED_MKTEXPK
1751 , False
1752 #endif
1753 )) {
1754 TRACE_FILES((stderr, "File OK, reloading ..."));
1755
1756 globals.ev.flags |= EV_RELOAD;
1757 return True;
1758 }
1759 else {
1760 #if DELAYED_MKTEXPK
1761 if (resource.watch_file == 0.0)
1762 statusline_info(STATUS_MEDIUM, "File corrupted (click on window to reload) ...");
1763 TRACE_FILES((stderr, "returning FALSE"));
1764 #endif
1765 return False;
1766 }
1767 }
1768 /* Bug alert: Don't set EV_RELOAD again here, else xdvi
1769 can go into a stretch of time where it again and again
1770 tries to reload a file even if the user doesn't click
1771 on the canvas.
1772 */
1773 /*
1774 else {
1775 globals.ev.flags |= EV_RELOAD;
1776 }
1777 */
1778 TRACE_FILES((stderr, "returning TRUE"));
1779 return True;
1780 }
1781 else {
1782 TRACE_FILES((stderr, "file not changed"));
1783 }
1784 }
1785 /* BUG ALERT: Don't use fstat(fileno(m_dvi_fp) here; if file hase
1786 disappeared, this won't report an error! */
1787 else if (stat(globals.dvi_name, &fstatbuf) != 0 /* stat failed ... */
1788 || fstatbuf.st_mtime != globals.dvi_file.time /* ... or different timestamp, reload: */) {
1789 dviErrFlagT errflag = NO_ERROR;
1790
1791 TRACE_FILES((stderr, "Stat failed, or different timestamp ..."));
1792 globals.dvi_file.time = 0; /* force reload next time also if stat failed */
1793
1794 if (resource.use_temp_fp) { /* in this case, reload only if file has been written completely */
1795 if (resource.watch_file == 0.0) {
1796 statusline_info(STATUS_MEDIUM, "File corrupted (click on window to reload) ...");
1797 globals.cursor.flags |= CURSOR_CORRUPTED;
1798 globals.ev.flags |= EV_CURSOR;
1799 }
1800 else {
1801 statusline_info(STATUS_MEDIUM, "File corrupted (will try to reload) ...");
1802 }
1803 close_old_filep();
1804 if (file_exists_p(globals.dvi_name, &errflag)
1805 && process_preamble(m_dvi_fp, &errflag)
1806 && find_postamble(m_dvi_fp, &errflag)
1807 && read_postamble(m_dvi_fp, &errflag, False
1808 #if DELAYED_MKTEXPK
1809 , False
1810 #endif
1811 )) {
1812 TRACE_FILES((stderr, "File OK, reloading ..."));
1813
1814 globals.ev.flags |= EV_RELOAD;
1815 return True;
1816 }
1817 else {
1818 TRACE_FILES((stderr, "NO successful load: %s", get_dvi_error(errflag)));
1819 /* fprintf(stderr, "=========== NO successful load: %s\n", get_dvi_error(errflag)); */
1820 return False;
1821 }
1822 }
1823 else {
1824 TRACE_FILES((stderr, "Not using temp fp, reloading..."));
1825 globals.ev.flags |= EV_RELOAD;
1826 return True;
1827 }
1828 }
1829 return False;
1830 }
1831
1832 /**
1833 ** Reload the dvi file (unconditionally). Return True on success, False else.
1834 **/
1835
1836 Boolean
1837 load_dvi_file(
1838 #if !DELAYED_MKTEXPK
1839 Boolean load_fonts,
1840 #endif
1841 dviErrFlagT *errflag)
1842 {
1843 unsigned int old_page_w, old_page_h;
1844 static ino_t dvi_inode = 0;
1845
1846 TRACE_FILES((stderr, "load_dvi_file: going to read %p", (void *)m_dvi_fp));
1847
1848 if (resource.use_temp_fp && m_dvi_fp != NULL) {
1849 /* in this case, reload only if file has been written completely */
1850 *errflag = NO_ERROR;
1851 fseek(m_dvi_fp, 0L, SEEK_SET);
1852 if (!process_preamble(m_dvi_fp, errflag)
1853 || !find_postamble(m_dvi_fp, errflag)
1854 || !read_postamble(m_dvi_fp, errflag,
1855 #if DELAYED_MKTEXPK
1856 False, False
1857 #else
1858 True
1859 #endif
1860 )) {
1861 TRACE_FILES((stderr, "reading of %p failed: %s!",
1862 (void *)m_dvi_fp,
1863 get_dvi_error(*errflag)));
1864 return False;
1865 }
1866 }
1867
1868 old_page_w = globals.page.w;
1869 old_page_h = globals.page.h;
1870
1871 *errflag = NO_ERROR;
1872
1873 #if DELAYED_MKTEXPK
1874 /* use same trick with reading postamble twice to first find names of PK fonts
1875 that need to be created. */
1876 reset_missing_font_count();
1877 kpse_set_program_enabled(kpse_any_glyph_format, False, kpse_src_compile);
1878 #endif
1879
1880 if (!internal_open_dvi(globals.dvi_name, errflag,
1881 #if DELAYED_MKTEXPK
1882 True, False
1883 #else
1884 load_fonts
1885 #endif
1886 )) {
1887 XClearWindow(DISP, mane.win);
1888 xdvi_bell();
1889 statusline_info(STATUS_MEDIUM, "%s: %s%s", globals.dvi_name, get_dvi_error(*errflag),
1890 resource.watch_file > 0.0 ? "; will try to reload ..." : " (click on window to reload)");
1891 close_old_filep();
1892
1893 return False;
1894 }
1895 #if DELAYED_MKTEXPK
1896 /* second time */
1897 kpse_set_program_enabled(kpse_any_glyph_format, True, kpse_src_compile);
1898
1899 if (!internal_open_dvi(globals.dvi_name, errflag, True, True)) {
1900 XClearWindow(DISP, mane.win);
1901 xdvi_bell();
1902 statusline_info(STATUS_MEDIUM, "%s: %s%s", globals.dvi_name, get_dvi_error(*errflag),
1903 resource.watch_file > 0.0 ? "; will try to reload ..." : " (click on window to reload)");
1904 close_old_filep();
1905 return False;
1906 }
1907 #endif
1908 else { /* success */
1909 if (fstatbuf.st_ino != dvi_inode) {
1910 dvi_inode = fstatbuf.st_ino;
1911 form_dvi_property();
1912 set_dvi_property();
1913 }
1914 if (globals.page.w != old_page_w || globals.page.h != old_page_h)
1915 reconfig();
1916
1917 htex_reinit();
1918
1919 globals.cursor.flags &= ~CURSOR_CORRUPTED;
1920 return True;
1921 }
1922 }