Debian Codegraph @

src/lib/TeachTxtParser.cxx

raw
1 /* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */
2
3 /* libmwaw
4 * Version: MPL 2.0 / LGPLv2+
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 2.0 (the "License"); you may not use this file except in compliance with
8 * the License or as specified alternatively below. You may obtain a copy of
9 * the License at http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * Major Contributor(s):
17 * Copyright (C) 2002 William Lachance ([email protected])
18 * Copyright (C) 2002,2004 Marc Maurer ([email protected])
19 * Copyright (C) 2004-2006 Fridrich Strba ([email protected])
20 * Copyright (C) 2006, 2007 Andrew Ziem
21 * Copyright (C) 2011, 2012 Alonso Laurent ([email protected])
22 *
23 *
24 * All Rights Reserved.
25 *
26 * For minor contributions see the git repository.
27 *
28 * Alternatively, the contents of this file may be used under the terms of
29 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
30 * in which case the provisions of the LGPLv2+ are applicable
31 * instead of those above.
32 */
33
34 #include <iomanip>
35 #include <iostream>
36 #include <limits>
37 #include <set>
38 #include <sstream>
39
40 #include <librevenge/librevenge.h>
41
42 #include "MWAWTextListener.hxx"
43 #include "MWAWFont.hxx"
44 #include "MWAWFontConverter.hxx"
45 #include "MWAWHeader.hxx"
46 #include "MWAWParagraph.hxx"
47 #include "MWAWPictData.hxx"
48 #include "MWAWPosition.hxx"
49 #include "MWAWPrinter.hxx"
50 #include "MWAWRSRCParser.hxx"
51 #include "MWAWSubDocument.hxx"
52
53 #include "TeachTxtParser.hxx"
54
55 /** Internal: the structures of a TeachTxtParser */
56 namespace TeachTxtParserInternal
57 {
58 ////////////////////////////////////////
59 //! Internal: the state of a TeachTxtParser
60 struct State {
61 //! constructor
62 State()
63 : m_type(MWAWDocument::MWAW_T_UNKNOWN)
64 , m_posFontMap()
65 , m_idPictEntryMap()
66 , m_numberSpacesForTab(0)
67 , m_actPage(0)
68 , m_numPages(0)
69 {
70 }
71 //! the file type
72 MWAWDocument::Type m_type;
73 //! the map of id -> font
74 std::map<long, MWAWFont > m_posFontMap;
75 //! a map id->pictEntry
76 std::map<int,MWAWEntry> m_idPictEntryMap;
77 //! number of space to used to replace tab (0: means keep tabs )
78 int m_numberSpacesForTab;
79 int m_actPage /** the actual page */, m_numPages /** the number of page of the final document */;
80 };
81
82 }
83
84 ////////////////////////////////////////////////////////////
85 // constructor/destructor, ...
86 ////////////////////////////////////////////////////////////
87 TeachTxtParser::TeachTxtParser(MWAWInputStreamPtr const &input, MWAWRSRCParserPtr const &rsrcParser, MWAWHeader *header)
88 : MWAWTextParser(input, rsrcParser, header), m_state()
89 {
90 init();
91 }
92
93 TeachTxtParser::~TeachTxtParser()
94 {
95 }
96
97 void TeachTxtParser::init()
98 {
99 resetTextListener();
100 setAsciiName("main-1");
101
102 m_state.reset(new TeachTxtParserInternal::State);
103
104 getPageSpan().setMargins(0.1);
105 }
106
107 MWAWInputStreamPtr TeachTxtParser::rsrcInput()
108 {
109 return getRSRCParser()->getInput();
110 }
111
112 libmwaw::DebugFile &TeachTxtParser::rsrcAscii()
113 {
114 return getRSRCParser()->ascii();
115 }
116
117 ////////////////////////////////////////////////////////////
118 // new page
119 ////////////////////////////////////////////////////////////
120 void TeachTxtParser::newPage(int number)
121 {
122 if (number <= m_state->m_actPage || number > m_state->m_numPages)
123 return;
124
125 while (m_state->m_actPage < number) {
126 m_state->m_actPage++;
127 if (!getTextListener() || m_state->m_actPage == 1)
128 continue;
129 getTextListener()->insertBreak(MWAWTextListener::PageBreak);
130 }
131 }
132
133 ////////////////////////////////////////////////////////////
134 // the parser
135 ////////////////////////////////////////////////////////////
136 void TeachTxtParser::parse(librevenge::RVNGTextInterface *docInterface)
137 {
138 if (!getInput().get() || !getRSRCParser() || !checkHeader(nullptr)) throw(libmwaw::ParseException());
139 bool ok = false;
140 try {
141 // create the asciiFile
142 ascii().setStream(getInput());
143 ascii().open(asciiName());
144 checkHeader(nullptr);
145 ok = createZones();
146 if (ok) {
147 createDocument(docInterface);
148 sendText();
149 #ifdef DEBUG
150 flushExtra();
151 #endif
152 }
153 ascii().reset();
154 }
155 catch (...) {
156 MWAW_DEBUG_MSG(("TeachTxtParser::parse: exception catched when parsing\n"));
157 ok = false;
158 }
159
160 resetTextListener();
161 if (!ok) throw(libmwaw::ParseException());
162 }
163
164 ////////////////////////////////////////////////////////////
165 // create the document
166 ////////////////////////////////////////////////////////////
167 void TeachTxtParser::createDocument(librevenge::RVNGTextInterface *documentInterface)
168 {
169 if (!documentInterface) return;
170 if (getTextListener()) {
171 MWAW_DEBUG_MSG(("TeachTxtParser::createDocument: listener already exist\n"));
172 return;
173 }
174
175 // update the page
176 m_state->m_actPage = 0;
177
178 // create the page list
179 int numPages=computeNumPages();
180 m_state->m_numPages = numPages;
181 MWAWPageSpan ps(getPageSpan());
182 ps.setPageSpan(m_state->m_numPages+1);
183 std::vector<MWAWPageSpan> pageList(1,ps);
184 MWAWTextListenerPtr listen(new MWAWTextListener(*getParserState(), pageList, documentInterface));
185 setTextListener(listen);
186 listen->startDocument();
187 }
188
189
190 ////////////////////////////////////////////////////////////
191 //
192 // Intermediate level
193 //
194 ////////////////////////////////////////////////////////////
195 bool TeachTxtParser::createZones()
196 {
197 MWAWRSRCParserPtr rsrcParser = getRSRCParser();
198 auto const &entryMap = rsrcParser->getEntriesMap();
199
200 // the chapter zone zone
201 auto it = entryMap.lower_bound("styl");
202 while (it != entryMap.end()) {
203 if (it->first != "styl")
204 break;
205 MWAWEntry const &entry = it++->second;
206 readStyles(entry);
207 }
208 // the different pict zones
209 it = entryMap.lower_bound("PICT");
210 while (it != entryMap.end()) {
211 if (it->first != "PICT")
212 break;
213 MWAWEntry const &entry = it++->second;
214 m_state->m_idPictEntryMap[entry.id()]=entry;
215 }
216 // a unknown zone in Tex-Edit with id=1000
217 it = entryMap.lower_bound("wrct");
218 while (it != entryMap.end()) {
219 if (it->first != "wrct")
220 break;
221 MWAWEntry const &entry = it++->second;
222 readWRCT(entry);
223 }
224 // we can have also some sound in snd:10000
225 /** checkme: find also two times BBSR:0x250 with size 0x168,
226 probably not in the format.. */
227 return true;
228 }
229
230 void TeachTxtParser::flushExtra()
231 {
232 #ifdef DEBUG
233 for (auto const &it : m_state->m_idPictEntryMap) {
234 MWAWEntry const &entry=it.second;
235 if (entry.isParsed()) continue;
236 sendPicture(entry.id());
237 }
238 #endif
239 }
240
241 int TeachTxtParser::computeNumPages() const
242 {
243 MWAWInputStreamPtr input = const_cast<TeachTxtParser *>(this)->getInput();
244 input->seek(0, librevenge::RVNG_SEEK_SET);
245 int nPages=1;
246 int pageBreakChar=(m_state->m_type==MWAWDocument::MWAW_T_TEXEDIT) ? 0xc : 0;
247
248 while (!input->isEnd()) {
249 if (input->readLong(1)==pageBreakChar)
250 nPages++;
251 }
252 return nPages;
253 }
254
255 bool TeachTxtParser::sendText()
256 {
257 if (!getTextListener()) {
258 MWAW_DEBUG_MSG(("TeachTxtParser::sendText: can not find the listener\n"));
259 return false;
260 }
261 MWAWInputStreamPtr input = getInput();
262 input->seek(0, librevenge::RVNG_SEEK_SET);
263 long debPos=0;
264
265 libmwaw::DebugStream f;
266 f << "Entries(TEXT):";
267 getTextListener()->setFont(MWAWFont(3,12));
268
269 std::map<long, MWAWFont >::const_iterator fontIt;
270 int nPict=0;
271 unsigned char pageBreakChar=(m_state->m_type==MWAWDocument::MWAW_T_TEXEDIT) ? 0xc : 0;
272
273 int actPage=1;
274 long endPos = input->size();
275 for (long i=0; i < endPos; i++) {
276 bool isEnd = input->isEnd();
277 unsigned char c=isEnd ? static_cast<unsigned char>(0) : static_cast<unsigned char>(input->readULong(1));
278 if (isEnd || c==0xd || c==pageBreakChar) {
279 ascii().addPos(debPos);
280 ascii().addNote(f.str().c_str());
281 debPos = input->tell();
282 if (isEnd) break;
283 f.str("");
284 f << "TEXT:";
285 }
286 fontIt=m_state->m_posFontMap.find(i);
287 if (fontIt != m_state->m_posFontMap.end()) {
288 f << "[Style,cPos=" << std::hex << i << std::dec << "]";
289 getTextListener()->setFont(fontIt->second);
290 }
291 if (c)
292 f << c;
293 if (c==pageBreakChar) {
294 newPage(++actPage);
295 continue;
296 }
297 if (c==0 && m_state->m_type==MWAWDocument::MWAW_T_TEXEDIT && !isEnd) {
298 // tex-edit accept control character, ...
299 auto nextC=static_cast<unsigned char>(input->readULong(1));
300 if (nextC < 0x20) {
301 i++;
302 getTextListener()->insertChar('^');
303 getTextListener()->insertChar(uint8_t('@'+nextC));
304 continue;
305 }
306 input->seek(-1, librevenge::RVNG_SEEK_CUR);
307 }
308 switch (c) {
309 case 0x9:
310 if (m_state->m_numberSpacesForTab>0) {
311 for (int j = 0; j < m_state->m_numberSpacesForTab; j++)
312 getTextListener()->insertChar(' ');
313 }
314 else
315 getTextListener()->insertTab();
316 break;
317 case 0xd:
318 getTextListener()->insertEOL();
319 break;
320 case 0x11: // command key
321 getTextListener()->insertUnicode(0x2318);
322 break;
323 case 0x14: // apple logo: check me
324 getTextListener()->insertUnicode(0xf8ff);
325 break;
326 case 0xca:
327 sendPicture(1000+nPict++);
328 break;
329 default:
330 if (c < 0x20) f << "##[" << std::hex << int(c) << std::dec << "]";
331 i += getTextListener()->insertCharacter(c, input, endPos);
332 break;
333 }
334 }
335 return true;
336 }
337 ////////////////////////////////////////////////////////////
338 //
339 // Low level
340 //
341 ////////////////////////////////////////////////////////////
342
343 // the styles
344 bool TeachTxtParser::readStyles(MWAWEntry const &entry)
345 {
346 if (!entry.valid() || entry.length()<2) {
347 MWAW_DEBUG_MSG(("TeachTxtParser::readStyles: the entry is bad\n"));
348 return false;
349 }
350 entry.setParsed(true);
351 long pos = entry.begin();
352 MWAWInputStreamPtr input = rsrcInput();
353 libmwaw::DebugFile &ascFile = rsrcAscii();
354 input->seek(pos, librevenge::RVNG_SEEK_SET);
355
356 libmwaw::DebugStream f;
357 auto N=static_cast<int>(input->readULong(2));
358 f << "Entries(Style)[" << entry.type() << "-" << entry.id() << "]:N="<<N;
359 if (20*N+2 != entry.length()) {
360 MWAW_DEBUG_MSG(("TeachTxtParser::readStyles: the number of values seems bad\n"));
361 f << "###";
362 ascFile.addPos(pos-4);
363 ascFile.addNote(f.str().c_str());
364 }
365 ascFile.addPos(pos-4);
366 ascFile.addNote(f.str().c_str());
367 for (int i = 0; i < N; i++) {
368 MWAWFont font;
369 f.str("");
370 pos = input->tell();
371 long cPos = input->readLong(4);
372 int dim[2];
373 for (auto &d : dim) d = static_cast<int>(input->readLong(2));
374 f << "height?=" << dim[0] << ":" << dim[1] << ",";
375 font.setId(static_cast<int>(input->readULong(2)));
376 auto flag=static_cast<int>(input->readULong(1));
377 uint32_t flags = 0;
378 if (flag&0x1) flags |= MWAWFont::boldBit;
379 if (flag&0x2) flags |= MWAWFont::italicBit;
380 if (flag&0x4) font.setUnderlineStyle(MWAWFont::Line::Simple);
381 if (flag&0x8) flags |= MWAWFont::embossBit;
382 if (flag&0x10) flags |= MWAWFont::shadowBit;
383 if (flag&0x20) font.setDeltaLetterSpacing(-1.);
384 if (flag&0x40) font.setDeltaLetterSpacing(1.);
385 if (flag&0x80) f << "#flags=" << std::hex << (flag&0x80) << std::dec << ",";
386 flag=static_cast<int>(input->readULong(1));
387 if (flag) f << "#flags1=" << std::hex << flag << std::dec << ",";
388 font.setSize(float(input->readULong(2)));
389 font.setFlags(flags);
390 unsigned char col[3];
391 for (auto &c : col) c = static_cast<unsigned char>(input->readULong(2)>>8);
392 font.setColor(MWAWColor(col[0],col[1],col[2]));
393 font.m_extra=f.str();
394 if (m_state->m_posFontMap.find(cPos) != m_state->m_posFontMap.end()) {
395 MWAW_DEBUG_MSG(("TeachTxtParser::readStyles: a style for pos=%lx already exist\n", static_cast<long unsigned int>(cPos)));
396 }
397 else
398 m_state->m_posFontMap[cPos] = font;
399 f.str("");
400 f << "Style-" << i << ":" << "cPos=" << std::hex << cPos << std::dec << ",";
401 #ifdef DEBUG
402 f << ",font=[" << font.getDebugString(getFontConverter()) << "]";
403 #endif
404 ascFile.addPos(pos);
405 ascFile.addNote(f.str().c_str());
406 }
407 return true;
408 }
409
410 // unknown structure 4 int, related to some counter ?
411 bool TeachTxtParser::readWRCT(MWAWEntry const &entry)
412 {
413 if (!entry.valid() || entry.length()<8) {
414 MWAW_DEBUG_MSG(("TeachTxtParser::readWRCT: the entry is bad\n"));
415 return false;
416 }
417 entry.setParsed(true);
418 long pos = entry.begin();
419 MWAWInputStreamPtr input = rsrcInput();
420 libmwaw::DebugFile &ascFile = rsrcAscii();
421 input->seek(pos, librevenge::RVNG_SEEK_SET);
422
423 libmwaw::DebugStream f;
424 // f0=27|29|2c, f1=1|3|7, f2xf3: big number, a dim?
425 f << "Entries(WRCT)[" << entry.type() << "-" << entry.id() << "]:";
426 for (int i = 0; i < 4; i++)
427 f << "f" << i << "=" << input->readLong(2) << ",";
428
429 ascFile.addPos(pos-4);
430 ascFile.addNote(f.str().c_str());
431 return true;
432 }
433
434 // the pictures
435 bool TeachTxtParser::sendPicture(int id)
436 {
437 if (m_state->m_idPictEntryMap.find(id)==m_state->m_idPictEntryMap.end()) {
438 MWAW_DEBUG_MSG(("TeachTxtParser::sendPicture: can not find picture for id=%d\n",id));
439 return false;
440 }
441 if (!getTextListener()) {
442 MWAW_DEBUG_MSG(("TeachTxtParser::sendPicture: can not find the listener\n"));
443 return false;
444 }
445
446 MWAWInputStreamPtr input = rsrcInput();
447 MWAWRSRCParserPtr rsrcParser = getRSRCParser();
448 MWAWEntry const &entry=m_state->m_idPictEntryMap.find(id)->second;
449
450 librevenge::RVNGBinaryData data;
451 long pos = input->tell();
452 rsrcParser->parsePICT(entry,data);
453 input->seek(pos,librevenge::RVNG_SEEK_SET);
454
455 auto dataSz=int(data.size());
456 if (!dataSz)
457 return false;
458 MWAWInputStreamPtr pictInput=MWAWInputStream::get(data, false);
459 if (!pictInput)
460 return false;
461 MWAWBox2f box;
462 auto res = MWAWPictData::check(pictInput, dataSz,box);
463 if (res == MWAWPict::MWAW_R_BAD) {
464 MWAW_DEBUG_MSG(("TeachTxtParser::sendPicture: can not find the picture\n"));
465 return false;
466 }
467 pictInput->seek(0,librevenge::RVNG_SEEK_SET);
468 std::shared_ptr<MWAWPict> thePict(MWAWPictData::get(pictInput, dataSz));
469 MWAWPosition pictPos=MWAWPosition(MWAWVec2f(0,0),box.size(), librevenge::RVNG_POINT);
470 pictPos.setRelativePosition(MWAWPosition::Paragraph, MWAWPosition::XCenter);
471 pictPos.m_wrapping = MWAWPosition::WRunThrough;
472 if (thePict) {
473 MWAWEmbeddedObject picture;
474 if (thePict->getBinary(picture))
475 getTextListener()->insertPicture(pictPos, picture);
476 }
477 return true;
478 }
479
480
481 ////////////////////////////////////////////////////////////
482 // read the header
483 ////////////////////////////////////////////////////////////
484 bool TeachTxtParser::checkHeader(MWAWHeader *header, bool strict)
485 {
486 *m_state = TeachTxtParserInternal::State();
487 /** no data fork, may be ok, but this means
488 that the file contains no text, so... */
489 MWAWInputStreamPtr input = getInput();
490 if (!input || !getRSRCParser() || !input->hasDataFork())
491 return false;
492
493 std::string type, creator;
494 if (!input->getFinderInfo(type, creator))
495 return false;
496 MWAWDocument::Type fileType(MWAWDocument::MWAW_T_UNKNOWN);
497 if (creator=="ttxt") {
498 fileType=MWAWDocument::MWAW_T_TEACHTEXT;
499 m_state->m_numberSpacesForTab=2;
500 }
501 else if (creator=="TBB5")
502 fileType=MWAWDocument::MWAW_T_TEXEDIT;
503 else
504 return false;
505 if (strict && fileType==MWAWDocument::MWAW_T_TEACHTEXT && type!="ttro") {
506 /** visibly, some other applications can create ttxt file,
507 so check that we have at least a styl rsrc or a PICT */
508 MWAWEntry entry = getRSRCParser()->getEntry("styl", 128);
509 if (!entry.valid()) {
510 entry = getRSRCParser()->getEntry("PICT", 1000);
511 MWAW_DEBUG_MSG(("TeachTxtParser::checkHeader: can not find any basic ressource, stop\n"));
512 if (!entry.valid())
513 return false;
514 }
515 }
516 m_state->m_type=fileType;
517 setVersion(1);
518 if (header)
519 header->reset(fileType, version());
520
521 return true;
522 }
523
524 // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab: