File: wvRTF.c

package info (click to toggle)
wv 1.2.9-4.2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 5,044 kB
  • ctags: 4,093
  • sloc: ansic: 31,036; sh: 11,951; xml: 1,677; makefile: 21
file content (755 lines) | stat: -rw-r--r-- 15,526 bytes parent folder | download | duplicates (6)
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
/* wvWare
 * Copyright (C) Caolan McNamara, Dom Lachowicz, and others
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <time.h>

#include "getopt.h"
#include "wv.h"

/* By Dom Lachowicz (cinamod@hotmail.com) */

/* i don't like appearing to use printf */
#define rtf_output printf
#define rtf_output_char(c)  do {rtf_output("%c", (c));} while(0)
#define ENSURE_BUF()    fflush(stdout)

typedef struct _rtfUserData {
    /* formatting variables */

    /* cached integer values */
    int cFont;
    int cFontSize;
    int cCol;

    /* boolean formats */
    int bIsBold:1;
    int bIsItalic:1;
    int bIsStrike:1;
    int bIsUl:1;
    int bIsSup:1;
    int bIsSub:1;

    /* paragraph related */
    int bInPara:1;
    int bInSec:1;
} rtfUserData;

/* this gets printed at the top of each document in the {\fonttbl section */

struct _fontMapping {
    char *word;
    char *rtf;
};

/* TODO: build me up appropriately */
static struct _fontMapping fontMap[] = {
    {"Arial", "Arial"},
    {"Bitstream Charter", "Bitstream Charter"},
    {"Bookman", "Bookman"},
    {"Courier", "Courier"},
    {"Courier New", "Courier New"},
    {"Century Schoolbook", "Century Schoolbook"},
    {"Dingbats", "Dingbats"},
    {"Goth", "Goth"},
    {"Nimbus Sans", "Nimbus Sans"},
    {"Palladio", "Palladio"},
    {"Standard Symbol", "Standard Symbol"},
    {"Symbol", "Symbol"},
    {"Times", "Times New Roman"},
    {"Times New Roman", "Times New Roman"},
};

#define FontTblSize (sizeof(fontMap)/sizeof(fontMap[0]))
#define DFL_FONT_INDEX 13	/* I map this to whatever "Times New Roman" is */
static void
output_fonttable (void)
{
    int i;

    rtf_output ("{\\fonttbl\n");

    for (i = 0; i < FontTblSize; i++)
	rtf_output ("{\\f%d\\fnil\\fcharset0\\fprq0\\fttruetype %s;}\n", i,
		    fontMap[i].rtf);

    rtf_output ("}\n");
}

/* map the MSWord name to the corresponding RTF name index */
static int
mapFont (const char *name)
{
    int k;

    for (k = 0; k < FontTblSize; k++)
	if (!strcasecmp (fontMap[k].word, name))
	    return k;

    return DFL_FONT_INDEX;
}

#undef DFL_FONT_INDEX
#undef FontTblSize

/* this gets printed at the top of each document in the {\colortbl section */
static int colorTable[][3] = {
    {0x00, 0x00, 0x00},		/* black */
    {0x00, 0x00, 0xff},		/* blue */
    {0x00, 0xff, 0xff},		/* cyan */
    {0x00, 0xff, 0x00},		/* green */
    {0xff, 0x00, 0xff},		/* magenta */
    {0xff, 0x00, 0x00},		/* red */
    {0xff, 0xff, 0x00},		/* yellow */
    {0xff, 0xff, 0xff},		/* white */
    {0x00, 0x00, 0x80},		/* dark blue */
    {0x00, 0x80, 0x80},		/* dark cyan */
    {0x00, 0x80, 0x00},		/* dark green */
    {0x80, 0x00, 0x80},		/* dark magenta */
    {0x80, 0x00, 0x00},		/* dark red */
    {0x80, 0x80, 0x00},		/* dark yellow */
    {0x80, 0x80, 0x80},		/* dark gray */
    {0xc0, 0xc0, 0xc0},		/* light gray */
};

/* rtf names for the color_table as above */
static char *rtfColors[] = {
    "\\cf0",			/* black */
    "\\cf1",			/* blue */
    "\\cf2",			/* cyan */
    "\\cf3",			/* green */
    "\\cf4",			/* magenta */
    "\\cf5",			/* red */
    "\\cf6",			/* yellow */
    "\\cf7",			/* white */
    "\\cf8",			/* dark blue */
    "\\cf9",			/* dark cyan */
    "\\cf10",			/* dark green */
    "\\cf11",			/* dark magenta */
    "\\cf12",			/* dark red */
    "\\cf13",			/* dark yellow */
    "\\cf14",			/* dark gray */
    "\\cf15",			/* light gray */
};

#define RED(i)   colorTable[(i)][0]
#define GREEN(i) colorTable[(i)][1]
#define BLUE(i)  colorTable[(i)][2]
#define ClrTblSize (sizeof(colorTable)/sizeof(colorTable[0]))
static void
output_colortable (void)
{
    int i;

    rtf_output ("{\\colortbl\n");

    for (i = 0; i < ClrTblSize; i++)
      {
	  rtf_output ("\\red%d\\green%d\\blue%d;\n", RED (i), GREEN (i),
		      BLUE (i));
      }

    rtf_output ("}\n");
}

#undef RED
#undef GREEN
#undef BLUE
#undef ClrTblSize

static void
output_rtfUserData (rtfUserData * ud)
{
    /* add the initial bracket */
    rtf_output_char ('{');

    /* font color */
    rtf_output ("%s", rtfColors[ud->cCol]);

    /* font face */
    rtf_output ("\\f%d", ud->cFont);

    /* font size */
    rtf_output ("\\fs%d", ud->cFontSize);

    /* italic text */
    if (ud->bIsItalic)
	rtf_output ("\\i");

    /* bold text */
    if (ud->bIsBold)
	rtf_output ("\\b");

    /* underline and strike-through */
    if (ud->bIsUl)
	rtf_output ("\\ul");
    if (ud->bIsStrike)
	rtf_output ("\\strike");

    /* sub/superscript */
    if (ud->bIsSup)
      {
	  rtf_output ("\\super");
      }
    else if (ud->bIsSub)
      {
	  rtf_output ("\\sub");
      }
    /* add the final space */
    rtf_output_char (' ');
}

static void
fill_rtfUserData (rtfUserData * ud, CHP * chp, wvParseStruct * ps)
{
    char *fname = NULL;

    if (!ps->fib.fFarEast)
      {
	  fname = wvGetFontnameFromCode (&ps->fonts, chp->ftcAscii);
      }
    else
      {
	  fname = wvGetFontnameFromCode (&ps->fonts, chp->ftcFE);
      }

    ud->cCol = 0;
    if (chp->ico)
      ud->cCol = chp->ico - 1;    

    ud->cFont = mapFont (fname);
    ud->cFontSize = chp->hps;
    ud->bIsBold = (chp->fBold);
    ud->bIsItalic = (chp->fItalic);
    ud->bIsUl = (chp->kul);
    ud->bIsStrike = (chp->fStrike);
    ud->bIsSup = (chp->iss == 1);
    ud->bIsSub = (chp->iss == 2);
    free(fname);
}

static void
handleImage (Blip * b, long width, long height)
{

    /* TODO: image support */
    wvStream * pwv = NULL;
    size_t size = 0;
    int data = 0;
    int cnt = 0;
    int tag = time (NULL);

    /* short-circuit this method if we don't support
       the incoming format */
    switch (b->type)
      {
      case msoblipPNG:
	  /* conveniently I know how to export to PNG */
	  rtf_output
	      ("{\\*\\shppict{\\pict\\pngblip\\picw%d\\pich%d\\picwgoal\\pichgoal\n",
	       width, height);
	  break;
      case msoblipDIB:
      case msoblipWMF:
      case msoblipEMF:
      case msoblipPICT:
      case msoblipJPEG:
      default:
	  /* TODO: support other image types */
	  return;
      }

    rtf_output ("\bliptag%d{\\*\\blipuid%032x}", tag, tag);

    pwv = b->blip.bitmap.m_pvBits;
    size = wvStream_size (pwv);
    wvStream_rewind(pwv);
    while (cnt < size)
      {
	  if (cnt++ % 64 == 0)
	      rtf_output_char ('\n');
	  rtf_output ("%02x", read_8ubit(pwv));
      }

    rtf_output_char ('}');
}

static int
charProc (wvParseStruct * ps, U16 eachchar, U8 chartype, U16 lid)
{

    /* convert incoming character to unicode */
    if (chartype)
	eachchar = wvHandleCodePage (eachchar, lid);

    /* take care of any oddities in Microsoft's character "encoding" */
    /* TODO: does the above code page handler take care of these? */
    if (chartype == 1 && eachchar == 146)
	eachchar = 39;		/* apostrophe */

    switch (eachchar)
      {
      case 13:			/* paragraph end */
	  return 0;

      case 11:			/* hard line break */
	  break;

      case 12:			/* page breaks, section marks */
	  break;

      case 14:			/* column break */
	  break;

      case 19:			/* field begin */
	  /* flush current text buffer */
	  ps->fieldstate++;
	  ps->fieldmiddle = 0;
	  return 0;
      case 20:			/* field separator */
	  ps->fieldmiddle = 1;
	  return 0;
      case 21:			/* field end */
	  ps->fieldstate--;
	  ps->fieldmiddle = 0;
	  return 0;

      default:
	  break;
      }

    /* todo: properly handle fields */
    if (eachchar == 0x13 || eachchar == 0x14)
	return 0;

    /* properly escape this */
    if (eachchar == '{' || eachchar == '}')
	rtf_output_char ('\\');

    rtf_output_char (eachchar);
    return 0;
}

static int
specCharProc (wvParseStruct * ps, U16 eachchar, CHP * achp)
{
    Blip blip;
    wvStream *fil;
    long pos;
    FSPA *fspa;
    PICF picf;
    FDOA *fdoa;

    switch (eachchar)
      {
      case 19:			/* field begin */
	  ps->fieldstate++;
	  ps->fieldmiddle = 0;
	  return 0;
      case 20:			/* field separator */
	  if (achp->fOle2)
	    {
		wvTrace (("Field has an embedded OLE2 object\n"));
	    }
	  ps->fieldmiddle = 1;
	  return 0;
      case 21:			/* field end */
	  ps->fieldstate--;
	  ps->fieldmiddle = 0;
	  return 0;
      default:
	  break;
      }

    /* TODO: properly handle fields */
    if (ps->fieldstate)
      {
	  if (eachchar == 0x13 || eachchar == 0x14)
	      return 0;
      }

    /* image handling */
    switch (eachchar)
      {
      case 0x01:

	  if (achp->fOle2)
	    {
		wvTrace (("embedded OLE2 component. currently unsupported"));
		return 0;
	    }

	  pos = wvStream_tell (ps->data);

	  wvStream_goto (ps->data, achp->fcPic_fcObj_lTagObj);

	  wvGetPICF (wvQuerySupported (&ps->fib, NULL), &picf, ps->data);

	  fil = picf.rgb;

	  if (wv0x01 (&blip, fil, picf.lcb - picf.cbHeader))
	    {
		handleImage (&blip, picf.dxaGoal, picf.dyaGoal);
	    }
	  else
	    {
		wvTrace (("Dom: strange no graphic data 1\n"));
	    }

	  wvStream_goto (ps->data, pos);

	  return 0;
	  break;

      case 0x08:

	  if (wvQuerySupported (&ps->fib, NULL) == WORD8)
	    {
		if (ps->nooffspa > 0)
		  {

		      fspa = wvGetFSPAFromCP (ps->currentcp, ps->fspa,
					      ps->fspapos, ps->nooffspa);

		      if (!fspa)
			{
			    wvError (
				     ("No fspa! Panic and Insanity Abounds!\n"));
			    return 0;
			}

		      if (wv0x08 (&blip, fspa->spid, ps))
			{
			    handleImage (&blip, fspa->xaRight - fspa->xaLeft,
					 fspa->yaBottom - fspa->yaTop);
			}
		      else
			{
			    wvTrace (("Dom: strange no graphic data 2\n"));
			    return 0;
			}
		  }
		else
		  {
		      wvTrace (("nooffspa was <=0 -- ignoring"));
		  }
	    }
	  else
	    {
		wvError (
			 ("pre Word8 0x08 graphic -- unsupported at the moment"));
		fdoa =
		    wvGetFDOAFromCP (ps->currentcp, NULL, ps->fdoapos,
				     ps->nooffdoa);
	    }

      }

    return 0;
}

static int
eleProc (wvParseStruct * ps, wvTag tag, void *props, int dirty)
{
    /* some word structures */
    PAP *apap;
    CHP *achp;
    SEP *asep;
    int iRes;

    rtfUserData *ud = (rtfUserData *) ps->userData;

    switch (tag)
      {
      case SECTIONBEGIN:

	  /* TODO: get smarter */
	  asep = (SEP *) props;
	  rtf_output ("\\sectd\\sbknone\\colsx360\n");

	  ud->bInSec = 1;
	  break;

      case SECTIONEND:
	  ud->bInSec = 0;
	  break;

      case PARABEGIN:
	  apap = (PAP *) props;

	  ud->bInPara = 1;

	  rtf_output ("\\pard");
	  switch (apap->jc)
	    {
	    case 0:		/* left */
		break;
	    case 1:		/* center */
		rtf_output ("\\qc");
		break;
	    case 2:		/* right */
		rtf_output ("\\qr");
		break;
	    default:
		break;
	    }

	  break;

      case PARAEND:		/* pretty much nothing */
	  rtf_output_char ('\n');
	  ud->bInPara = 0;
	  break;

      case CHARPROPBEGIN:
	  achp = (CHP *) props;
	  fill_rtfUserData (ud, achp, ps);
	  output_rtfUserData (ud);
	  break;

      case CHARPROPEND:
	  achp = (CHP *) props;
	  fill_rtfUserData (ud, achp, ps);
	  if (ud->bInPara)
	    {
		rtf_output_char ('}');
	    }
	  break;

      default:
	  break;
      }

    return 0;
}

static int
docProc (wvParseStruct * ps, wvTag tag)
{
    switch (tag)
      {
      case DOCBEGIN:
	  /* print out my rtf preamble */
	  rtf_output ("{\\rtf1\\ansi\\ansicpg1252\\deff0\n");

	  /* now print out a font table */
	  /* and a color table */
	  output_fonttable ();
	  output_colortable ();
	  rtf_output
	      ("\\kerning0\\cf0\\viewkind1\\paperw12240\\paperh15840\\margl1440\\margr1440\\widowctl\n");
	  break;

      case DOCEND:
	  rtf_output ("}\n");
	  ENSURE_BUF ();
	  break;

      default:
	  break;
      }

    return 0;
}

static void
do_version (void)
{
    printf ("wvRTF version %s\n",VERSION);
}

static void
do_help (void)
{
    do_version ();
    printf ("(c) Dom Lachowicz 2000\n");
    printf ("Usage:\n");
    printf ("\t-c --charset=set\n");
    printf ("\t-p --password=pass\n");
    printf ("\t-v --version\n");
    printf ("\t-? --help\n");
    printf ("\nConverts MSWord documents to RTF\n");
}

static char *charset = NULL;

int
main (int argc, char *argv[])
{
    FILE *input;
    char *fname, *password;
    int ret;

    wvParseStruct ps;
    char *dir = NULL;

    rtfUserData ud;

    static struct option long_options[] = {
	{"charset", 1, 0, 'c'},
	{"password", 1, 0, 'p'},
	{"dir", 1, 0, 'd'},
	{"version", 0, 0, 'v'},
	{"help", 0, 0, '?'},
	{0, 0, 0, 0}
    };

    int c, index = 0;

    if (argc < 2)
      {
	  do_help ();
	  return 1;
      }

    while (1)
      {
	  c = getopt_long (argc, argv, "?vc:p:d:", long_options, &index);
	  if (c == -1)
	      break;
	  switch (c)
	    {
	    case '?':
		do_help ();
		return 0;
	    case 'v':
		do_version ();
		return 0;
	    case 'c':
		if (optarg)
		    charset = optarg;
		else
		    wvError (("No argument given to charset"));
		break;
	    case 'p':
		if (optarg)
		    password = optarg;
		else
		    wvError (("No password given to password option"));
		break;
	    case 'd':
		if (optarg)
		    dir = optarg;
		else
		    wvError (("No directory given to dir option"));
		break;
	    default:
		do_help ();
		return -1;
	    }
      }

    if (optind >= argc)
      {
	  fprintf (stderr, "No file name given to open\n");
	  return -1;
      }

    fname = argv[optind];

    input = fopen (fname, "rb");
    if (!input)
      {
	fprintf (stderr, "Failed to open %s\n", fname);
	  return -1;
      }
    fclose (input);

    wvInit ();
    ret = wvInitParser (&ps, fname);
    ps.filename = fname;
    ps.dir = dir;

    /* set to 0 */
    memset (&ud, 1, sizeof (rtfUserData));
    ps.userData = &ud;

    if (ret & 0x8000)		/* Password protected? */
      {
	  if ((ret & 0x7fff) == WORD8)
	    {
		ret = 0;
		if (password == NULL)
		  {
		      fprintf (stderr,
			       "Password required, this is an encrypted document\n");
		      return -1;
		  }
		else
		  {
		      wvSetPassword (password, &ps);
		      if (wvDecrypt97 (&ps))
			{
			    wvError (("Incorrect Password\n"));
			    return -1;
			}
		  }
	    }
	  else if (((ret & 0x7fff) == WORD7) || ((ret & 0x7fff) == WORD6))
	    {
		ret = 0;
		if (password == NULL)
		  {
		      fprintf (stderr,
			       "Password required, this is an encrypted document\n");
		      return -1;
		  }
		else
		  {
		      wvSetPassword (password, &ps);
		      if (wvDecrypt95 (&ps))
			{
			    wvError (("Incorrect Password\n"));
			    return -1;
			}
		  }
	    }
      }

    if (ret)
      {
	  wvError (("startup error\n"));
	  wvOLEFree (&ps);
	  return -1;
      }

    wvSetElementHandler (&ps, eleProc);
    wvSetDocumentHandler (&ps, docProc);
    wvSetCharHandler (&ps, charProc);
    wvSetSpecialCharHandler (&ps, specCharProc);

    wvText (&ps);

    /* free associated memory */
    wvOLEFree (&ps);

    return 0;
}