Debian Codegraph @

src/lib/XYWrite.cpp

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* libwps
3 * Version: MPL 2.0 / LGPLv2.1+
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * Major Contributor(s):
10 * Copyright (C) 2006, 2007 Andrew Ziem
11 * Copyright (C) 2004 Marc Maurer ([email protected])
12 * Copyright (C) 2004-2006 Fridrich Strba ([email protected])
13 *
14 * For minor contributions see the git repository.
15 *
16 * Alternatively, the contents of this file may be used under the terms
17 * of the GNU Lesser General Public License Version 2.1 or later
18 * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
19 * applicable instead of those above.
20 */
21
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include <sstream>
26
27 #include <librevenge-stream/librevenge-stream.h>
28
29 #include "libwps_internal.h"
30 #include "libwps_tools_win.h"
31
32 #include "WPSCell.h"
33 #include "WPSContentListener.h"
34 #include "WPSEntry.h"
35 #include "WPSFont.h"
36 #include "WPSHeader.h"
37 #include "WPSPageSpan.h"
38 #include "WPSParagraph.h"
39 #include "WPSPosition.h"
40 #include "WPSTable.h"
41 #include "WPSTextSubDocument.h"
42
43 #include "XYWrite.h"
44
45 namespace XYWriteParserInternal
46 {
47 /** Internal: class to store a basic cell with borders */
48 struct Cell final : public WPSCell
49 {
50 //! constructor
51 explicit Cell(XYWriteParser &parser)
52 : WPSCell()
53 , m_parser(parser)
54 , m_entry()
55 , m_style()
56 {
57 }
58 //! virtual destructor
59 ~Cell() final;
60
61 //! operator<<
62 friend std::ostream &operator<<(std::ostream &o, Cell const &cell);
63 //! call when a cell must be send
64 bool send(WPSListenerPtr &listener) final
65 {
66 if (!listener) return true;
67 auto *listen=dynamic_cast<WPSContentListener *>(listener.get());
68 if (!listen)
69 {
70 WPS_DEBUG_MSG(("XYWriteParserInternal::Cell::send: unexpected listener\n"));
71 return true;
72 }
73 listen->openTableCell(*this);
74 sendContent(listener);
75 listen->closeTableCell();
76 return true;
77 }
78
79 //! call when the content of a cell must be send
80 bool sendContent(WPSListenerPtr &) final
81 {
82 auto input=m_parser.getInput();
83 if (!input)
84 {
85 WPS_DEBUG_MSG(("XYWriteParserInternal::Cell::sendContent: can not find the impu\n"));
86 return true;
87 }
88 long pos=input->tell();
89 m_parser.parseTextZone(m_entry, m_style);
90 input->seek(pos, librevenge::RVNG_SEEK_SET);
91 return true;
92 }
93
94 //! the actual parser
95 XYWriteParser &m_parser;
96 //! the text entry
97 WPSEntry m_entry;
98 //! the cell style
99 std::string m_style;
100 };
101 Cell::~Cell()
102 {
103 }
104
105 //! a structure used to store a format
106 struct Format
107 {
108 //! constructor
109 explicit Format(bool inDosFile=false)
110 : m_inDosFile(inDosFile)
111 , m_string()
112 , m_args()
113 , m_entry()
114 , m_isComplex(false)
115 , m_listCounter(-1)
116 , m_level()
117 , m_children()
118 {
119 }
120 //! return true if the format is empty
121 bool empty() const
122 {
123 return m_string.empty() && m_args.empty();
124 }
125 //! returns the upper case of a string
126 static std::string upperCase(std::string const &str)
127 {
128 std::string res(str);
129 for (auto &c : res)
130 c=char(std::toupper(c));
131 return res;
132 }
133 //! returns the title in uppercase
134 std::string title() const
135 {
136 return upperCase(m_string);
137 }
138 //! returns the two/... first character of the main string in uppercase
139 std::string shortTitle(size_t sz=2) const
140 {
141 if (m_string.size()<=sz)
142 return upperCase(m_string);
143 return upperCase(m_string.substr(0,sz));
144 }
145 //! update a font if possible
146 bool updateFont(WPSFont &font) const
147 {
148 bool ok=true;
149 auto str=title();
150 auto sTitle=shortTitle();
151 if (sTitle=="MD")
152 {
153 if (str=="MDNM")
154 font.m_attributes&=(unsigned int)(WPS_SMALL_CAPS_BIT|WPS_ALL_CAPS_BIT);
155 else if (str=="MDBO" || str=="MD+BO")
156 font.m_attributes|=WPS_BOLD_BIT;
157 else if (str=="MD-BO")
158 font.m_attributes&=~(unsigned int)(WPS_BOLD_BIT);
159 else if (str=="MDBR" || str=="MD+BR")
160 font.m_attributes|=(WPS_BOLD_BIT|WPS_ITALICS_BIT);
161 else if (str=="MD-BR")
162 font.m_attributes&=~(unsigned int)(WPS_BOLD_BIT|WPS_ITALICS_BIT);
163 else if (str=="MDBU" || str=="MD+BU")
164 font.m_attributes|=(WPS_BOLD_BIT|WPS_UNDERLINE_BIT);
165 else if (str=="MD-BU")
166 font.m_attributes&=~(unsigned int)(WPS_BOLD_BIT|WPS_UNDERLINE_BIT);
167 else if (str=="MDDN" || str=="MD+DN")
168 font.m_attributes|=WPS_STRIKEOUT_BIT;
169 else if (str=="MD-DN")
170 font.m_attributes&=~(unsigned int)(WPS_STRIKEOUT_BIT);
171 else if (str=="MDRV" || str=="MD+IT")
172 font.m_attributes|=WPS_ITALICS_BIT;
173 else if (str=="MD-IT")
174 font.m_attributes&=~(unsigned int)(WPS_ITALICS_BIT);
175 else if (str=="MD+RV")
176 font.m_attributes|=WPS_REVERSEVIDEO_BIT;
177 else if (str=="MD-RV")
178 font.m_attributes&=~(unsigned int)(WPS_REVERSEVIDEO_BIT);
179 else if (str=="MDSD" || str=="MD+SD")
180 font.m_attributes|=WPS_SUBSCRIPT_BIT;
181 else if (str=="MD-SD")
182 font.m_attributes&=~(unsigned int)(WPS_SUBSCRIPT_BIT);
183 else if (str=="MDSU" || str=="MD+SU")
184 font.m_attributes|=WPS_SUPERSCRIPT_BIT;
185 else if (str=="MD-SU")
186 font.m_attributes&=~(unsigned int)(WPS_SUPERSCRIPT_BIT);
187 else if (str=="MDUL" || str=="MD+UL")
188 font.m_attributes|=WPS_UNDERLINE_BIT;
189 else if (str=="MD-UL")
190 font.m_attributes&=~(unsigned int)(WPS_UNDERLINE_BIT);
191 else
192 ok=false;
193 }
194 else if (sTitle=="RG")
195 {
196 if (str=="RG0")
197 font.m_attributes&=~(unsigned int)(WPS_SMALL_CAPS_BIT|WPS_ALL_CAPS_BIT);
198 else if (str=="RG1")
199 {
200 font.m_attributes&=~(unsigned int)(WPS_SMALL_CAPS_BIT);
201 font.m_attributes|=WPS_ALL_CAPS_BIT;
202 }
203 else if (str=="RG2")
204 {
205 font.m_attributes&=~(unsigned int)(WPS_ALL_CAPS_BIT);
206 font.m_attributes|=WPS_SMALL_CAPS_BIT;
207 }
208 else
209 ok=false;
210 }
211 else if (sTitle=="FG")
212 ok=readColor(font.m_color);
213 else if (sTitle=="SZ")
214 {
215 double value;
216 bool inPoint;
217 std::string extra;
218 if (readUnit(str, 2, m_inDosFile, value, inPoint, extra) && inPoint)
219 font.m_size=value;
220 }
221
222 if (!ok && !m_string.empty())
223 {
224 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::updateFont: unknown format=%s\n", m_string.c_str()));
225 return false;
226 }
227 return true;
228 }
229 //! update a paragraph if possible
230 bool updateParagraph(WPSParagraph &para) const
231 {
232 bool ok=true;
233 auto str=title();
234 auto sTitle=shortTitle();
235 double value=0;
236 bool inPoint;
237 std::string tmp;
238 if (str=="FC")
239 para.m_justify=libwps::JustificationCenter;
240 else if (str=="FL")
241 para.m_justify=libwps::JustificationLeft;
242 else if (str=="FR")
243 para.m_justify=libwps::JustificationRight;
244 else if (str=="JU")
245 {
246 if (para.m_justify==libwps::JustificationLeft)
247 para.m_justify=libwps::JustificationFull;
248 }
249 else if (str=="NJ")
250 {
251 if (para.m_justify==libwps::JustificationFull)
252 para.m_justify=libwps::JustificationLeft;
253 }
254 else if (sTitle=="IP" || sTitle=="RM" || sTitle=="LS")
255 {
256 size_t p=2;
257 if (readUnit(str, p, m_inDosFile, value, inPoint, tmp, sTitle!="LS"))
258 {
259 if (sTitle=="LS")
260 para.setInterline(value, (!inPoint || (m_inDosFile && value<=3)) ? librevenge::RVNG_PERCENT : librevenge::RVNG_POINT, WPSParagraph::AtLeast);
261 else if (inPoint)
262 {
263 if (sTitle=="IP")
264 para.m_margins[0]=value/72;
265 else if (!m_inDosFile || value<150) // in dos file, size from left
266 para.m_margins[2]=value/72;
267 }
268 if (!tmp.empty())
269 {
270 WPS_DEBUG_MSG(("XYWriteParserInternal::Paragraph::updateParagraph: find extra data in %s\n", m_string.c_str()));
271 }
272 }
273 }
274 else if (sTitle=="AL")
275 {
276 if (str=="AL0" || str=="AL1")
277 para.setInterline(1, librevenge::RVNG_PERCENT);
278 }
279 else if (sTitle=="NB" || sTitle=="BB")
280 {
281 if (str=="NB0" || str=="NB1" || str=="BB")
282 para.m_breakStatus=0;
283 else if (sTitle=="NB") // no break
284 {
285 size_t p=2;
286 if (readNumber(str, p, value))
287 para.m_breakStatus=libwps::NoBreakWithNextBit;
288 else
289 ok=false;
290 }
291 else // allow break + data?
292 ok=false;
293 }
294 else if (sTitle=="LL" || sTitle=="EL")
295 {
296 // some extra spacings
297 for (size_t i=0; i<=(sTitle=="LL" ? std::min<size_t>(1,m_args.size()) : 0); ++i)
298 {
299 size_t p=i==0 ? 2 : 0;
300 if (readUnit(i==0 ? str : m_args[i-1], p, m_inDosFile, value, inPoint, tmp))
301 {
302 if (sTitle=="EL") // after a line
303 continue;
304 // LL after para
305 if (i==1)
306 para.m_spacings[2]=inPoint ? value/72 : value*12/72;
307 // FIXME update also para spacings 0 when i==0
308 }
309 }
310 }
311 else if (sTitle=="TS")
312 {
313 for (size_t i=0; i<=m_args.size(); ++i)
314 {
315 size_t p=i==0 ? 2 : 0;
316 WPSTabStop tab;
317 if (readUnit(i==0 ? m_string : m_args[i-1], p, m_inDosFile, value, inPoint, tmp))
318 {
319 if (!inPoint)
320 continue;
321 tmp=upperCase(tmp);
322 if (tmp=="R")
323 tab.m_alignment=WPSTabStop::RIGHT;
324 else if (tmp=="C")
325 tab.m_alignment=WPSTabStop::CENTER;
326 else if (tmp=="D")
327 tab.m_alignment=WPSTabStop::DECIMAL;
328 else
329 tab.m_alignment=WPSTabStop::LEFT;
330 tab.m_position=value/72.;
331 para.m_tabs.push_back(tab);
332 }
333 }
334 }
335 else if (sTitle=="BG")
336 ok=readColor(para.m_backgroundColor);
337 else
338 ok=false;
339 if (!ok && !m_string.empty())
340 {
341 WPS_DEBUG_MSG(("XYWriteParserInternal::Paragraph::updateParagraph: unknown format=%s\n", m_string.c_str()));
342 return false;
343 }
344 return true;
345 }
346 //! operator<<
347 friend std::ostream &operator<<(std::ostream &o, Format const &format)
348 {
349 o << format.m_string;
350 if (!format.m_children.empty())
351 {
352 o << "\n";
353 for (auto const &child : format.m_children)
354 o << "\t" << child << "\n";
355 return o;
356 }
357 if (format.m_isComplex && format.m_entry.valid())
358 o << "[dt=" << format.m_entry.length() << "]";
359 if (format.m_args.empty())
360 return o;
361 o << "[";
362 for (auto const &arg : format.m_args)
363 o << arg << ",";
364 o << "]";
365 return o;
366 }
367 //! flag to know if we are in a dos file
368 bool m_inDosFile;
369 //! the main part
370 std::string m_string;
371 //! the other arguments
372 std::vector<std::string> m_args;
373 //! a text zone entry
374 WPSEntry m_entry;
375 //! a flag to know if this is a complex entry
376 bool m_isComplex;
377 //! the list counter (if known)
378 mutable int m_listCounter;
379 //! the list level (if known)
380 mutable WPSList::Level m_level;
381 //! the list of child (for style, ...)
382 std::vector<Format> m_children;
383
384 ////////////////////////////////
385 // low level
386 ////////////////////////////////
387
388 //! try to read a color
389 bool readColor(WPSColor &color) const
390 {
391 if (m_args.size()!=2)
392 {
393 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::readColor: bad number of argument\n"));
394 return false;
395 }
396 unsigned char col[3];
397 for (size_t i=0; i<3; ++i)
398 {
399 size_t p=i==0 ? 2 : 0;
400 unsigned int val;
401 std::string tmp;
402 if (!readUInt(i==0 ? m_string : m_args[i-1], p, val, tmp) || val>255)
403 {
404 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::readColor: can not read a component\n"));
405 return false;
406 }
407 col[i]=(unsigned char)(val);
408 }
409 color=WPSColor(col[0],col[1],col[2]);
410 return true;
411 }
412 //! try to read a box of double in points
413 static bool readBox2f(std::string const &str, size_t i, bool inDosFile, WPSBox2f &box, std::string &extra)
414 {
415 Vec2f vec;
416 std::string remain;
417 for (int c=0; c<2; ++c)
418 {
419 if ((c==0 && (!readVec2f(str, i, inDosFile, vec, remain) || remain.substr(0,1)!=" ")) ||
420 (c==1 && (!readVec2f(remain, 1, inDosFile, vec, extra))))
421 return false;
422 if (c==0)
423 box.setMin(vec);
424 else
425 box.setMax(vec);
426 }
427 return true;
428 }
429 //! try to read a vector of double in points
430 static bool readVec2f(std::string const &str, size_t i, bool inDosFile, Vec2f &vec, std::string &extra)
431 {
432 double value=0;
433 bool inPoint;
434 std::string remain;
435 for (int c=0; c<2; ++c)
436 {
437 if ((c==0 && (!readUnit(str, i, inDosFile, value, inPoint, remain) || remain.substr(0,1)!="x")) ||
438 (c==1 && (!readUnit(remain, 1, inDosFile, value, inPoint, extra))) || !inPoint)
439 return false;
440 vec[c]=float(value);
441 }
442 return true;
443 }
444 //! try to read a vector of uint
445 static bool readVec2i(std::string const &str, size_t i, Vec2i &vec, std::string &extra)
446 {
447 unsigned int value=0;
448 std::string remain;
449 for (int c=0; c<2; ++c)
450 {
451 size_t p=c==0 ? i : 1;
452 if ((c==0 && (!readUInt(str, p, value, remain) || remain.substr(0,1)!="x")) ||
453 (c==1 && (!readUInt(remain, p, value, extra))))
454 return false;
455 vec[c]=int(value);
456 }
457 return true;
458 }
459 //! try to read a int
460 static bool readUInt(std::string const &str, size_t &i, unsigned int &value, std::string &extra)
461 {
462 auto len=str.size();
463 value=0;
464 size_t p=i;
465 while (p<len && str[p]>='0' && str[p]<='9')
466 value=value*10+(unsigned int)(str[p++]-'0');
467 if (p==i)
468 return false;
469 i=p;
470 if (i<len)
471 extra=str.substr(i);
472 return true;
473 }
474 //! try to read a double.
475 static bool readNumber(std::string const &str, size_t &i, double &value)
476 try
477 {
478 if (str.size()<=i)
479 {
480 if (!str.empty())
481 {
482 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::readNumber: the string %s is too short\n", str.c_str()));
483 }
484 return false;
485 }
486 size_t p;
487 if (i==0)
488 value = std::stod(str,&p);
489 else
490 value = std::stod(str.substr(i),&p);
491 i+=p;
492 return true;
493 }
494 catch (...)
495 {
496 if (!str.empty())
497 {
498 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::readNumber: can not extract number in %s\n", str.c_str()));
499 }
500 return false;
501 }
502 /** try to read an unit, returns a number in Point or in Line.
503 \note if unit=AUTO set value to 72pt=1in
504 */
505 static bool readUnit(std::string const &str, size_t i, bool inDosFile, double &value, bool &inPoint, std::string &extra, bool dosInChar=true)
506 {
507 if (str.size()>=i+4 && str.substr(i,4)=="AUTO")
508 {
509 value=72;
510 inPoint=true;
511 if (str.size()>i+4)
512 extra=str.substr(i+4);
513 return true;
514 }
515 if (!readNumber(str,i,value))
516 return false;
517 auto remain=upperCase(str.substr(i,2));
518 if (i+2<str.size())
519 extra=str.substr(i+2);
520 inPoint=true;
521 if (inDosFile && remain.empty())
522 {
523 if (dosInChar) value*=8;
524 return true;
525 }
526 if (remain=="PT")
527 return true;
528 if (remain=="IN")
529 {
530 value *= 72;
531 return true;
532 }
533 if (remain=="CM")
534 {
535 value *= 72/2.54;
536 return true;
537 }
538 if (remain=="MM")
539 {
540 value *= 72/25.4;
541 return true;
542 }
543 if (remain=="LI")
544 {
545 inPoint=false;
546 return true;
547 }
548 if (inDosFile)
549 {
550 if (dosInChar) value*=8;
551 extra=str.substr(i);
552 return true;
553 }
554 if (!str.empty())
555 {
556 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::readUnit: can not extract unit in %s\n", str.c_str()));
557 }
558 return false;
559
560 }
561 };
562
563 //! the state of XYWrite
564 struct State
565 {
566 //! constructor
567 explicit State(libwps_tools_win::Font::Type fontType)
568 : m_isDosFile(false)
569 , m_eof(-1)
570 , m_fontType(fontType)
571 , m_metaData()
572 , m_nameToStyleMap()
573 , m_counterToTypeMap()
574 , m_counterToValueMap()
575 {
576 }
577 //! returns the current font type
578 libwps_tools_win::Font::Type getFontType() const
579 {
580 if (m_fontType!=libwps_tools_win::Font::UNKNOWN)
581 return m_fontType;
582 // checkme
583 return m_isDosFile ? libwps_tools_win::Font::CP_437 :
584 libwps_tools_win::Font::WIN3_WEUROPE;
585 }
586 //! flag to know if the file is or not a dos file
587 bool m_isDosFile;
588 //! the last file position
589 long m_eof;
590 //! the user font type
591 libwps_tools_win::Font::Type m_fontType;
592 //! the meta data
593 librevenge::RVNGPropertyList m_metaData;
594 //! map name to style
595 std::map<std::string, Format> m_nameToStyleMap;
596 //! map counter to type
597 std::map<int, libwps::NumberingType> m_counterToTypeMap;
598 //! map counter to value
599 std::map<int, int> m_counterToValueMap;
600 };
601
602 //! Internal: the subdocument of a XYWriteParser
603 class SubDocument final : public WPSTextSubDocument
604 {
605 public:
606 //! constructor for a text entry
607 SubDocument(RVNGInputStreamPtr const &input, XYWriteParser &pars, WPSEntry const &entry, std::string const &style="")
608 : WPSTextSubDocument(input, &pars), m_entry(entry), m_style(style) {}
609 //! destructor
610 ~SubDocument() final {}
611
612 //! operator==
613 bool operator==(std::shared_ptr<WPSSubDocument> const &doc) const final
614 {
615 if (!doc || !WPSTextSubDocument::operator==(doc))
616 return false;
617 auto const *sDoc = dynamic_cast<SubDocument const *>(doc.get());
618 if (!sDoc) return false;
619 return m_entry == sDoc->m_entry && m_style == sDoc->m_style;
620 }
621
622 //! the parser function
623 void parse(std::shared_ptr<WPSContentListener> &listener, libwps::SubDocumentType subDocumentType) final;
624 //! the entry
625 WPSEntry m_entry;
626 //! the style
627 std::string m_style;
628 };
629
630 void SubDocument::parse(std::shared_ptr<WPSContentListener> &listener, libwps::SubDocumentType /*subDocumentType*/)
631 {
632 if (!listener.get())
633 {
634 WPS_DEBUG_MSG(("XYWriteParserInternal::SubDocument::parse: no listener\n"));
635 return;
636 }
637
638 if (!m_parser)
639 {
640 listener->insertCharacter(' ');
641 WPS_DEBUG_MSG(("XYWriteParserInternal::SubDocument::parse: bad parser\n"));
642 return;
643 }
644 if (!m_entry.valid() || !m_input)
645 {
646 listener->insertCharacter(' ');
647 return;
648 }
649
650 auto *mnParser = dynamic_cast<XYWriteParser *>(m_parser);
651 if (!mnParser)
652 {
653 WPS_DEBUG_MSG(("XYWriteParserInternal::SubDocument::parse: bad parser...\n"));
654 listener->insertCharacter(' ');
655 return;
656 }
657 long pos=m_input->tell();
658 mnParser->parseTextZone(m_entry, m_style);
659 m_input->seek(pos, librevenge::RVNG_SEEK_SET);
660 }
661 }
662
663 // constructor, destructor
664 XYWriteParser::XYWriteParser(RVNGInputStreamPtr &input, WPSHeaderPtr &header,
665 libwps_tools_win::Font::Type encoding)
666 : WPSParser(input, header)
667 , m_listener()
668 , m_state()
669 {
670 m_state.reset(new XYWriteParserInternal::State(encoding));
671 }
672
673 XYWriteParser::~XYWriteParser()
674 {
675 }
676
677 bool XYWriteParser::checkFilePosition(long pos) const
678 {
679 if (m_state->m_eof < 0)
680 {
681 RVNGInputStreamPtr input = const_cast<XYWriteParser *>(this)->getInput();
682 long actPos = input->tell();
683 input->seek(0, librevenge::RVNG_SEEK_END);
684 m_state->m_eof=input->tell();
685 input->seek(actPos, librevenge::RVNG_SEEK_SET);
686 }
687 return pos>=0 && pos <= m_state->m_eof;
688 }
689
690 // listener
691 std::shared_ptr<WPSContentListener> XYWriteParser::createListener(librevenge::RVNGTextInterface *interface)
692 {
693 auto input=getInput();
694 if (!input)
695 throw "Can not find input";
696 std::vector<WPSPageSpan> pageList;
697 WPSPageSpan ps;
698 ps.setMarginLeft(0.1);
699 ps.setMarginRight(0.1);
700 ps.setMarginTop(0.1);
701 ps.setMarginBottom(0.1);
702 input->seek(0, librevenge::RVNG_SEEK_SET);
703 while (!input->isEnd() && input->tell()<m_state->m_eof)
704 {
705 uint8_t c=libwps::readU8(input);
706 if (c==0x1a)
707 break;
708 if (c!=0xae)
709 continue;
710 XYWriteParserInternal::Format format;
711 if (!parseFormat(format))
712 break;
713 std::string const str=format.title();
714 std::string const sTitle=format.shortTitle();
715 if (str=="PG")
716 pageList.push_back(ps);
717 else if (sTitle=="RH" || sTitle=="RF")
718 {
719 if (str.size()==2)
720 {
721 WPSEntry fEntry=format.m_entry;
722 long fEnd=fEntry.end();
723 fEntry.setBegin(fEntry.begin()+2);
724 fEntry.setEnd(fEnd);
725 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
726 (getInput(), *this,fEntry));
727 ps.setHeaderFooter(sTitle=="RH" ? WPSPageSpan::HEADER : WPSPageSpan::FOOTER,
728 WPSPageSpan::ALL, subdoc);
729 }
730 else if (str.size()>=3 && (str[2]=='A' || str[2]=='E' || str[2]=='O'))
731 {
732 WPSEntry fEntry=format.m_entry;
733 long fEnd=fEntry.end();
734 fEntry.setBegin(fEntry.begin()+3);
735 fEntry.setEnd(fEnd);
736 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
737 (getInput(), *this,fEntry));
738 ps.setHeaderFooter(sTitle=="RH" ? WPSPageSpan::HEADER : WPSPageSpan::FOOTER,
739 str[2]=='A' ? WPSPageSpan::ALL : str[2]=='E' ? WPSPageSpan::EVEN : WPSPageSpan::ODD, subdoc);
740 }
741 }
742 else if (sTitle=="PW" || sTitle=="FD")
743 {
744 // PB is probably related to the page type A4 paysage==82?
745 double val;
746 bool inPoint;
747 std::string tmp;
748 if (format.readUnit(str, 2, m_state->m_isDosFile, val, inPoint, tmp) && inPoint && val>0 && val<100*72)
749 {
750 if (sTitle=="FD")
751 ps.setFormLength(val/72.);
752 else
753 ps.setFormWidth(val/72.);
754 }
755 else
756 {
757 WPS_DEBUG_MSG(("XYWriteParser::createListener: can not parse %s\n", format.m_string.c_str()));
758 }
759 }
760 else if (sTitle=="OF" || sTitle=="TP" || sTitle=="BT")
761 {
762 for (size_t j=0; j<=format.m_args.size(); ++j)
763 {
764 size_t p=j==0 ? 2 : 0;
765 double value;
766 bool inPoint;
767 std::string tmp;
768 if (format.readUnit(j==0 ? str : format.m_args[j-1], p, m_state->m_isDosFile, value, inPoint, tmp))
769 {
770 if (sTitle=="OF" && inPoint)
771 {
772 if (j==0)
773 ps.setMarginLeft(value/72);
774 else
775 ps.setMarginRight(value/72);
776 }
777 else if (sTitle=="TP" && inPoint)
778 {
779 if (j==1) // i==0 bef header
780 ps.setMarginTop(value/72);
781 }
782 else if (sTitle=="BT" && inPoint)
783 {
784 if (j==2) // i==0 aft footer, i==1 min, 3 max
785 ps.setMarginBottom(value/72);
786 }
787 }
788 else
789 {
790 WPS_DEBUG_MSG(("XYWriteParser::createListener: can not parse %s\n", format.m_string.c_str()));
791 }
792 }
793
794 }
795 }
796 pageList.push_back(ps);
797 auto listener=std::make_shared<WPSContentListener>(pageList, interface);
798 listener->setMetaData(m_state->m_metaData);
799 return listener;
800 }
801
802 ////////////////////////////////////////////////////////////
803 // main funtions to parse a document
804 ////////////////////////////////////////////////////////////
805
806 // main function to parse the document
807 void XYWriteParser::parse(librevenge::RVNGTextInterface *documentInterface)
808 {
809 RVNGInputStreamPtr input=getInput();
810 if (!input)
811 {
812 WPS_DEBUG_MSG(("XYWriteParser::parse: does not find main input\n"));
813 throw (libwps::ParseException());
814 }
815 if (!checkHeader(nullptr, true))
816 throw (libwps::ParseException());
817
818 ascii().setStream(input);
819 ascii().open("MN0");
820 try
821 {
822 if (!m_state->m_isDosFile && !findAllZones())
823 throw (libwps::ParseException());
824 m_listener=createListener(documentInterface);
825 if (!m_listener)
826 {
827 WPS_DEBUG_MSG(("XYWriteParser::parse: can not create the listener\n"));
828 throw (libwps::ParseException());
829 }
830 m_listener->startDocument();
831 WPSEntry entry;
832 entry.setBegin(0);
833 entry.setEnd(m_state->m_eof);
834 parseTextZone(entry);
835 m_listener->endDocument();
836 }
837 catch (...)
838 {
839 WPS_DEBUG_MSG(("XYWriteParser::parse: exception catched when parsing the main document\n"));
840 throw (libwps::ParseException());
841 }
842
843 m_listener.reset();
844
845 ascii().reset();
846 }
847
848 bool XYWriteParser::findAllZones()
849 {
850 RVNGInputStreamPtr input = getInput();
851 if (!input)
852 {
853 WPS_DEBUG_MSG(("XYWriteParser::findAllZones: can not find the input\n"));
854 return false;
855 }
856 input->seek(0, librevenge::RVNG_SEEK_SET);
857 bool ok=false;
858 while (!input->isEnd())
859 {
860 if (libwps::readU8(input)==0x1a)
861 {
862 ok=true;
863 break;
864 }
865 }
866 if (!ok)
867 {
868 WPS_DEBUG_MSG(("XYWriteParser::findAllZones: can not find the end main zone marker\n"));
869 return false;
870 }
871 long endZone1=input->tell();
872 while (!input->isEnd())
873 {
874 if (libwps::readU8(input)==0x1a)
875 {
876 WPSEntry entry;
877 entry.setBegin(endZone1);
878 entry.setEnd(input->tell());
879 parseMetaData(entry);
880 input->seek(entry.end(), librevenge::RVNG_SEEK_SET);
881 break;
882 }
883 }
884 // now normally 22 02 fe fc fe 01 00
885 if (m_state->m_eof!=input->tell()+7)
886 {
887 WPS_DEBUG_MSG(("XYWriteParser::findAllZones: end of file seems bad\n"));
888 }
889 // ok, update the end of the main zone and returns
890 m_state->m_eof=endZone1-1;
891 return true;
892 }
893
894 bool XYWriteParser::update(XYWriteParserInternal::Format const &format, libwps_tools_win::Font::Type &fontType) const
895 {
896 if (!m_listener)
897 throw "no listener";
898 std::string const str=format.title();
899 std::string const sTitle=format.shortTitle();
900 if (sTitle=="MD" || sTitle=="RG" || sTitle=="SZ" ||
901 sTitle=="FG")
902 {
903 auto font=m_listener->getFont();
904 if (!format.updateFont(font))
905 return false;
906 m_listener->setFont(font);
907 }
908 else if (sTitle=="UF" && str.size()>2)
909 {
910 auto font=m_listener->getFont();
911 font.m_name=libwps_tools_win::Font::unicodeString(format.m_string.substr(2), m_state->getFontType());
912 auto newType=libwps_tools_win::Font::getFontType(font.m_name);
913 if (newType!=libwps_tools_win::Font::UNKNOWN)
914 fontType=newType;
915 m_listener->setFont(font);
916 }
917 else if (str=="FC" || str=="FL" || str=="FR" ||
918 str=="JU" || str=="NJ" ||
919 sTitle=="IP" || sTitle=="RM" ||
920 sTitle=="AL" || sTitle=="LS" || sTitle=="BB" || sTitle=="NB" ||
921 sTitle=="EL" || sTitle=="LL" || sTitle=="TS" ||
922 sTitle=="BG")
923 {
924 auto paragraph=m_listener->getParagraph();
925 if (!format.updateParagraph(paragraph))
926 return false;
927 m_listener->setParagraph(paragraph);
928 }
929 else if (sTitle=="LM")
930 {
931 size_t p=2;
932 double value;
933 std::string tmp;
934 bool inPoint=false;
935 if (!format.readUnit(str, p, m_state->m_isDosFile, value, inPoint, tmp))
936 return false;
937 auto paragraph=m_listener->getParagraph();
938 if (inPoint)
939 paragraph.m_margins[1]=value/72;
940 if (format.m_listCounter==-1 && !tmp.empty()&&format.m_entry.valid())
941 {
942 format.m_listCounter=-2;
943 // look for a counter
944 auto THIS=const_cast<XYWriteParser *>(this);
945 auto input=THIS->getInput();
946 if (!input)
947 throw "XYWriteParser::update: no input";
948 long actPos=input->tell();
949 bool ok=false;
950 input->seek(format.m_entry.begin(), librevenge::RVNG_SEEK_SET);
951 while (!input->isEnd() && input->tell()<format.m_entry.end())
952 {
953 if (libwps::readU8(input)==';')
954 {
955 ok=true;
956 break;
957 }
958 }
959 if (ok)
960 {
961 ok=false;
962 auto defType=m_state->getFontType();
963 while (!input->isEnd() && input->tell()<format.m_entry.end())
964 {
965 auto ch=libwps::readU8(input);
966 if (ch!=0xae)
967 {
968 if (ch=='\t') ch=' '; // replace tabulations by space
969 libwps::appendUnicode(uint32_t(libwps_tools_win::Font::unicode(ch, defType)),
970 format.m_listCounter >= 0 ? format.m_level.m_suffix :
971 format.m_level.m_prefix);
972 continue;
973 }
974 XYWriteParserInternal::Format newFormat;
975 if (!THIS->parseFormat(newFormat))
976 break;
977 p=1;
978 unsigned int val;
979 std::string const newFStr=newFormat.title();
980 std::string extra;
981 if (!newFStr.empty() && newFStr[0]=='C' &&
982 newFormat.readUInt(newFStr, p, val, extra))
983 {
984 if (format.m_listCounter>=0)
985 {
986 format.m_level.m_prefix.clear();
987 format.m_level.m_suffix.clear();
988 }
989 format.m_listCounter=int(val);
990 auto it=m_state->m_counterToTypeMap.find(format.m_listCounter);
991 if (it!=m_state->m_counterToTypeMap.end())
992 {
993 format.m_level.m_type=it->second;
994 }
995 else
996 {
997 WPS_DEBUG_MSG(("XYWriteParser::update: can not find counter %d\n", format.m_listCounter));
998 }
999 ok=true;
1000 }
1001 else
1002 {
1003 #ifdef DEBUG
1004 std::cerr << "XYWriteParser::update[LM]: unused\n";
1005 std::cerr << "\t" << newFormat << "\n";
1006 #endif
1007 }
1008 }
1009 }
1010 if (!ok)
1011 {
1012 #ifdef DEBUG
1013 std::cerr << "XYWriteParser::update[LM]: unused\n";
1014 std::cerr << "\t" << format << "\n";
1015 #endif
1016 }
1017 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1018 }
1019 if (!format.m_level.isDefault())
1020 {
1021 format.m_level.m_labelIndent=paragraph.m_margins[1];
1022 paragraph.m_listLevel=format.m_level;
1023 paragraph.m_listLevelIndex=1;
1024 paragraph.m_margins[1]=0;
1025 }
1026 m_listener->setParagraph(paragraph);
1027 }
1028 else
1029 return false;
1030 return true;
1031 }
1032
1033 bool XYWriteParser::parseTextZone(WPSEntry const &entry, std::string const &styleName)
1034 {
1035 RVNGInputStreamPtr input = getInput();
1036 if (!input || !m_listener)
1037 throw (libwps::ParseException());
1038 if (!entry.valid())
1039 return true;
1040 input->seek(entry.begin(), librevenge::RVNG_SEEK_SET);
1041 auto fontType=m_state->getFontType();
1042 WPSFont defFont;
1043 defFont.m_name="Courier New";
1044 defFont.m_size=10;
1045 m_listener->setFont(defFont);
1046 if (!styleName.empty())
1047 {
1048 auto it=m_state->m_nameToStyleMap.find(styleName);
1049 if (it!=m_state->m_nameToStyleMap.end())
1050 {
1051 for (auto const &child : it->second.m_children)
1052 {
1053 std::string const sTitle=child.shortTitle();
1054 if (!update(child, fontType) && sTitle!="FT" && sTitle!="BF") // checkme: FT and BF related to footnote
1055 {
1056 #ifdef DEBUG
1057 std::cerr << "XYWriteParser::parseTextZone[child]: unused\n";
1058 std::cerr << "\t" << child << "\n";
1059 #endif
1060 }
1061 }
1062 }
1063 }
1064 while (!input->isEnd() && input->tell()<entry.end())
1065 {
1066 uint8_t c=libwps::readU8(input);
1067 if (c==0x1a)
1068 {
1069 if (input->tell()<entry.end())
1070 {
1071 WPS_DEBUG_MSG(("XYWriteParser::parseTextZone: find unexpected end zone\n"));
1072 }
1073 break;
1074 }
1075 if (c==0xae)
1076 {
1077 XYWriteParserInternal::Format format;
1078 if (!parseFormat(format))
1079 throw (libwps::ParseException());
1080 std::string const str=format.title();
1081 std::string const sTitle=format.shortTitle();
1082 bool done=true;
1083 if (update(format, fontType))
1084 ;
1085 else if (sTitle=="DC" && str.size()>2) // DCxxx=[1iIaA]...
1086 {
1087 size_t p=2;
1088 unsigned int val;
1089 std::string extra;
1090 if (!format.readUInt(format.m_string, p, val, extra) || !format.m_entry.valid() ||
1091 extra.size()<=1 || extra[0]!='=' ||
1092 m_state->m_counterToTypeMap.find(int(val)) != m_state->m_counterToTypeMap.end())
1093 done=false;
1094 else
1095 {
1096 std::map<char, libwps::NumberingType> const cToTypeMap=
1097 {
1098 {'1', libwps::ARABIC}, {'a', libwps::LOWERCASE}, {'A', libwps::UPPERCASE}, {'i', libwps::LOWERCASE_ROMAN}, {'I', libwps::UPPERCASE_ROMAN}
1099 };
1100 auto it=cToTypeMap.find(extra[1]);
1101 if (it==cToTypeMap.end())
1102 {
1103 WPS_DEBUG_MSG(("XYWriteParserInternal::Format::parseTextZone: can not decode counter format in %s\n", extra.c_str()));
1104 }
1105 else
1106 m_state->m_counterToTypeMap[int(val)]=it->second;
1107 }
1108 }
1109 else if (sTitle=="SS")
1110 {
1111 if (createFormatChildren(format,format.m_string.size()+1) && format.m_string.size()>2)
1112 m_state->m_nameToStyleMap[format.m_string.substr(2)]=format;
1113 else
1114 done=false;
1115 }
1116 else if (sTitle=="FM" && format.m_string.size()>2 &&
1117 (format.m_string[2]>='1' && format.m_string[2]<='3'))
1118 {
1119 if (createFormatChildren(format,3))
1120 {
1121 std::string name("__");
1122 name+=format.m_string.substr(0,3);
1123 m_state->m_nameToStyleMap[name]=format;
1124 }
1125 else
1126 done=false;
1127 }
1128 else if (sTitle=="US" && format.m_string.size()>2)
1129 {
1130 auto it=m_state->m_nameToStyleMap.find(format.m_string.substr(2));
1131 if (it==m_state->m_nameToStyleMap.end())
1132 {
1133 WPS_DEBUG_MSG(("XYWriteParser::parseTextZone: can not find style %s\n", format.m_string.c_str()));
1134 }
1135 else
1136 {
1137 if (format.m_string.size()>4)
1138 {
1139 // unsure, when we need to reset the style
1140 m_listener->setFont(defFont);
1141 m_listener->setParagraph(WPSParagraph());
1142 }
1143 for (auto const &child : it->second.m_children)
1144 {
1145 if (!update(child, fontType))
1146 {
1147 #ifdef DEBUG
1148 std::cerr << "XYWriteParser::parseTextZone[child]: unused\n";
1149 std::cerr << "\t" << child << "\n";
1150 #endif
1151 }
1152 }
1153 }
1154 }
1155 else if (sTitle=="FA")
1156 {
1157 if (createFormatChildren(format))
1158 parseFrameZone(format);
1159 else
1160 done=false;
1161 }
1162 else if (sTitle=="IG")
1163 {
1164 if (createFormatChildren(format,format.m_string.size()+1))
1165 parsePictureZone(format);
1166 else
1167 done=false;
1168 }
1169 else if (sTitle=="NT" && format.m_string.size()>2 && format.m_entry.valid())
1170 {
1171 WPSEntry fEntry=format.m_entry;
1172 long fEnd=fEntry.end();
1173 fEntry.setBegin(fEntry.begin()+2);
1174 fEntry.setEnd(fEnd);
1175 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
1176 (getInput(), *this,fEntry));
1177 m_listener->insertComment(subdoc);
1178 }
1179 else if (sTitle=="FN")
1180 {
1181 bool hasId=format.m_string.size()>2 &&
1182 (format.m_string[2]>='1' && format.m_string[2]<='3');
1183 WPSEntry fEntry=format.m_entry;
1184 long fEnd=fEntry.end();
1185 fEntry.setBegin(fEntry.begin()+(hasId ? 3 : 2));
1186 fEntry.setEnd(fEnd);
1187 std::string sName("__FM");
1188 sName+=format.m_string[2];
1189 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
1190 (getInput(), *this, fEntry, hasId ? sName : ""));
1191 m_listener->insertNote(WPSContentListener::FOOTNOTE, subdoc);
1192 }
1193 else if (str=="PG")
1194 m_listener->insertBreak(WPS_PAGE_BREAK);
1195 else if (str=="PN")
1196 m_listener->insertField(WPSField(WPSField::PageNumber));
1197 else if (str=="DA" || str=="TM") // TM date custom format ?
1198 m_listener->insertField(WPSField(WPSField::Date));
1199 else if (str=="TI")
1200 m_listener->insertField(WPSField(WPSField::Time));
1201 else if (sTitle=="CT")
1202 {
1203 long actPos=input->tell();
1204 if (!createTable(format, entry.end()))
1205 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1206 }
1207 else if ((sTitle=="RH" || sTitle=="RF") && // header/footer already parsed
1208 (str.size()==2 ||
1209 (str.size()>=3 && (str[2]=='A'||str[2]=='E'||str[2]=='O'))))
1210 ;
1211 else if (sTitle=="PW" || sTitle=="FD" || sTitle=="PB" || sTitle=="OF" || sTitle=="TP" || sTitle=="BT" || // page dimension
1212 format.shortTitle(3)=="UBN" || sTitle=="GU" || sTitle=="EE" || sTitle=="ET" || // related to table (checkme)
1213 sTitle=="SY" || // other method to define a font
1214 sTitle=="NF") // footnote number
1215 ;
1216 else if (sTitle=="LB" || sTitle=="RE")
1217 {
1218 // LBname: label
1219 // RE[PCF]name: ref to page, chapter, reference
1220 static bool first=true;
1221 if (first)
1222 {
1223 WPS_DEBUG_MSG(("XYWriteParser::parseTextZone: retrieving label/cross ref is not implemented\n"));
1224 }
1225 }
1226 else if (format.shortTitle(1)=="C")
1227 {
1228 unsigned int value;
1229 size_t p=1;
1230 std::string tmp;
1231 if (!format.readUInt(str, p, value, tmp))
1232 done=false;
1233 else
1234 {
1235 int actValue=0;
1236 auto it=m_state->m_counterToValueMap.find(int(value));
1237 if (it!=m_state->m_counterToValueMap.end())
1238 actValue=it->second;
1239 ++actValue;
1240 std::stringstream s;
1241 s << actValue;
1242 for (auto res : s.str())
1243 m_listener->insertCharacter(uint8_t(res));
1244 m_state->m_counterToValueMap[int(value)]=actValue;
1245 }
1246 }
1247 else
1248 done=false;
1249 if (!done)
1250 {
1251 #ifdef DEBUG
1252 std::cerr << "XYWriteParser::parseTextZone: unused\n";
1253 std::cerr << "\t" << format << "\n";
1254 #endif
1255 }
1256 continue;
1257 }
1258 if (c==0xff && input->tell()+2<entry.end())
1259 {
1260 // special case a char in binary...
1261 long pos=input->tell();
1262 c=0;
1263 bool ok=true;
1264 for (int i=0; i<2; ++i)
1265 {
1266 auto ch=libwps::readU8(input);
1267 if (ch>='A' && ch<='F')
1268 c=(unsigned char)(c*16+(ch-'A'+10));
1269 else if (ch>='0' && ch<='9')
1270 c=(unsigned char)(c*16+(ch-'0'));
1271 else
1272 {
1273 ok=false;
1274 break;
1275 }
1276 }
1277 if (!ok)
1278 {
1279 input->seek(pos, librevenge::RVNG_SEEK_SET);
1280 WPS_DEBUG_MSG(("XYWriteParser::parseTextZone: find bad char FF in pos=%lx\n", (unsigned long)(input->tell())));
1281 continue;
1282 }
1283 }
1284 switch (c)
1285 {
1286 case 0x9:
1287 m_listener->insertTab();
1288 break;
1289 case 0xa:
1290 break;
1291 case 0xd:
1292 {
1293 // we must reset the list level to 0
1294 if (m_listener->getCurrentList())
1295 {
1296 auto paragraph=m_listener->getParagraph();
1297 if (paragraph.m_listLevelIndex>0)
1298 {
1299 paragraph.m_margins[1]=paragraph.m_listLevel.m_labelIndent;
1300 paragraph.m_listLevelIndex=0;
1301 m_listener->setParagraph(paragraph);
1302 }
1303 }
1304 m_listener->insertEOL();
1305 break;
1306 }
1307 default:
1308 if (c<0x1f || ((c==0xaf || c==0xfa) && input->tell() != entry.begin()+1 && input->tell() != entry.end()))
1309 {
1310 WPS_DEBUG_MSG(("XYWriteParser::parseTextZone: find bad char %x in pos=%lx\n", unsigned(c), (unsigned long)(input->tell())));
1311 }
1312 else
1313 m_listener->insertUnicode(uint32_t(libwps_tools_win::Font::unicode(c, fontType)));
1314 }
1315 }
1316 return true;
1317 }
1318
1319 bool XYWriteParser::parseFrameZone(XYWriteParserInternal::Format const &frameFormat)
1320 {
1321 RVNGInputStreamPtr input = getInput();
1322 if (!input || !m_listener ||!frameFormat.m_entry.valid())
1323 throw (libwps::ParseException());
1324 Vec2f dim;
1325 WPSEntry textEntry;
1326 for (auto const &child : frameFormat.m_children)
1327 {
1328 std::string const sTitle=child.shortTitle();
1329 bool done=false;
1330 if (sTitle=="SI")
1331 {
1332 std::string tmp;
1333 done=child.readVec2f(child.m_string, 2, m_state->m_isDosFile, dim, tmp);
1334 }
1335 else if (sTitle=="LB") // label are not implement
1336 done=true;
1337 else if (sTitle=="PO") // find POTMxPC;data
1338 {
1339 textEntry=child.m_entry;
1340 done=true;
1341 }
1342 if (!done)
1343 {
1344 #ifdef DEBUG
1345 std::cerr << "XYWriteParser::parseFrameZone: unused\n";
1346 std::cerr << "\t" << child << "\n";
1347 #endif
1348 }
1349 }
1350 if (dim[0]<=0 || dim[1]<=0 || !textEntry.valid())
1351 {
1352 WPS_DEBUG_MSG(("XYWriteParser::parseFrameZone: can not find frame data\n"));
1353 return false;
1354 }
1355 long begPos=input->tell();
1356
1357 long endPos=textEntry.end();
1358 input->seek(textEntry.begin(), librevenge::RVNG_SEEK_SET);
1359 while (!input->isEnd() && input->tell()<endPos)
1360 {
1361 if (libwps::readU8(input)==';')
1362 break;
1363 }
1364 textEntry.setBegin(input->tell());
1365 textEntry.setEnd(endPos);
1366 WPSPosition fPos(Vec2f(), dim, librevenge::RVNG_POINT);
1367 fPos.setRelativePosition(WPSPosition::Char);
1368 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
1369 (getInput(), *this, textEntry));
1370 m_listener->insertTextBox(fPos, subdoc);
1371 input->seek(begPos, librevenge::RVNG_SEEK_SET);
1372 return true;
1373 }
1374
1375 bool XYWriteParser::parsePictureZone(XYWriteParserInternal::Format const &pictureFormat)
1376 {
1377 RVNGInputStreamPtr input = getInput();
1378 if (!input || !m_listener || !pictureFormat.m_entry.valid())
1379 throw (libwps::ParseException());
1380 WPSBox2f box;
1381 Vec2i scaleArray(100,100);
1382 for (auto const &child : pictureFormat.m_children)
1383 {
1384 std::string const sTitle=child.shortTitle();
1385 bool done=false;
1386 if (sTitle=="CR")
1387 {
1388 std::string tmp;
1389 done=child.readBox2f(child.m_string, 2, m_state->m_isDosFile, box, tmp);
1390 }
1391 else if (sTitle=="TY" || child.m_string=="IML" || sTitle=="RV") // type, unknown, revision?
1392 done=true;
1393 else if (sTitle=="SC")
1394 {
1395 std::string tmp;
1396 done=child.readVec2i(child.m_string, 2, scaleArray, tmp);
1397 }
1398 if (!done)
1399 {
1400 #ifdef DEBUG
1401 std::cerr << "XYWriteParser::parsePictureZone: unused\n";
1402 std::cerr << "\t" << child << "\n";
1403 #endif
1404 }
1405 }
1406 Vec2f dim(static_cast<float>(scaleArray[0])/100.f*box.size()[0], float(scaleArray[1])/100.f*box.size()[1]);
1407 if (dim[0]<=0 || dim[1]<=0)
1408 {
1409 WPS_DEBUG_MSG(("XYWriteParser::parsePictureZone: can not find picture dimension\n"));
1410 return false;
1411 }
1412
1413 long begPos=input->tell();
1414 long endPos=pictureFormat.m_entry.end();
1415 input->seek(pictureFormat.m_entry.begin()+2, librevenge::RVNG_SEEK_SET);
1416 while (!input->isEnd() && input->tell()<endPos)
1417 {
1418 if (libwps::readU8(input)==',')
1419 break;
1420 }
1421 WPSEntry textEntry;
1422 textEntry.setBegin(pictureFormat.m_entry.begin()+2);
1423 textEntry.setEnd(input->tell()-1);
1424 WPSPosition fPos(Vec2f(), dim, librevenge::RVNG_POINT);
1425 fPos.setRelativePosition(WPSPosition::Char);
1426 WPSSubDocumentPtr subdoc(new XYWriteParserInternal::SubDocument
1427 (getInput(), *this, textEntry));
1428 m_listener->insertTextBox(fPos, subdoc);
1429 input->seek(begPos, librevenge::RVNG_SEEK_SET);
1430 return true;
1431 }
1432
1433 bool XYWriteParser::createTable(XYWriteParserInternal::Format const &tableFormat, long endPos)
1434 {
1435 RVNGInputStreamPtr input = getInput();
1436 if (!input || !m_listener || tableFormat.shortTitle()!="CT")
1437 throw (libwps::ParseException());
1438 long begPos=input->tell();
1439 if (begPos>=endPos)
1440 {
1441 WPS_DEBUG_MSG(("XYWriteParser::createTable: the zone seems too short\n"));
1442 return false;
1443 }
1444 std::vector<float> colWidth;
1445 std::vector<std::string> colStyle;
1446 for (size_t j=0; j<=tableFormat.m_args.size(); ++j)
1447 {
1448 size_t p=j==0 ? 2 : 0;
1449 double value;
1450 bool inPoint;
1451 std::string tmp;
1452 if (tableFormat.readUnit(j==0 ? tableFormat.m_string : tableFormat.m_args[j-1], p, m_state->m_isDosFile, value, inPoint, tmp) && inPoint)
1453 {
1454 if (j==0) // left pos
1455 ;
1456 else
1457 {
1458 colWidth.push_back(float(value));
1459 if (tmp.size()>1)
1460 colStyle.push_back(tmp.substr(1));
1461 else
1462 colStyle.push_back("");
1463 }
1464 }
1465 else
1466 {
1467 WPS_DEBUG_MSG(("XYWriteParser::createTable: can not read some colum size %s\n", j==0 ? tableFormat.m_string.c_str() : tableFormat.m_args[j-1].c_str()));
1468 if (j)
1469 {
1470 colWidth.push_back(0);
1471 colStyle.push_back("");
1472 }
1473 }
1474 }
1475 if (colWidth.empty())
1476 {
1477 WPS_DEBUG_MSG(("XYWriteParser::createTable: can not find any columns\n"));
1478 return false;
1479 }
1480 int numColumns=int(colWidth.size());
1481
1482 std::vector<XYWriteParserInternal::Cell> cells;
1483 int cRow=0, cCol=0;
1484 cells.push_back(XYWriteParserInternal::Cell(*this));
1485 cells.back().m_entry.setBegin(input->tell());
1486 cells.back().setPosition(Vec2i(cCol,cRow));
1487
1488 bool ok=false;
1489 while (!input->isEnd())
1490 {
1491 long pos=input->tell();
1492 if (pos>=endPos)
1493 break;
1494 uint8_t c=libwps::readU8(input);
1495 if (c==0x1a)
1496 {
1497 if (input->tell()<endPos)
1498 {
1499 WPS_DEBUG_MSG(("XYWriteParser::createTable: find unexpected end zone\n"));
1500 }
1501 break;
1502 }
1503 if (c!=0xae)
1504 continue;
1505 XYWriteParserInternal::Format format;
1506 if (!parseFormat(format))
1507 throw (libwps::ParseException());
1508 std::string const str=format.title();
1509 std::string const sTitle=format.shortTitle();
1510 if (str=="EC")
1511 {
1512 ok=true;
1513 break;
1514 }
1515 if (sTitle=="CT")
1516 break;
1517 else if (sTitle=="CO")
1518 {
1519 unsigned int value;
1520 size_t p=2;
1521 std::string tmp;
1522 if (!format.readUInt(format.m_string, p, value, tmp))
1523 continue;
1524 if (numColumns==0 || cells.empty() || value==0) // the table is not created
1525 break;
1526 cells.back().m_entry.setEnd(pos);
1527 int newCol=int(value)-1;
1528 if (newCol>numColumns)
1529 break;
1530 if (newCol<=cCol)
1531 ++cRow;
1532 cCol=newCol;
1533 cells.push_back(XYWriteParserInternal::Cell(*this));
1534 cells.back().m_entry.setBegin(input->tell());
1535 cells.back().setPosition(Vec2i(cCol,cRow));
1536 if (cCol<int(colStyle.size()))
1537 cells.back().m_style=colStyle[size_t(cCol)];
1538 }
1539 }
1540 if (ok)
1541 {
1542 m_listener->openTable(colWidth, librevenge::RVNG_POINT);
1543 cRow=-1;
1544 WPSListenerPtr listener(m_listener);
1545 for (auto &cell : cells)
1546 {
1547 auto const cPos=cell.position();
1548 while (cRow<cPos[1])
1549 {
1550 if (cRow!=-1)
1551 m_listener->closeTableRow();
1552 m_listener->openTableRow(-10, librevenge::RVNG_POINT);
1553 ++cRow;
1554 cCol=0;
1555 }
1556 if (cCol<cPos[0])
1557 m_listener->addEmptyTableCell(Vec2i(cCol,cRow),Vec2i(cPos[0]-cCol,1));
1558 m_listener->openTableCell(cell);
1559 cell.sendContent(listener);
1560 m_listener->closeTableCell();
1561 cCol=cPos[0]+1;
1562 }
1563 if (cRow!=-1)
1564 m_listener->closeTableRow();
1565 m_listener->closeTable();
1566 }
1567 else
1568 input->seek(begPos, librevenge::RVNG_SEEK_SET);
1569 return ok;
1570 }
1571
1572 bool XYWriteParser::parseMetaData(WPSEntry const &entry)
1573 {
1574 RVNGInputStreamPtr input = getInput();
1575 if (!input)
1576 throw (libwps::ParseException());
1577 if (!entry.valid())
1578 return true;
1579 input->seek(entry.begin(), librevenge::RVNG_SEEK_SET);
1580 XYWriteParserInternal::Format format;
1581 std::string actualString;
1582 auto fontType=m_state->getFontType();
1583 while (!input->isEnd() && input->tell()+1<entry.end())
1584 {
1585 uint8_t c=libwps::readU8(input);
1586 if (c==0x1a)
1587 {
1588 WPS_DEBUG_MSG(("XYWriteParser::parseMetaData: find end of zone\n"));
1589 return false;
1590 }
1591 if (c!=0xae)
1592 {
1593 actualString+=char(c);
1594 continue;
1595 }
1596 const auto strEnd = actualString.find_last_not_of(" ");
1597 actualString=actualString.substr(0, strEnd+1);
1598 if (!actualString.empty())
1599 {
1600 // also LBLG:40 another author
1601 // find also LBCD:20, LBCT:15, LBMD:20, LBMT:15 with some checksum?
1602 // and LBRP:4, LBPJ:20, LBCM:44, LBKY:~250 empty
1603 auto const finalStr=libwps_tools_win::Font::unicodeString(actualString, fontType);
1604 std::string const str=format.title();
1605 if (str=="LBAU") // sz:40
1606 m_state->m_metaData.insert("dc:creator", finalStr);
1607 else if (str=="LBRV") // revision sz:4
1608 m_state->m_metaData.insert("librevenge:version-number", finalStr);
1609 }
1610 actualString.clear();
1611 if (!parseFormat(format))
1612 return false;
1613 }
1614 return true;
1615 }
1616
1617 ////////////////////////////////////////////////////////////
1618 // low level
1619 ////////////////////////////////////////////////////////////
1620
1621 bool XYWriteParser::parseFormat(XYWriteParserInternal::Format &format)
1622 {
1623 RVNGInputStreamPtr input = getInput();
1624 if (!input)
1625 throw (libwps::ParseException());
1626 format=XYWriteParserInternal::Format(m_state->m_isDosFile);
1627 format.m_entry.setBegin(input->tell());
1628 while (!input->isEnd())
1629 {
1630 if (input->tell()>=m_state->m_eof)
1631 {
1632 WPS_DEBUG_MSG(("XYWriteParser::parseFormat: can not find end of format\n"));
1633 return false;
1634 }
1635 uint8_t c=libwps::readU8(input);
1636 if (c==0xaf)
1637 {
1638 format.m_entry.setEnd(input->tell()-1);
1639 return true;
1640 }
1641 if (c==0xfa || c==0xae)
1642 {
1643 format.m_isComplex=true;
1644 // normally ae XXX fa ... af
1645 // but sometimes I found ae XXX ae ... af fa ... af
1646 if (format.m_entry.valid())
1647 {
1648 WPS_DEBUG_MSG(("XYWriteParser::parseFormat: oops an entry is already defined\n"));
1649 }
1650 int depth=c==0xae ? 1 : 0;
1651 while (!input->isEnd())
1652 {
1653 if (input->tell()>=m_state->m_eof)
1654 {
1655 WPS_DEBUG_MSG(("XYWriteParser::parseFormat: can not find end of entry\n"));
1656 return false;
1657 }
1658 c=libwps::readU8(input);
1659 if (c==0xae)
1660 ++depth;
1661 else if (c==0xaf)
1662 {
1663 if (depth==0)
1664 {
1665 format.m_entry.setEnd(input->tell()-1);
1666 return true;
1667 }
1668 --depth;
1669 }
1670 }
1671 }
1672 if (c==0x1a)
1673 {
1674 WPS_DEBUG_MSG(("XYWriteParser::parseFormat: find end of zone\n"));
1675 return false;
1676 }
1677 if (c==',')
1678 format.m_args.push_back(std::string());
1679 else if (format.m_args.empty())
1680 format.m_string+=char(c);
1681 else
1682 format.m_args.back()+=char(c);
1683 }
1684 WPS_DEBUG_MSG(("XYWriteParser::parseFormat: find end of file\n"));
1685 return false;
1686 }
1687
1688 bool XYWriteParser::createFormatChildren(XYWriteParserInternal::Format &format, size_t fPos)
1689 {
1690 RVNGInputStreamPtr input = getInput();
1691 if (!input || !format.m_entry.valid())
1692 throw (libwps::ParseException());
1693 long endPos=format.m_entry.end();
1694 if (endPos>m_state->m_eof)
1695 {
1696 WPS_DEBUG_MSG(("XYWriteParser::createFormatChildren: end entry seems bad\n"));
1697 return false;
1698 }
1699 long prevPos=input->tell();
1700 input->seek(format.m_entry.begin(), librevenge::RVNG_SEEK_SET);
1701 // skip header
1702 for (size_t p=0; p<fPos; ++p)
1703 {
1704 if (input->isEnd() || input->tell()>=endPos)
1705 break;
1706 if (libwps::readU8(input)==',')
1707 break;
1708 }
1709 if (input->tell()>=endPos)
1710 {
1711 input->seek(prevPos, librevenge::RVNG_SEEK_SET);
1712 return true;
1713 }
1714 std::string actString;
1715 long begPos=input->tell();
1716 bool isComplex=false;
1717 while (!input->isEnd() && input->tell()<=endPos)
1718 {
1719 uint8_t c=input->tell()==endPos ? ',' : libwps::readU8(input);
1720 auto *child=format.m_children.empty() ? nullptr : &format.m_children.back();
1721 if (c==0xfa || c==0xae)
1722 {
1723 isComplex=true;
1724 // normally ae XXX fa ... af
1725 // but sometimes I found ae XXX ae ... af fa ... af
1726 int depth=c==0xae ? 1 : 0;
1727 while (!input->isEnd() && input->tell()<endPos)
1728 {
1729 c=libwps::readU8(input);
1730 if (c==0xae)
1731 ++depth;
1732 else if (c==',' && depth==0)
1733 break;
1734 else if (c==0xaf)
1735 {
1736 if (depth==0)
1737 break;
1738 --depth;
1739 }
1740 }
1741 if (c!=',')
1742 continue;
1743 }
1744 if (c==0x1a)
1745 {
1746 WPS_DEBUG_MSG(("XYWriteParser::createFormatChildren: find end of zone\n"));
1747 input->seek(prevPos, librevenge::RVNG_SEEK_SET);
1748 return false;
1749 }
1750 if (c==',')
1751 {
1752 if (!actString.empty())
1753 {
1754 if (actString[0]=='.' || (actString[0]>='0' && actString[0]<='9'))
1755 {
1756 if (child)
1757 {
1758 child->m_isComplex=isComplex;
1759 child->m_args.push_back(actString);
1760 }
1761 }
1762 else
1763 {
1764 if (child)
1765 child->m_entry.setEnd(begPos-1);
1766 format.m_children.push_back(XYWriteParserInternal::Format());
1767 format.m_children.back().m_entry.setBegin(begPos);
1768 format.m_children.back().m_inDosFile = m_state->m_isDosFile;
1769 format.m_children.back().m_string=actString;
1770 format.m_children.back().m_isComplex=isComplex;
1771 isComplex=false;
1772 }
1773 }
1774 actString.clear();
1775 begPos=input->tell();
1776 if (!format.m_children.empty())
1777 format.m_children.back().m_entry.setEnd(begPos==endPos ? endPos : begPos-1);
1778 if (begPos==endPos)
1779 break;
1780 continue;
1781 }
1782 if (c!='=')
1783 actString+=char(c);
1784 }
1785 input->seek(prevPos, librevenge::RVNG_SEEK_SET);
1786 return true;
1787 }
1788
1789 // basic function to check if the header is ok
1790 bool XYWriteParser::checkHeader(WPSHeader *header, bool /*strict*/)
1791 {
1792 RVNGInputStreamPtr input = getInput();
1793 if (!input || !checkFilePosition(10)) // too small for containing any usefull format
1794 {
1795 WPS_DEBUG_MSG(("XYWriteParser::checkHeader: file is too short\n"));
1796 return false;
1797 }
1798
1799 /* check sequence 0xae ...[,*] 0xaf */
1800 input->seek(0x0, librevenge::RVNG_SEEK_SET);
1801 bool ok=false, inFormat=false;
1802 int depth=0;
1803 int numBadChar=0, numCurrentChar=0;
1804 while (!input->isEnd())
1805 {
1806 if (numBadChar>10)
1807 break;
1808 uint8_t c=libwps::readU8(input);
1809 if (c<=0x1f && c!=0x9 && c!=0xa && c!=0xd && c!=0x1b)
1810 ++numBadChar;
1811 else if (!depth)
1812 {
1813 if (c==0xae)
1814 {
1815 inFormat=true;
1816 depth=1;
1817 }
1818 else if (c==0xaf) // end before begin
1819 break;
1820 }
1821 else
1822 {
1823 if (c==0xaf)
1824 {
1825 if (--depth==0) // find the end of a sequence, ok
1826 {
1827 ok=true;
1828 break;
1829 }
1830 inFormat=false;
1831 }
1832 else if (c==0xae)
1833 {
1834 ++depth;
1835 inFormat=true;
1836 }
1837 else if (c==',')
1838 numCurrentChar=0;
1839 else if (c==0xfa)
1840 inFormat=false;
1841 else if (inFormat)
1842 {
1843 if (++numCurrentChar>256)
1844 break;
1845 }
1846 }
1847 }
1848 if (!ok)
1849 {
1850 WPS_DEBUG_MSG(("XYWriteParser::checkHeader: can not find any sequence\n"));
1851 return false;
1852 }
1853 input->seek(-1, librevenge::RVNG_SEEK_END);
1854 int val=libwps::readU8(input);
1855 if (val==0x1a)
1856 m_state->m_isDosFile=true;
1857 else if (val)
1858 {
1859 WPS_DEBUG_MSG(("XYWriteParser::checkHeader: oops unexpected last character\n"));
1860 return false;
1861 }
1862 if (header)
1863 header->setMajorVersion(m_state->m_isDosFile ? 0 : 1);
1864 return true;
1865 }
1866
1867 // read the document structure ...
1868
1869 /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */