summaryrefslogtreecommitdiffstats
path: root/kdvi/dviRenderer_prescan.cpp
blob: 7cfd24151737f34ac42ca637ccb31740bf2187ee (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
// dviRenderer_prescan.cpp
//
// Part of KDVI - A DVI previewer for the KDE desktop environemt 
//
// (C) 2003--2004 Stefan Kebekus
// Distributed under the GPL

#include <config.h>

#include "dviRenderer.h"
#include "dvi.h"
#include "dviFile.h"
#include "fontpool.h"
#include "kdvi_multipage.h"
#include "performanceMeasurement.h"
#include "prebookmark.h"
#include "psgs.h"
#include "TeXFont.h"
#include "xdvi.h"

#include <kdebug.h>
#include <klocale.h>
#include <kmimetype.h>
#include <kprocess.h>
#include <kprocio.h>
#include <kprogress.h>
#include <tqapplication.h>
#include <tqbitmap.h>
#include <tqdir.h> 
#include <tqfileinfo.h>
#include <tqimage.h> 
#include <tqpainter.h>
#include <tqpaintdevice.h>


extern TQPainter foreGroundPaint;
extern void parse_special_argument(const TQString& strg, const char* argument_name, int* variable);


//#define DEBUG_PRESCAN


void dviRenderer::prescan_embedPS(char *cp, TQ_UINT8 *beginningOfSpecialCommand)
{
#ifdef  DEBUG_PRESCAN
  kdDebug(4300) << "dviRenderer::prescan_embedPS( cp = " << cp << " ) " << endl;
#endif

  // Encapsulated Postscript File
  if (strncasecmp(cp, "PSfile=", 7) != 0) 
    return;

  TQString command(cp+7);
  
  TQString include_command = command.simplifyWhiteSpace();
  
  // The line is supposed to start with "..ile=", and then comes the
  // filename. Figure out what the filename is and stow it away. Of
  // course, this does not work if the filename contains spaces
  // (already the simplifyWhiteSpace() above is wrong). If you have
  // files like this, go away.
  TQString EPSfilename = include_command;
  EPSfilename.truncate(EPSfilename.find(' '));

  // Strip enclosing quotation marks which are included by some LaTeX
  // macro packages (but not by others). This probably means that
  // graphic files are no longer found if the filename really does
  // contain quotes, but we don't really care that much.
  if ((EPSfilename.at(0) == '\"') && (EPSfilename.at(EPSfilename.length()-1) == '\"'))
    EPSfilename = EPSfilename.mid(1,EPSfilename.length()-2);

  // If the file is neither a PostScript not a PDF file, we exit here.
  // The graphic file is later read when the page is rendered.
  KMimeType::Ptr const mime_type =
    KMimeType::findByFileContent(EPSfilename);
  TQString const & mime_type_name = mime_type->name();

  bool const is_ps_file  = (mime_type_name == "application/postscript" ||
                            mime_type_name == "image/x-eps");
  bool const is_pdf_file = (!is_ps_file &&
                            mime_type_name == "application/pdf");
  if (!(is_ps_file || is_pdf_file))
    return;

  TQString originalFName = EPSfilename;

  embedPS_progress->setLabel(i18n("Embedding %1").tqarg(EPSfilename));  
  tqApp->processEvents();

  
  // Now locate the Gfx file on the hard disk...
  EPSfilename = ghostscript_interface::locateEPSfile(EPSfilename, baseURL);

  // If the EPSfilename really points to a PDF file, convert that file now.
  if (is_pdf_file)
    EPSfilename = dviFile->convertPDFtoPS(EPSfilename);

  if (!TQFile::exists(EPSfilename)) {
    // Find the number of the page
    TQ_UINT32 currentOffset = beginningOfSpecialCommand - dviFile->dvi_Data();
    TQ_UINT16 page;
    for(page=0; page < dviFile->total_pages; page++) 
      if ((dviFile->page_offset[page] <= currentOffset) && (currentOffset <= dviFile->page_offset[page+1]))
	break;
    errorMsg += i18n("Page %1: The PostScript file <strong>%2</strong> could not be found.<br>").tqarg(page+1).tqarg(originalFName);
    embedPS_progress->progressBar()->advance(1);
    tqApp->processEvents();
    return;
  }

  // Now parse the arguments. 
  int  llx     = 0; 
  int  lly     = 0;
  int  urx     = 0;
  int  ury     = 0;
  int  rwi     = 0;
  int  rhi     = 0;
  int  angle   = 0;

  // just to avoid ambiguities; the filename could contain keywords
  include_command = include_command.mid(include_command.find(' '));
  
  parse_special_argument(include_command, "llx=", &llx);
  parse_special_argument(include_command, "lly=", &lly);
  parse_special_argument(include_command, "urx=", &urx);
  parse_special_argument(include_command, "ury=", &ury);
  parse_special_argument(include_command, "rwi=", &rwi);
  parse_special_argument(include_command, "rhi=", &rhi);
  parse_special_argument(include_command, "angle=", &angle);

  int clip=include_command.find(" clip"); // -1 if clip keyword is not present, >= 0 otherwise

  // Generate the PostScript commands to be included
  TQString PS = TQString("ps: @beginspecial %1 @llx %2 @lly %3 @urx %4 @ury").tqarg(llx).tqarg(lly).tqarg(urx).tqarg(ury);
  if (rwi != 0)
    PS.append( TQString(" %1 @rwi").tqarg(rwi) );
  if (rhi != 0)
    PS.append( TQString(" %1 @rhi").tqarg(rhi) );
  if (angle != 0)
    PS.append( TQString(" %1 @angle").tqarg(angle) );
  if (clip != -1)
    PS.append(" @clip");
  PS.append( " @setspecial\n" );
  
  TQFile file( EPSfilename );
  if ( file.open( IO_ReadOnly ) ) {
    TQTextStream stream( &file );
    while ( !stream.atEnd() ) {
      PS += stream.readLine().section( '%', 0, 0);
      PS += "\n";
    }
    file.close();
  }
  PS.append( "@endspecial" );
  PS = PS.simplifyWhiteSpace();
  
  
  _isModified = true;
  TQ_UINT32 lengthOfOldSpecial = command_pointer - beginningOfSpecialCommand;
  TQ_UINT32 lengthOfNewSpecial = PS.length()+5;
  
  TQMemArray<TQ_UINT8> newDVI(dviFile->size_of_file + lengthOfNewSpecial-lengthOfOldSpecial);
  
  TQ_UINT8 *commandPtrSav = command_pointer;
  TQ_UINT8 *endPtrSav = end_pointer;
  end_pointer = newDVI.data() + dviFile->size_of_file + lengthOfNewSpecial-lengthOfOldSpecial;
  memcpy(newDVI.data(), dviFile->dvi_Data(), beginningOfSpecialCommand-dviFile->dvi_Data());
  command_pointer = newDVI.data()+(beginningOfSpecialCommand-dviFile->dvi_Data());
  command_pointer[0] = XXX4;
  command_pointer++;
  writeUINT32(PS.length());
  memcpy(newDVI.data()+(beginningOfSpecialCommand-dviFile->dvi_Data())+5, PS.latin1(), PS.length() );
  memcpy(newDVI.data()+(beginningOfSpecialCommand-dviFile->dvi_Data())+lengthOfNewSpecial, beginningOfSpecialCommand+lengthOfOldSpecial,
	 dviFile->size_of_file-(beginningOfSpecialCommand-dviFile->dvi_Data())-lengthOfOldSpecial );
  
  // Adjust page pointers in the DVI file
  dviFile->size_of_file = dviFile->size_of_file + lengthOfNewSpecial-lengthOfOldSpecial;
  end_pointer = newDVI.data() + dviFile->size_of_file;
  TQ_UINT32 currentOffset = beginningOfSpecialCommand-dviFile->dvi_Data();
  for(TQ_UINT16 i=0; i < dviFile->total_pages; i++) {
    if (dviFile->page_offset[i] > currentOffset) {
      dviFile->page_offset[i] = dviFile->page_offset[i] + lengthOfNewSpecial-lengthOfOldSpecial;
      command_pointer = dviFile->page_offset[i] + newDVI.data() + 4*10 + 1;
      TQ_UINT32 a = readUINT32();
      if (a > currentOffset) {
	a = a + lengthOfNewSpecial-lengthOfOldSpecial;
	command_pointer = dviFile->page_offset[i] + newDVI.data() + 4*10 + 1;
	writeUINT32(a);
      }
    }
  }
  
  
  dviFile->beginning_of_postamble            = dviFile->beginning_of_postamble + lengthOfNewSpecial - lengthOfOldSpecial;
  dviFile->page_offset[dviFile->total_pages] = dviFile->beginning_of_postamble;
  
  command_pointer = newDVI.data() + dviFile->beginning_of_postamble + 1;
  TQ_UINT32 a = readUINT32();
  if (a > currentOffset) {
    a = a + lengthOfNewSpecial - lengthOfOldSpecial;
    command_pointer = newDVI.data() + dviFile->beginning_of_postamble + 1;
    writeUINT32(a);
  }
  
  command_pointer = newDVI.data() + dviFile->size_of_file - 1;
  while((*command_pointer == TRAILER) && (command_pointer > newDVI.data()))
    command_pointer--;
  command_pointer -= 4;
  writeUINT32(dviFile->beginning_of_postamble);
  command_pointer -= 4;
  
  command_pointer = commandPtrSav;
  end_pointer     = endPtrSav;
  
  // Modify all pointers to point to the newly allocated memory
  command_pointer = newDVI.data() + (command_pointer - dviFile->dvi_Data()) + lengthOfNewSpecial-lengthOfOldSpecial;
  end_pointer = newDVI.data() + (end_pointer - dviFile->dvi_Data())  + lengthOfNewSpecial-lengthOfOldSpecial;
  
  dviFile->setNewData(newDVI);
  
  embedPS_progress->progressBar()->advance(1);
  tqApp->processEvents();
  return;
}


void dviRenderer::prescan_removePageSizeInfo(char *cp, TQ_UINT8 *beginningOfSpecialCommand)
{
#ifdef  DEBUG_PRESCAN
  kdDebug(4300) << "dviRenderer::prescan_embedPS( cp = " << cp << " ) " << endl;
#endif
  
  // Encapsulated Postscript File
  if (strncasecmp(cp, "papersize=", 10) != 0) 
    return;
  
  for (TQ_UINT8 *ptr=beginningOfSpecialCommand; ptr<command_pointer; ptr++) 
    *ptr = NOP;
}


void dviRenderer::prescan_ParsePapersizeSpecial(const TQString& _cp)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "Papersize-Special : papersize" << cp << endl;
#endif

  TQString cp = _cp.simplifyWhiteSpace();

  if (cp[0] == '=') {
    cp = cp.mid(1);
    dviFile->suggestedPageSize = new pageSize;
    dviFile->suggestedPageSize->setPageSize(cp);
  } else 
    printErrorMsgForSpecials(i18n("The papersize data '%1' could not be parsed.").tqarg(cp));

  return;
}


void dviRenderer::prescan_ParseBackgroundSpecial(const TQString& cp)
{
  TQColor col = parseColorSpecification(cp.stripWhiteSpace());
  if (col.isValid())
    for(TQ_UINT16 page=current_page; page < dviFile->total_pages; page++)
      PS_interface->setBackgroundColor(page, col);
  return;
}


void dviRenderer::prescan_ParseHTMLAnchorSpecial(const TQString& _cp)
{
  TQString cp = _cp;
  cp.truncate(cp.find('"'));
  Length l;
  l.setLength_in_inch(currinf.data.dvi_v/(resolutionInDPI*shrinkfactor));
  anchorList[cp] = Anchor(current_page+1, l);
}


void dviRenderer::prescan_ParsePSHeaderSpecial(const TQString& cp)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "PostScript-special, header " << cp.latin1() << endl;
#endif

  TQString _file = cp;
  
  // If the file is not found in the current directory, use kpsewhich
  // to find it.
  if (!TQFile::exists(_file)) {
    // Otherwise, use kpsewhich to find the eps file.
    KProcIO proc;
    proc << "kpsewhich" << cp;
    proc.start(KProcess::Block);
    proc.readln(_file);
  }
  
  if (TQFile::exists(_file))
    PS_interface->PostScriptHeaderString->append( TQString(" (%1) run\n").tqarg(_file) );
}


void dviRenderer::prescan_ParsePSBangSpecial(const TQString& cp)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "PostScript-special, literal header " << cp.latin1() << endl;
#endif
  
  PS_interface->PostScriptHeaderString->append( " @defspecial \n" );
  PS_interface->PostScriptHeaderString->append( cp );
  PS_interface->PostScriptHeaderString->append( " @fedspecial \n" );
}


void dviRenderer::prescan_ParsePSQuoteSpecial(const TQString& cp)
{
#ifdef DEBUG_PRESCAN
  kdError(4300) << "PostScript-special, literal PostScript " << cp.latin1() << endl;
#endif
  
  double PS_H = (currinf.data.dvi_h*300.0)/(65536*1200)-300;
  double PS_V = (currinf.data.dvi_v*300.0)/1200 - 300;
  PostScriptOutPutString->append( TQString(" %1 %2 moveto\n").tqarg(PS_H).tqarg(PS_V) );
  PostScriptOutPutString->append( " @beginspecial @setspecial \n" );
  PostScriptOutPutString->append( cp );
  PostScriptOutPutString->append( " @endspecial \n" );
}


void dviRenderer::prescan_ParsePSSpecial(const TQString& cp)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "PostScript-special, direct PostScript " << cp << endl;
#endif

  // Unfortunately, in some TeX distribution the hyperref package uses
  // the dvips driver by default, rather than the hypertex driver. As
  // a result, the DVI files produced are full of PostScript that
  // specifies links and anchors, and KDVI would call the ghostscript
  // interpreter for every page which makes it really slow. This is a
  // major nuisance, so that we try to filter and interpret the
  // hypertex generated PostScript here.
  if (cp.startsWith("ps:SDict begin")) {
    // We suspect this may be hyperref generated nonsense. Let's check
    // for some known code that hyperref generates.
    if (cp == "ps:SDict begin H.S end") 
      return; // start of hyperref rectangle
    if (cp == "ps:SDict begin H.R end") 
      return; // end of hyperref rectangle
    if (cp.endsWith("H.A end"))
      return; // end of hyperref anchor
    if (cp.endsWith("H.L end"))
      return; // end of hyperref link
    if (cp.startsWith("ps:SDict begin /product where{pop product(Distiller)"))
      return; // hyperref tries to work around Distiller bug
    if (cp.startsWith("ps:SDict begin [") && cp.endsWith(" pdfmark end")) {  // hyperref definition of link/anchor/bookmark/etc
      if (cp.contains("/DEST")) { // The PostScript code defines an anchor
	TQString anchorName = cp.section('(', 1, 1).section(')', 0, 0);
	Length l;
	l.setLength_in_inch(currinf.data.dvi_v/(resolutionInDPI*shrinkfactor));
	anchorList[anchorName] = Anchor(current_page+1, l);
      }
      // The PostScript code defines a bookmark
      if (cp.contains("/Dest") && cp.contains("/Title"))
	prebookmarks.append(PreBookmark(PDFencodingToTQString(cp.section('(', 2, 2).section(')', 0, 0)),
					cp.section('(', 1, 1).section(')', 0, 0), 
					cp.section('-', 1, 1).section(' ', 0, 0).toUInt()
					));
      return;
    }
  }
    
  double PS_H = (currinf.data.dvi_h*300.0)/(65536*1200)-300;
  double PS_V = (currinf.data.dvi_v*300.0)/1200 - 300;
  
  if (cp.find("ps::[begin]", 0, false) == 0) {
    PostScriptOutPutString->append( TQString(" %1 %2 moveto\n").tqarg(PS_H).tqarg(PS_V) );
    PostScriptOutPutString->append( TQString(" %1\n").tqarg(cp.mid(11)) );
  } else {
    if (cp.find("ps::[end]", 0, false) == 0) {
      PostScriptOutPutString->append( TQString(" %1\n").tqarg(cp.mid(9)) );
    } else {
      if (cp.find("ps::", 0, false) == 0) {
	PostScriptOutPutString->append( TQString(" %1\n").tqarg(cp.mid(4)) );
      } else {
	PostScriptOutPutString->append( TQString(" %1 %2 moveto\n").tqarg(PS_H).tqarg(PS_V) );
	PostScriptOutPutString->append( TQString(" %1\n").tqarg(cp.mid(3)) );
      }
    }
  }
}


void dviRenderer::prescan_ParsePSFileSpecial(const TQString& cp)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "epsf-special: psfile=" << cp <<endl;
#endif

  TQString include_command = cp.simplifyWhiteSpace();

  // The line is supposed to start with "..ile=", and then comes the
  // filename. Figure out what the filename is and stow it away. Of
  // course, this does not work if the filename contains spaces
  // (already the simplifyWhiteSpace() above is wrong). If you have
  // files like this, go away.
  TQString EPSfilename = include_command;
  EPSfilename.truncate(EPSfilename.find(' '));

  // Strip enclosing quotation marks which are included by some LaTeX
  // macro packages (but not by others). This probably means that
  // graphic files are no longer found if the filename really does
  // contain quotes, but we don't really care that much.
  if ((EPSfilename.at(0) == '\"') && (EPSfilename.at(EPSfilename.length()-1) == '\"')) {
    EPSfilename = EPSfilename.mid(1,EPSfilename.length()-2);
  }

  // If the file name ends in 'png', 'gif', 'jpg' or 'jpeg', we assume
  // that this is NOT a PostScript file, and we exit here.
  TQString ending = EPSfilename.section('.', -1).lower();
  if ((ending == "png") || (ending == "gif") || (ending == "jpg") || (ending == "jpeg")) {
    dviFile->numberOfExternalNONPSFiles++;  
    return;
  }
  
  // Now assume that the graphics file *is* a PostScript file
  dviFile->numberOfExternalPSFiles++;  
  
  // Now locate the Gfx file on the hard disk...
  EPSfilename = ghostscript_interface::locateEPSfile(EPSfilename, baseURL);
  
  // If the EPSfilename really points to a PDF file, convert that file now.
  if (ending == "pdf")
    EPSfilename = dviFile->convertPDFtoPS(EPSfilename);
  
  // Now parse the arguments. 
  int  llx     = 0; 
  int  lly     = 0;
  int  urx     = 0;
  int  ury     = 0;
  int  rwi     = 0;
  int  rhi     = 0;
  int  angle   = 0;
  
  // just to avoid ambiguities; the filename could contain keywords
  include_command = include_command.mid(include_command.find(' '));
  
  parse_special_argument(include_command, "llx=", &llx);
  parse_special_argument(include_command, "lly=", &lly);
  parse_special_argument(include_command, "urx=", &urx);
  parse_special_argument(include_command, "ury=", &ury);
  parse_special_argument(include_command, "rwi=", &rwi);
  parse_special_argument(include_command, "rhi=", &rhi);
  parse_special_argument(include_command, "angle=", &angle);
  
  int clip=include_command.find(" clip"); // -1 if clip keyword is not present, >= 0 otherwise
  
  if (TQFile::exists(EPSfilename)) {
    double PS_H = (currinf.data.dvi_h*300.0)/(65536*1200)-300;
    double PS_V = (currinf.data.dvi_v*300.0)/1200 - 300;
    PostScriptOutPutString->append( TQString(" %1 %2 moveto\n").tqarg(PS_H).tqarg(PS_V) );
    PostScriptOutPutString->append( "@beginspecial " );
    PostScriptOutPutString->append( TQString(" %1 @llx").tqarg(llx) );
    PostScriptOutPutString->append( TQString(" %1 @lly").tqarg(lly) );
    PostScriptOutPutString->append( TQString(" %1 @urx").tqarg(urx) );
    PostScriptOutPutString->append( TQString(" %1 @ury").tqarg(ury) );
    if (rwi != 0)
      PostScriptOutPutString->append( TQString(" %1 @rwi").tqarg(rwi) );
    if (rhi != 0)
      PostScriptOutPutString->append( TQString(" %1 @rhi").tqarg(rhi) );
    if (angle != 0)
      PostScriptOutPutString->append( TQString(" %1 @angle").tqarg(angle) );
    if (clip != -1)
      PostScriptOutPutString->append(" @clip");
    PostScriptOutPutString->append( " @setspecial \n" );
    PostScriptOutPutString->append( TQString(" (%1) run\n").tqarg(EPSfilename) );
    PostScriptOutPutString->append( "@endspecial \n" );
  }
  
  return;
}


void dviRenderer::prescan_ParseSourceSpecial(const TQString& cp)
{
  // if no rendering takes place, i.e. when the DVI file is first
  // loaded, generate a DVI_SourceFileAnchor. These anchors are used
  // in forward search, i.e. to relate references line
  // "src:123file.tex" to positions in the DVI file
  
  // extract the file name and the numeral part from the string
  TQ_UINT32 j;
  for(j=0;j<cp.length();j++)
    if (!cp.at(j).isNumber())
      break;
  TQ_UINT32 sourceLineNumber = cp.left(j).toUInt();
  TQFileInfo fi1(dviFile->filename);
  TQString  sourceFileName   = TQFileInfo(fi1.dir(), cp.mid(j).stripWhiteSpace()).absFilePath();
  Length l;
  l.setLength_in_inch(currinf.data.dvi_v/(resolutionInDPI*shrinkfactor));
  DVI_SourceFileAnchor sfa(sourceFileName, sourceLineNumber, current_page+1, l);
  sourceHyperLinkAnchors.push_back(sfa);
}


void dviRenderer::prescan_parseSpecials(char *cp, TQ_UINT8 *)
{
  TQString special_command(cp);

  // Now to those specials which are only interpreted during the
  // prescan phase, and NOT during rendering.
  
  // PaperSize special
  if (strncasecmp(cp, "papersize", 9) == 0) {
    prescan_ParsePapersizeSpecial(special_command.mid(9));
    return;
  }
  
  // color special for background color
  if (strncasecmp(cp, "background", 10) == 0) {
    prescan_ParseBackgroundSpecial(special_command.mid(10));
    return;
  }
  
  // HTML anchor special
  if (strncasecmp(cp, "html:<A name=", 13) == 0) {
    prescan_ParseHTMLAnchorSpecial(special_command.mid(14));
    return;
  }
  
  // Postscript Header File
  if (strncasecmp(cp, "header=", 7) == 0) {
    prescan_ParsePSHeaderSpecial(special_command.mid(7));
    return;
  }
  
  // Literal Postscript Header
  if (cp[0] == '!') {
    prescan_ParsePSBangSpecial(special_command.mid(1));
    return;
  }
  
  // Literal Postscript inclusion
  if (cp[0] == '"') {
    prescan_ParsePSQuoteSpecial(special_command.mid(1));
    return;
  }
  
  // PS-Postscript inclusion
  if (strncasecmp(cp, "ps:", 3) == 0) {
    prescan_ParsePSSpecial(special_command);
    return;
  }
  
  // Encapsulated Postscript File
  if (strncasecmp(cp, "PSfile=", 7) == 0) {
    prescan_ParsePSFileSpecial(special_command.mid(7));
    return;
  }
  
  // source special
  if (strncasecmp(cp, "src:", 4) == 0) {
    prescan_ParseSourceSpecial(special_command.mid(4));
    return;
  }
  
  // Finally there are those special commands which must be considered
  // both during rendering and during the pre-scan phase
  
  // HTML anchor end
  if (strncasecmp(cp, "html:</A>", 9) == 0) {
    html_anchor_end();
    return;
  }
  
  return;
}


void dviRenderer::prescan_setChar(unsigned int ch)
{
  TeXFontDefinition *fontp = currinf.fontp;
  if (fontp == NULL)
    return;

  if (currinf.set_char_p == &dviRenderer::set_char) {
    glyph *g = ((TeXFont *)(currinf.fontp->font))->getGlyph(ch, true, globalColor);
    if (g == NULL)
      return;
    currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * 
				(1200.0 / 2.54)/16.0 * g->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
    return;
  }
 
  if (currinf.set_char_p == &dviRenderer::set_vf_char) {
    macro *m = &currinf.fontp->macrotable[ch];
    if (m->pos == NULL) 
      return;
    currinf.data.dvi_h += (int)(currinf.fontp->scaled_size_in_DVI_units * dviFile->getCmPerDVIunit() * 
				(1200.0 / 2.54)/16.0 * m->dvi_advance_in_units_of_design_size_by_2e20 + 0.5);
    return;
  }
}


void dviRenderer::prescan(parseSpecials specialParser)
{
#ifdef DEBUG_PRESCAN
  kdDebug(4300) << "dviRenderer::prescan( ... )" << endl;
#endif

  if (resolutionInDPI == 0.0)
    setResolution(100);

  TQ_INT32 RRtmp=0, WWtmp=0, XXtmp=0, YYtmp=0, ZZtmp=0;
  TQ_UINT8 ch;
  double fontPixelPerDVIunit = dviFile->getCmPerDVIunit() * 1200.0/2.54;

  stack.clear();

  currinf.fontp        = NULL;
  currinf.set_char_p   = &dviRenderer::set_no_char;

  for (;;) {
    ch = readUINT8();
    
    if (ch <= (unsigned char) (SETCHAR0 + 127)) {
      prescan_setChar(ch);
      continue;
    }

    if (FNTNUM0 <= ch && ch <= (unsigned char) (FNTNUM0 + 63)) {
      currinf.fontp = currinf.fonttable->find(ch - FNTNUM0);
      if (currinf.fontp == NULL) {
	errorMsg = i18n("The DVI code referred to font #%1, which was not previously defined.").tqarg(ch - FNTNUM0);
	return;
      }
      currinf.set_char_p = currinf.fontp->set_char_p;
      continue;
    }
    
    
    TQ_INT32 a, b;
    
    switch (ch) {
    case SET1:
      prescan_setChar(readUINT8());
      break;
      
    case SETRULE:
      /* Be careful, dvicopy outputs rules with height =
	 0x80000000. We don't want any SIGFPE here. */
      a = readUINT32();
      b = readUINT32();
      b = ((long) (b *  65536.0*fontPixelPerDVIunit));
      currinf.data.dvi_h += b;
      break;
      
    case PUTRULE:
      a = readUINT32();
      b = readUINT32();
      break;
      
    case PUT1:
    case NOP:
      break;
      
    case BOP:
      command_pointer += 11 * 4;
      currinf.data.dvi_h = 1200 << 16; // Reminder: DVI-coordinates start at (1",1") from top of page
      currinf.data.dvi_v = 1200;
      currinf.data.pxl_v = int(currinf.data.dvi_v/shrinkfactor);
      currinf.data.w = currinf.data.x = currinf.data.y = currinf.data.z = 0;
      break;
      
    case PUSH:
      stack.push(currinf.data);
      break;
      
    case POP:
      if (stack.isEmpty())
	return;
      else
	currinf.data = stack.pop();
      break;
      
    case RIGHT1:
    case RIGHT2:
    case RIGHT3:
    case RIGHT4:
      RRtmp = readINT(ch - RIGHT1 + 1);
      currinf.data.dvi_h += ((long) (RRtmp *  65536.0*fontPixelPerDVIunit));
      break;
      
    case W1:
    case W2:
    case W3:
    case W4:
      WWtmp = readINT(ch - W0);
      currinf.data.w = ((long) (WWtmp *  65536.0*fontPixelPerDVIunit));
    case W0:
      currinf.data.dvi_h += currinf.data.w;
      break;
      
    case X1:
    case X2:
    case X3:
    case X4:
      XXtmp = readINT(ch - X0);
      currinf.data.x = ((long) (XXtmp *  65536.0*fontPixelPerDVIunit));
    case X0:
      currinf.data.dvi_h += currinf.data.x;
      break;
      
    case DOWN1:
    case DOWN2:
    case DOWN3:
    case DOWN4:
      {
	TQ_INT32 DDtmp = readINT(ch - DOWN1 + 1);
	currinf.data.dvi_v += ((long) (DDtmp *  65536.0*fontPixelPerDVIunit))/65536;
	currinf.data.pxl_v  = int(currinf.data.dvi_v/shrinkfactor);
      }
      break;
      
    case Y1:
    case Y2:
    case Y3:
    case Y4:
      YYtmp = readINT(ch - Y0);
      currinf.data.y    = ((long) (YYtmp *  65536.0*fontPixelPerDVIunit));
    case Y0:
      currinf.data.dvi_v += currinf.data.y/65536;
      currinf.data.pxl_v = int(currinf.data.dvi_v/shrinkfactor);
      break;
      
    case Z1:
    case Z2:
    case Z3:
    case Z4:
      ZZtmp = readINT(ch - Z0);
      currinf.data.z    = ((long) (ZZtmp *  65536.0*fontPixelPerDVIunit));
    case Z0:
      currinf.data.dvi_v += currinf.data.z/65536;
      currinf.data.pxl_v  = int(currinf.data.dvi_v/shrinkfactor);
      break;
      
    case FNT1:
    case FNT2:
    case FNT3:
    case FNT4:
      currinf.fontp = currinf.fonttable->find(readUINT(ch - FNT1 + 1));
      if (currinf.fontp == NULL) 
	return;
      currinf.set_char_p = currinf.fontp->set_char_p;
      break;
      
    case XXX1:
    case XXX2:
    case XXX3:
    case XXX4:
      {
	TQ_UINT8 *beginningOfSpecialCommand = command_pointer-1;
	a = readUINT(ch - XXX1 + 1);
	if (a > 0) {
	  char	*cmd	= new char[a+1];
	  strncpy(cmd, (char *)command_pointer, a);
	  command_pointer += a;
	  cmd[a] = '\0';
	  (this->*specialParser)(cmd, beginningOfSpecialCommand);
	  delete [] cmd;
	}
      }
      break;
      
    case FNTDEF1:
    case FNTDEF2:
    case FNTDEF3:
    case FNTDEF4:
      command_pointer += 12 + ch - FNTDEF1 + 1;
      command_pointer += readUINT8() + readUINT8();
      break;
      
    default:
      return;
    } /* end switch */
  } /* end for */
}