File: FilterRTF.cs

package info (click to toggle)
beagle 0.2.12-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 12,204 kB
  • ctags: 16,188
  • sloc: cs: 91,628; sh: 27,627; ansic: 10,646; makefile: 2,248; xml: 15
file content (527 lines) | stat: -rw-r--r-- 14,899 bytes parent folder | download
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

//
// Beagle
//
// FilterRTF.cs : Trivial implementation of a RTF-document filter.
//
// Copyright (C) 2004 Novell, Inc.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// Currently, the filtering is based on only few *control words*. If anyone
// has any samples that can break this "assumption", kindly post a copy of it, 
// if you can, to <vvaradhan@novell.com>
//
// FIXME:  Require more complex samples to test the parsing, mostly generated
//         using Microsoft Word or wordpad. :)

using System;
using System.Collections;
using System.IO;
using System.Text;

using Beagle.Util;
using Beagle.Daemon;

internal class RTFControlWordType {
	
	public enum Type {
		None,
		Skip,
		MetaDataBlock,
		MetaDataTag,
		Paragraph,
		ParaEnd,
		SplSection,
		EscSeq,
		CharProp
	}

	public Type Types;
	public string ctrlWord;
	
	RTFControlWordType (Type types, string ctrlword)
	{
		this.Types = types;
		this.ctrlWord = ctrlword;
	}

	// FIXME: Need to add "unicode", "styles", 
	// "header", "footer" etc.
	static RTFControlWordType[] types = 
	{
		new RTFControlWordType (Type.None, ""),
		new RTFControlWordType (Type.MetaDataBlock, "info"),
		new RTFControlWordType (Type.MetaDataTag, "title"),
		new RTFControlWordType (Type.MetaDataTag, "author"),
		new RTFControlWordType (Type.MetaDataTag, "comment"),
		new RTFControlWordType (Type.MetaDataTag, "operator"),
		new RTFControlWordType (Type.MetaDataTag, "nofpages"),
		new RTFControlWordType (Type.MetaDataTag, "nofwords"),
		new RTFControlWordType (Type.MetaDataTag, "generator"),
		new RTFControlWordType (Type.MetaDataTag, "company"),
		new RTFControlWordType (Type.ParaEnd, "par"),
		new RTFControlWordType (Type.Paragraph, "pard"),
		new RTFControlWordType (Type.SplSection, "header"),
		new RTFControlWordType (Type.SplSection, "footer"),
		new RTFControlWordType (Type.SplSection, "headerl"),
		new RTFControlWordType (Type.SplSection, "footerl"),
		new RTFControlWordType (Type.SplSection, "footnote"),
		new RTFControlWordType (Type.CharProp, "b"),
		new RTFControlWordType (Type.CharProp, "i"),
		new RTFControlWordType (Type.CharProp, "ul"),
		new RTFControlWordType (Type.CharProp, "up"),
		new RTFControlWordType (Type.CharProp, "dn"),
		new RTFControlWordType (Type.Skip, "'"),
		new RTFControlWordType (Type.Skip, "*"),
		new RTFControlWordType (Type.EscSeq, "{"),
		new RTFControlWordType (Type.EscSeq, "}"),
		new RTFControlWordType (Type.EscSeq, "\\"),
	};

	public static RTFControlWordType Find (string strCtrlWord)
	{
		for (int i = 0; i < types.Length; i++) {
			if (String.Compare (types[i].ctrlWord, strCtrlWord) == 0)
				return types[i];
		}
		return types[0];
	}
}
namespace Beagle.Filters {

	public class FilterRTF : Beagle.Daemon.Filter {
		
		public enum Position {
			None,
			InMetaData,
			InMetaDataTagGenerator,
			InBody,
			InPara
		}

		public enum ErrorCodes {
			ERROR_RTF_OK,
			ERROR_RTF_EOF,
			ERROR_RTF_UNHANDLED_SYMBOL
		};
		
		Position pos;
		int groupCount;
		int skipCount;
		int hotStyleCount;
		bool bPartHotStyle;
		FileStream FsRTF;
		StreamReader SReaderRTF;
	        string partText;

		Stack MetaDataStack;
		Stack TextDataStack;

		public FilterRTF ()
		{
			// Make this a general rtf filter.
			AddSupportedFlavor (FilterFlavor.NewFromMimeType ("application/rtf"));

			pos = Position.None;
			groupCount = 0;
			skipCount = 0;
			hotStyleCount = 0;
			bPartHotStyle = false;
			FsRTF = null;
			SReaderRTF = null;
			partText = "";

			MetaDataStack = new Stack ();
			TextDataStack = new Stack ();

			SnippetMode = true;
		}

		override protected void DoOpen (FileInfo info) 
		{
			try {
				FsRTF = new FileStream (info.FullName, FileMode.Open, 
							FileAccess.Read);
				if (FsRTF != null)
					SReaderRTF = new StreamReader (FsRTF);
				else {
					Logger.Log.Error ("Unable to open {0}.", info.FullName);
					Finished ();
				}
			} catch (Exception) {
				Logger.Log.Error ("Unable to open {0}.", info.FullName);
				Finished ();
			}
			
		}

		// Identifies the type of RTF control word and handles accordingly
		private ErrorCodes HandleControlWord (string strCtrlWord, int paramVal, bool bMeta)
		{
			RTFControlWordType ctrlWrdType = RTFControlWordType.Find (strCtrlWord);
			
			switch (ctrlWrdType.Types) {
			case RTFControlWordType.Type.MetaDataBlock: /* process meta-data */
				pos = Position.InMetaData;
				break;
			case RTFControlWordType.Type.MetaDataTag:
				if (pos == Position.InMetaData) {
					if (String.Compare (strCtrlWord, "title") == 0)
						MetaDataStack.Push ("dc:title");
					else if (String.Compare (strCtrlWord, "author") == 0)
						MetaDataStack.Push ("dc:author");
					else if (String.Compare (strCtrlWord, "comment") == 0)
						MetaDataStack.Push ("fixme:comment");
					else if (String.Compare (strCtrlWord, "operator") == 0)
						MetaDataStack.Push ("fixme:operator");
					else if (String.Compare (strCtrlWord, "nofpages") == 0) {
						MetaDataStack.Push (Convert.ToString (paramVal));
						MetaDataStack.Push ("fixme:page-count");
					}
					else if (String.Compare (strCtrlWord, "nofwords") == 0) {
						MetaDataStack.Push (Convert.ToString (paramVal));
						MetaDataStack.Push ("fixme:word-count");
					}
					else if (String.Compare (strCtrlWord, "company") == 0)
						MetaDataStack.Push ("fixme:company");
				} else if (String.Compare (strCtrlWord, "generator") == 0) {
					pos = Position.InMetaDataTagGenerator;
					MetaDataStack.Push ("fixme:generator");
				}
				break;

			case RTFControlWordType.Type.Paragraph:
				if (!bMeta)
					pos = Position.InPara;
				break;

			case RTFControlWordType.Type.ParaEnd:
				if (!bMeta)
					pos = Position.InBody;
				break;

				// FIXME: "Hot" styles are not *properly reset to normal*
				// on some *wierd* conditions.
				// To avoid such stuff, we need to maintain a stack of 
				// groupCounts for set/reset Hot styles.
			case RTFControlWordType.Type.SplSection:
				hotStyleCount = groupCount - 1;
				break;

			case RTFControlWordType.Type.CharProp:
				if (pos == Position.InPara) {
					if (paramVal < 0) {
						//Console.WriteLine ("HotUp: \\{0}{1}", strCtrlWord, paramVal);
						hotStyleCount = groupCount - 1;
						//HotUp ();
					}
				}
				break;

			case RTFControlWordType.Type.EscSeq:
				if (pos == Position.InPara) {
					TextDataStack.Push (strCtrlWord);
					TextDataStack.Push ("EscSeq");
				}
				break;
			case RTFControlWordType.Type.Skip:
				skipCount = groupCount - 1;
				//SkipDataStack.Push (groupCount-1);
				break;
			}
			return ErrorCodes.ERROR_RTF_OK;
		}

		// FIXME: Probably need a little cleanup ;-)

		private ErrorCodes ProcessControlWords (bool bMeta)
		{
			int aByte = -1;
			char ch;
			int paramVal = -1;
			bool negParamVal = false;
			StringBuilder strCtrlWord = new StringBuilder ();
			StringBuilder strParameter = new StringBuilder ();
			
			aByte = SReaderRTF.Read ();
			if (aByte == -1)
				return ErrorCodes.ERROR_RTF_EOF;
			
			ch = (char) aByte;
			RTFControlWordType ctrlWrdType = RTFControlWordType.Find (new String (ch, 1));

			if (!Char.IsLetter (ch) && 
			    ctrlWrdType.Types != RTFControlWordType.Type.Skip &&
			    ctrlWrdType.Types != RTFControlWordType.Type.EscSeq) {
				Logger.Log.Error ("Unhandled symbol: {0}, {1}", ch, ctrlWrdType.Types);
				return ErrorCodes.ERROR_RTF_UNHANDLED_SYMBOL;
			}
			while (aByte != -1) {
				strCtrlWord.Append (ch);
				aByte = SReaderRTF.Peek ();
				ch = (char) aByte; 
				if (Char.IsLetter (ch)) {
					aByte = SReaderRTF.Read ();
					ch = (char) aByte;
				}
				else
					break;
			}
			aByte = SReaderRTF.Peek ();
			ch = (char) aByte;
			if (aByte != -1 && ch == '-') {
				negParamVal = true;
				aByte = SReaderRTF.Read (); // move the fp
				aByte = SReaderRTF.Peek ();
				ch = (char) aByte;
			}
			if (Char.IsDigit (ch)) {
				aByte = SReaderRTF.Read ();
				ch = (char) aByte;
				while (aByte != -1) {
					strParameter.Append (ch);
					aByte = SReaderRTF.Peek ();
					ch = (char) aByte;
					if (Char.IsDigit (ch)) {
						aByte = SReaderRTF.Read ();
						ch = (char) aByte;
					}
					else
						break;
				}
				if (strParameter.Length > 0)
					paramVal = Convert.ToInt32 (strParameter.ToString());
			}
			//Console.WriteLine ("{0}\t{1}", strCtrlWord, strParameter);
			if (negParamVal && paramVal > -1)
				paramVal *= -1;
			return (HandleControlWord (strCtrlWord.ToString(), paramVal, bMeta));
		}

		private ErrorCodes RTFParse (bool bMeta)
		{
			int aByte = -1;
			char ch;
			StringBuilder str = new StringBuilder ();
			string strTemp = null;
			ErrorCodes ec;
		       
			while ((aByte = SReaderRTF.Read ()) != -1) {
				ch = (char) aByte;
				switch (ch) {
				case '\\': /* process keywords */
					if (skipCount > 0) {
						if (groupCount > skipCount)
							continue;
						else
							skipCount = 0;
					}
					ec = ProcessControlWords (bMeta); 
					if (ec != ErrorCodes.ERROR_RTF_OK)
						return ec;
					if (pos == Position.InPara)
						AddTextForIndexing (str);
					str.Remove (0, str.Length);
					break;
				case '{': /* process groups */
					if (pos == Position.InPara)
						AddTextForIndexing (str);
					str.Remove (0, str.Length);
					groupCount++;
					break;
				case '}': /* process groups */
					groupCount--;
					if (pos == Position.InMetaData ||
					    pos == Position.InMetaDataTagGenerator) {
						// groupCount will atleast be 1 for 
						// the outermost "{" block
						if (pos == Position.InMetaData && groupCount == 1) {
							if (bMeta)
								return ErrorCodes.ERROR_RTF_OK;
						} else {
							if (MetaDataStack.Count > 0) {
								strTemp = (string) MetaDataStack.Pop ();
								if ((String.Compare (strTemp, "fixme:word-count") == 0) ||
								    (String.Compare (strTemp, "fixme:page-count") == 0)) {
									str.Append ((string) MetaDataStack.Pop ());
									AddProperty (Beagle.Property.NewUnsearched (strTemp,
														 str.ToString()));
								}
								else
									AddProperty (Beagle.Property.New (strTemp, 
													  str.ToString()));
							}
						}
						
					} else if (pos == Position.InPara) {
						AddTextForIndexing (str);

					} else if (pos == Position.InBody) {
						//Console.WriteLine ("\\par : {0}", str);
						if (str.Length > 0)
							str.Append (' ');
						AddTextForIndexing (str);
						AppendStructuralBreak ();
					}
					if (hotStyleCount > 0
					    && groupCount <= hotStyleCount) {
						//Console.WriteLine ("Group count: {0}, stack: {1}", 
						//groupCount, hotStyleCount);
						HotDown ();
						hotStyleCount = 0;
					}
					
					break;
				case '\r': /* ignore \r */
				case '\n': /* ignore \n */
					break;
				default:
					if ((skipCount == 0 || groupCount <= skipCount)
					    && (pos == Position.InPara || pos == Position.InBody))
						str.Append (ch);
					break;
				}
			}
			if (partText.Length > 0) {
				if (bPartHotStyle && !IsHot) 
					HotUp ();
				AppendText (partText);
				if (IsHot)
					HotDown ();
			}
			return ErrorCodes.ERROR_RTF_OK;
		}

		private void AddTextForIndexing (StringBuilder str)
		{
			string strTemp;
			string paramStr = null;

			bool wasHot = false;

			while (TextDataStack.Count > 0) {
				strTemp = (string) TextDataStack.Pop ();
				switch (strTemp) {
				case "EscSeq":
					strTemp = (string) TextDataStack.Pop ();
					str.Append (strTemp);
					break;
				}
			}
			
			strTemp = "";
			if (str.Length > 0) {
				//Console.WriteLine ("Text: [{0}]", str);

				paramStr = str.ToString ();
				str.Remove (0, str.Length);

				int index = paramStr.LastIndexOf (' ');
				int sindex = 0;

				if (index > -1) {
					// During the previous-parsing, a word got terminatted partially,
					// find the remaining part of the word, concatenate it and add it to 
					// the respective pools and reset the HOT status, if required.
					if (partText.Length > 0) {
						sindex = paramStr.IndexOf (' ');
						strTemp = partText + paramStr.Substring (0, sindex);
						//Console.WriteLine ("PartHotStyle: {0}, HotStyleCount: {1}, partText: {2}",
						//   bPartHotStyle,
						//	   hotStyleCount, strTemp);
						if (!IsHot) {
							if (bPartHotStyle)
								HotUp ();
						}
						else
							wasHot = true;

						AppendText (strTemp);
						if (!wasHot && bPartHotStyle)
							HotDown ();
						bPartHotStyle = false;
					}
					paramStr = paramStr.Substring (sindex);
					index = paramStr.LastIndexOf (' ');
					sindex = 0;
				}
				if (index > -1) {
					partText = paramStr.Substring (index);
					paramStr = paramStr.Substring (sindex, index);
				} else {
					strTemp = partText + paramStr;
					partText = strTemp;
					paramStr = "";
					strTemp = "";
				}
					
				// Enable *HOT* just before appending the text
				// because, there can be some *Partial Texts* without
				// *HOT* styles that needs to be appended.
				if (hotStyleCount > 0) {
					if (!IsHot)
						HotUp ();
					bPartHotStyle = true;
				} else 
					bPartHotStyle |= false;

				if (paramStr.Length > 0)
					AppendText (paramStr);

				if (partText.Length < 1)
					bPartHotStyle = false;
			}
		}

		override protected void DoPull ()
		{
			ErrorCodes ec;
			ec = ErrorCodes.ERROR_RTF_OK;
			pos = Position.None;

			// Discard the buffered data, if not,
			// the buffered data can change the 
			// state "pos" variable that results 
			// in complete mess.
			// Fixes: http://bugzilla.gnome.org/show_bug.cgi?id=172294
			SReaderRTF.DiscardBufferedData ();

			// Rewind the file pointer to start from beginning.
			SReaderRTF.BaseStream.Seek (0, SeekOrigin.Begin);

			ec = RTFParse (false);
			if (ec != ErrorCodes.ERROR_RTF_OK)
				Logger.Log.Error ("{0}", ec);
			Finished ();
		}
		
		override protected void DoPullProperties ()
		{
			ErrorCodes ec;
			ec = ErrorCodes.ERROR_RTF_OK;
			ec = RTFParse (true);
			if (ec != ErrorCodes.ERROR_RTF_OK)
				Logger.Log.Error ("{0}", ec);
		}

	}
}