Debian Codegraph @

src/lib/Quattro9.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 <algorithm>
26 #include <cmath>
27 #include <sstream>
28 #include <stack>
29 #include <utility>
30
31 #include <librevenge-stream/librevenge-stream.h>
32
33 #include "libwps_internal.h"
34 #include "libwps_tools_win.h"
35
36 #include "WKSContentListener.h"
37 #include "WKSSubDocument.h"
38
39 #include "WPSCell.h"
40 #include "WPSEntry.h"
41 #include "WPSFont.h"
42 #include "WPSHeader.h"
43 #include "WPSOLEParser.h"
44 #include "WPSOLEStream.h"
45 #include "WPSPageSpan.h"
46 #include "WPSStream.h"
47 #include "WPSStringStream.h"
48
49 #include "Quattro9Graph.h"
50 #include "Quattro9Spreadsheet.h"
51
52 #include "Quattro9.h"
53
54 using namespace libwps;
55
56 //! Internal: namespace to define internal class of Quattro9Parser
57 namespace Quattro9ParserInternal
58 {
59 //! Internal: the subdocument of a WPS4Parser
60 class SubDocument final : public WKSSubDocument
61 {
62 public:
63 //! constructor for a text entry
64 SubDocument(RVNGInputStreamPtr const &input, Quattro9Parser &pars, bool header) :
65 WKSSubDocument(input, &pars), m_header(header) {}
66 //! destructor
67 ~SubDocument() final {}
68
69 //! operator==
70 bool operator==(std::shared_ptr<WPSSubDocument> const &doc) const final
71 {
72 if (!doc || !WKSSubDocument::operator==(doc))
73 return false;
74 auto const *sDoc = dynamic_cast<SubDocument const *>(doc.get());
75 if (!sDoc) return false;
76 return m_header == sDoc->m_header;
77 }
78
79 //! the parser function
80 void parse(std::shared_ptr<WKSContentListener> &listener, libwps::SubDocumentType subDocumentType) final;
81 //! a flag to known if we need to send the header or the footer
82 bool m_header;
83 };
84
85 void SubDocument::parse(std::shared_ptr<WKSContentListener> &listener, libwps::SubDocumentType)
86 {
87 if (!listener.get())
88 {
89 WPS_DEBUG_MSG(("Quattro9ParserInternal::SubDocument::parse: no listener\n"));
90 return;
91 }
92 if (!dynamic_cast<WKSContentListener *>(listener.get()))
93 {
94 WPS_DEBUG_MSG(("Quattro9ParserInternal::SubDocument::parse: bad listener\n"));
95 return;
96 }
97
98 Quattro9Parser *pser = m_parser ? dynamic_cast<Quattro9Parser *>(m_parser) : nullptr;
99 if (!pser)
100 {
101 listener->insertCharacter(' ');
102 WPS_DEBUG_MSG(("Quattro9ParserInternal::SubDocument::parse: bad parser\n"));
103 return;
104 }
105 pser->sendHeaderFooter(m_header);
106 }
107
108 //! a zone name
109 struct ZoneName
110 {
111 //! constructor
112 explicit ZoneName(char const *name, char const *extra=nullptr)
113 : m_name(name)
114 , m_extra(extra==nullptr ? "" : extra)
115 {
116 }
117 //! the zone name
118 std::string m_name;
119 //! the extra data
120 std::string m_extra;
121 };
122
123 //! the state of Quattro9Parser
124 struct State
125 {
126 //! constructor
127 State(libwps_tools_win::Font::Type fontType, char const *password)
128 : m_fontType(fontType)
129 , m_version(-1)
130 , m_password(password)
131 , m_metaData()
132 , m_fontNamesList()
133 , m_fontsList()
134 , m_idToExternalFileMap()
135 , m_idToExternalNameMap()
136 , m_idToFieldMap()
137 , m_actualSheet(-1)
138 , m_actualStrings()
139 , m_isEncrypted(false)
140 , m_isDecoded(false)
141 , m_idToZoneNameMap()
142 {
143 }
144
145 //! return the default font style
146 libwps_tools_win::Font::Type getDefaultFontType() const
147 {
148 if (m_fontType != libwps_tools_win::Font::UNKNOWN)
149 return m_fontType;
150 return libwps_tools_win::Font::WIN3_WEUROPE;
151 }
152 //! returns a default font with file's version */
153 static WPSFont getDefaultFont()
154 {
155 WPSFont res;
156 res.m_name="Times New Roman";
157 res.m_size=12;
158 return res;
159 }
160 //! init the zone name map
161 void initZoneNameMap();
162 //! the user font type
163 libwps_tools_win::Font::Type m_fontType;
164 //! the file version
165 int m_version;
166 //! the password (if known)
167 char const *m_password;
168 //! the meta data
169 librevenge::RVNGPropertyList m_metaData;
170 //! the font name list
171 std::vector<librevenge::RVNGString> m_fontNamesList;
172 //! the font list
173 std::vector<WPSFont> m_fontsList;
174 //! map id to filename
175 std::map<int, librevenge::RVNGString> m_idToExternalFileMap;
176 //! map id to external name
177 std::map<int, librevenge::RVNGString> m_idToExternalNameMap;
178 //! map id to field
179 std::map<int, std::pair<librevenge::RVNGString,QuattroFormulaInternal::CellReference> >m_idToFieldMap;
180 //! the actual sheet id
181 int m_actualSheet;
182 //! the actual string list
183 std::pair<std::shared_ptr<WPSStream>, std::vector<TextEntry> > m_actualStrings;
184 //! true if the file is encrypted
185 bool m_isEncrypted;
186 //! true if the main stream has been decoded
187 bool m_isDecoded;
188 //! map zone id to zone name
189 std::map<int, ZoneName> m_idToZoneNameMap;
190 private:
191 State(State const &)=delete;
192 State &operator=(State const &)=delete;
193 };
194
195 void State::initZoneNameMap()
196 {
197 if (!m_idToZoneNameMap.empty())
198 return;
199 m_idToZoneNameMap=std::map<int,ZoneName>
200 {
201 { 0x1, ZoneName("File", "header")},
202 { 0x2, ZoneName("File", "pointer")},
203 { 0x3, ZoneName("File", "setting")},
204 { 0x4, ZoneName("File", "password")},
205 { 0x5, ZoneName("File", "user")},
206 { 0x6, ZoneName("Font", "name")},
207 { 0x7, ZoneName("Font", "style")},
208 { 0x8, ZoneName("UserFormat")},
209 { 0x9, ZoneName("Style", "name")},
210 { 0xa, ZoneName("Cell", "style")},
211 { 0xb, ZoneName("DLLIdFunct", "lib") },
212 { 0xc, ZoneName("DLLIdFunct", "func") },
213 { 0x101, ZoneName("Group") }, // group of spreadsheet, column, cell, ...
214 { 0x401, ZoneName("Document", "begin") },
215 { 0x402, ZoneName("Document", "end") },
216 { 0x403, ZoneName("Document", "external,link") },
217 { 0x404, ZoneName("Document", "external,link,end") },
218 { 0x405, ZoneName("Document", "external,link,name") },
219 { 0x406, ZoneName("Document", "fields")},
220 { 0x407, ZoneName("Document", "strings")},
221 { 0x408, ZoneName("Document", "formula")},
222 { 0x411, ZoneName("Document", "sep")}, // the document main data seems to be define before
223 { 0x430, ZoneName("Document", "num,sheet") },
224 { 0x488, ZoneName("Selection")}, // checkme
225 { 0x601, ZoneName("Spreadsheet", "begin") }, // or maybe a shape
226 { 0x602, ZoneName("Spreadsheet", "end") },
227 { 0x613, ZoneName("Spreadsheet", "info") },
228 { 0x617, ZoneName("Spreadsheet", "page,break") },
229 { 0x61d, ZoneName("Spreadsheet", "join,cells") },
230 { 0x631, ZoneName("Spreadsheet", "row,def") },
231 { 0x632, ZoneName("Spreadsheet", "col,def") },
232 { 0x633, ZoneName("Spreadsheet", "row,size") },
233 { 0x634, ZoneName("Spreadsheet", "col,size") },
234 { 0x635, ZoneName("Spreadsheet", "rows,size") },
235 { 0x636, ZoneName("Spreadsheet", "cols,size") },
236 { 0x637, ZoneName("Spreadsheet", "row,dSize") }, // related to a change of size determined by the cell content
237 { 0x638, ZoneName("Spreadsheet", "col,dSize") }, // checkme
238 { 0xa01, ZoneName("Spreadsheet", "col,begin") },
239 { 0xa02, ZoneName("Spreadsheet", "col,end") },
240 { 0xa03, ZoneName("Spreadsheet", "col,sep") }, // always follow a01, a separator?
241 { 0xc01, ZoneName("Spreadsheet", "cell,list") },
242 { 0xc02, ZoneName("Spreadsheet", "cell,res") },
243 { 0x1401, ZoneName("Graph", "begin") },
244 { 0x1402, ZoneName("Graph", "end") },
245 { 0x2001, ZoneName("Graph", "zone,begin") },
246 { 0x2002, ZoneName("Graph", "zone,end") },
247 { 0x2051, ZoneName("Graph", "header") },
248 { 0x2052, ZoneName("Graph", "name") },
249 { 0x2073, ZoneName("Button", "name") },
250
251 { 0x2131, ZoneName("Frame", "fill") },
252 { 0x2141, ZoneName("Frame", "pattern") },
253 { 0x2151, ZoneName("Frame", "unknown") },
254 { 0x2161, ZoneName("Frame", "name") },
255 { 0x2171, ZoneName("Frame", "header") },
256 { 0x2184, ZoneName("Frame", "name2") },
257
258 { 0x21d1, ZoneName("OLE", "name") },
259
260 { 0x2221, ZoneName("Shape", "basic") },
261 { 0x2371, ZoneName("Textbox", "style") },
262 { 0x2372, ZoneName("Textbox", "string") },
263 { 0x2374, ZoneName("Textbox", "zone4") },
264 { 0x2375, ZoneName("Textbox", "zone5") },
265
266 { 0x23d1, ZoneName("Shape", "unknown") }, // picture or group?
267
268 { 0x2f30, ZoneName("Pict", "image") },
269
270 { 0x2ff1, ZoneName("Pict", "zone1") },
271 { 0x2ff2, ZoneName("Pict", "dir") },
272 { 0x2ff3, ZoneName("Pict", "zone2") },
273 { 0x2ff4, ZoneName("Pict", "fill[bitmap]") },
274 };
275 }
276
277 ////////////////////////////////////////////////////////////
278 // Text entry
279 ////////////////////////////////////////////////////////////
280 librevenge::RVNGString TextEntry::getString(std::shared_ptr<WPSStream> const &stream, libwps_tools_win::Font::Type type) const
281 {
282 if (empty()) return "";
283 if (!stream || !stream->m_input)
284 {
285 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::getString: can not read a stream\n"));
286 return "";
287 }
288 auto input=stream->m_input;
289 long actPos=input->tell();
290 input->seek(m_entry.begin(), librevenge::RVNG_SEEK_SET);
291 std::string string;
292 for (long i=0; i<m_entry.length(); ++i)
293 {
294 auto c = char(libwps::readU8(input));
295 if (c == '\0') break;
296 if (c == 0xd)
297 {
298 static bool first=true;
299 if (first)
300 {
301 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::getString: find some EOL in string, use send\n"));
302 first=false;
303 }
304 string.push_back(' ');
305 continue;
306 }
307 string.push_back(c);
308 }
309 input->seek(actPos, librevenge::RVNG_SEEK_SET);
310 return libwps_tools_win::Font::unicodeString(string, type);
311 }
312
313 std::string TextEntry::getDebugString(std::shared_ptr<WPSStream> const &stream) const
314 {
315 std::stringstream s;
316 s << getString(stream).cstr();
317 if (m_flag) s << "[fl=" << std::hex << m_flag << std::dec << "]";
318 if (!m_extra.empty()) s << "[" << m_extra << "]";
319 return s.str();
320 }
321
322 void TextEntry::send(std::shared_ptr<WPSStream> const &stream, WPSFont const &font, libwps_tools_win::Font::Type type, WKSContentListenerPtr &listener)
323 {
324 if (!listener)
325 {
326 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::send: called without listener\n"));
327 return;
328 }
329 if (empty()) return;
330 if (!stream || !stream->m_input)
331 {
332 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::send: can not read a stream\n"));
333 return;
334 }
335 auto input=stream->m_input;
336 long actPos=input->tell();
337 input->seek(m_entry.begin(), librevenge::RVNG_SEEK_SET);
338 bool prevEOL=false;
339 int numFonts=int(m_fontsList.size());
340 auto fontType=type;
341 std::string text;
342 for (long i=0; i<=m_entry.length(); ++i)
343 {
344 auto c=i==m_entry.length() ? '\0' : char(libwps::readU8(input));
345 auto fIt=m_posFontIdMap.find(int(i));
346 if ((fIt!=m_posFontIdMap.end() || c==0 || c==0x9 || c==0xa || c==0xd) && !text.empty())
347 {
348 listener->insertUnicodeString(libwps_tools_win::Font::unicodeString(text, fontType));
349 text.clear();
350 }
351 if (i==m_entry.length()) break;
352 if (fIt!=m_posFontIdMap.end())
353 {
354 auto id=fIt->second;
355 if (id==0)
356 {
357 fontType=type;
358 listener->setFont(font);
359 }
360 else if (id>0 && id<=numFonts)
361 {
362 auto newFont=m_fontsList[size_t(id-1)];
363 if (!newFont.m_name.empty())
364 {
365 auto newType=libwps_tools_win::Font::getFontType(newFont.m_name);
366 if (newType!=libwps_tools_win::Font::UNKNOWN)
367 fontType=newType;
368 }
369 listener->setFont(newFont);
370 }
371 else
372 {
373 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::send: unknown font %d\n", id));
374 }
375 }
376 switch (c)
377 {
378 case 0:
379 break;
380 case 0x9:
381 listener->insertTab();
382 break;
383 case 0xa:
384 if (!prevEOL)
385 {
386 WPS_DEBUG_MSG(("Quattro9ParserInternal::TextEntry::send: find 0xa without 0xd\n"));
387 }
388 break;
389 case 0xd:
390 listener->insertEOL();
391 break;
392 default:
393 text.push_back(c);
394 break;
395 }
396 prevEOL=c==0xd;
397 }
398 input->seek(actPos, librevenge::RVNG_SEEK_SET);
399 }
400
401 }
402
403 // constructor, destructor
404 Quattro9Parser::Quattro9Parser(RVNGInputStreamPtr &input, WPSHeaderPtr &header, libwps_tools_win::Font::Type encoding, char const *password)
405 : WKSParser(input, header)
406 , m_listener()
407 , m_state(new Quattro9ParserInternal::State(encoding, password))
408 , m_graphParser(new Quattro9Graph(*this))
409 , m_spreadsheetParser(new Quattro9Spreadsheet(*this))
410 {
411 }
412
413 Quattro9Parser::~Quattro9Parser()
414 {
415 }
416
417 int Quattro9Parser::version() const
418 {
419 return m_state->m_version;
420 }
421
422 libwps_tools_win::Font::Type Quattro9Parser::getDefaultFontType() const
423 {
424 return m_state->getDefaultFontType();
425 }
426
427 bool Quattro9Parser::getExternalFileName(int fId, librevenge::RVNGString &fName) const
428 {
429 auto it = m_state->m_idToExternalFileMap.find(fId);
430 if (it!=m_state->m_idToExternalFileMap.end())
431 {
432 fName=it->second;
433 return true;
434 }
435 if (fId==2)
436 {
437 // checkme current file?
438 return true;
439 }
440 WPS_DEBUG_MSG(("Quattro9Parser::getExternalFileName: can not find %d name\n", fId));
441 return false;
442 }
443
444 bool Quattro9Parser::getField(int fId, librevenge::RVNGString &text,
445 QuattroFormulaInternal::CellReference &ref,
446 librevenge::RVNGString const &fileName) const
447 {
448 ref.m_cells.clear();
449 if (fId&0x4000)
450 {
451 auto it=m_state->m_idToExternalNameMap.find(fId & 0xbfff);
452 if (it!=m_state->m_idToExternalNameMap.end() && !it->second.empty())
453 {
454 text=it->second;
455 WKSContentListener::FormulaInstruction instr;
456 instr.m_type=instr.F_Text;
457 if (!fileName.empty())
458 {
459 instr.m_content="[";
460 instr.m_content+=fileName.cstr();
461 instr.m_content+="]";
462 }
463 instr.m_content+=it->second.cstr();
464 ref.addInstruction(instr);
465 return true;
466 }
467 WPS_DEBUG_MSG(("Quattro9Parser::getField: can not find %d name\n", fId&0xbfff));
468 return false;
469 }
470 auto it = m_state->m_idToFieldMap.find(fId);
471 if (it!=m_state->m_idToFieldMap.end())
472 {
473 text=it->second.first;
474 ref=it->second.second;
475 if (!fileName.empty()) // unsure
476 {
477 for (auto &r : ref.m_cells)
478 {
479 if (r.m_type==r.F_Cell || r.m_type==r.F_CellList)
480 r.m_fileName=fileName;
481 }
482 }
483 return true;
484 }
485 WPS_DEBUG_MSG(("Quattro9Parser::getField: can not find %d field\n", fId));
486 return false;
487 }
488 //////////////////////////////////////////////////////////////////////
489 // interface with Quattro9Graph
490 //////////////////////////////////////////////////////////////////////
491 bool Quattro9Parser::getColor(int id, WPSColor &color) const
492 {
493 return m_graphParser->getColor(id, color);
494 }
495
496 bool Quattro9Parser::getPattern(int id, WPSGraphicStyle::Pattern &pattern) const
497 {
498 return m_graphParser->getPattern(id, pattern);
499 }
500
501 bool Quattro9Parser::sendPageGraphics(int sheetId) const
502 {
503 return m_graphParser->sendPageGraphics(sheetId);
504 }
505
506 //////////////////////////////////////////////////////////////////////
507 // interface with Quattro9Spreadsheet
508 //////////////////////////////////////////////////////////////////////
509 bool Quattro9Parser::getFont(int id, WPSFont &font) const
510 {
511 if (id < 0 || id>=int(m_state->m_fontsList.size()))
512 {
513 WPS_DEBUG_MSG(("Quattro9Parser::getFont: can not find font %d\n", id));
514 return false;
515 }
516 font=m_state->m_fontsList[size_t(id)];
517 return true;
518 }
519
520 Vec2f Quattro9Parser::getCellPosition(int sheetId, Vec2i const &cell) const
521 {
522 return m_spreadsheetParser->getPosition(sheetId, cell);
523 }
524
525 void Quattro9Parser::addDocumentStrings()
526 {
527 if (!m_state->m_actualStrings.first || m_state->m_actualStrings.second.empty())
528 return;
529 m_spreadsheetParser->addDocumentStrings(m_state->m_actualStrings.first, m_state->m_actualStrings.second);
530 m_state->m_actualStrings.first.reset();
531 m_state->m_actualStrings.second.clear();
532 }
533
534 // main function to parse the document
535 void Quattro9Parser::parse(librevenge::RVNGSpreadsheetInterface *documentInterface)
536 {
537 RVNGInputStreamPtr input=getInput();
538 if (!input)
539 {
540 WPS_DEBUG_MSG(("Quattro9Parser::parse: does not find main ole\n"));
541 throw (libwps::ParseException());
542 }
543
544 if (!checkHeader(nullptr)) throw(libwps::ParseException());
545
546 bool ok=false;
547 try
548 {
549 ascii().setStream(input);
550 ascii().open("MN0");
551 if (checkHeader(nullptr) && readZones())
552 m_listener=createListener(documentInterface);
553 if (m_listener)
554 {
555 m_spreadsheetParser->setListener(m_listener);
556 m_graphParser->setListener(m_listener);
557 m_graphParser->updateState();
558 m_spreadsheetParser->updateState();
559
560 m_listener->startDocument();
561 int numSheet=m_spreadsheetParser->getNumSpreadsheets();
562 if (numSheet==0) ++numSheet;
563 for (int i=0; i<numSheet; ++i)
564 m_spreadsheetParser->sendSpreadsheet(i);
565 m_listener->endDocument();
566 m_listener.reset();
567 ok = true;
568 }
569 }
570 catch (...)
571 {
572 WPS_DEBUG_MSG(("Quattro9Parser::parse: exception catched when parsing MN0\n"));
573 throw (libwps::ParseException());
574 }
575
576 ascii().reset();
577 if (!ok)
578 throw(libwps::ParseException());
579 }
580
581 std::shared_ptr<WKSContentListener> Quattro9Parser::createListener(librevenge::RVNGSpreadsheetInterface *interface)
582 {
583 std::vector<WPSPageSpan> pageList;
584 WPSPageSpan ps;
585 int numSheet=m_spreadsheetParser->getNumSpreadsheets();
586 if (numSheet<=0) numSheet=1;
587 ps.setPageSpan(numSheet);
588 pageList.push_back(ps);
589 auto listener=std::make_shared<WKSContentListener>(pageList, interface);
590 listener->setMetaData(m_state->m_metaData);
591 return listener;
592 }
593
594 ////////////////////////////////////////////////////////////
595 // low level
596 ////////////////////////////////////////////////////////////
597 // read the header
598 ////////////////////////////////////////////////////////////
599 bool Quattro9Parser::checkHeader(WPSHeader *header, bool strict)
600 {
601 m_state.reset(new Quattro9ParserInternal::State(m_state->m_fontType, m_state->m_password));
602 auto input=getInput();
603 auto mainStream=std::make_shared<WPSStream>(input, ascii());
604 if (!mainStream || !checkHeader(mainStream, strict))
605 return false;
606 if (header)
607 {
608 header->setMajorVersion(m_state->m_version);
609 header->setCreator(libwps::WPS_QUATTRO_PRO);
610 header->setKind(libwps::WPS_SPREADSHEET);
611 header->setIsEncrypted(m_state->m_isEncrypted);
612 header->setNeedEncoding(true);
613 }
614 return true;
615 }
616
617 bool Quattro9Parser::checkHeader(std::shared_ptr<WPSStream> stream, bool strict)
618 {
619 if (!stream || !stream->checkFilePosition(14))
620 {
621 WPS_DEBUG_MSG(("Quattro9Parser::checkHeader: file is too short\n"));
622 return false;
623 }
624 RVNGInputStreamPtr input = stream->m_input;
625 libwps::DebugFile &ascFile=stream->m_ascii;
626 libwps::DebugStream f;
627
628 m_state->m_version=2000;
629 input->seek(0,librevenge::RVNG_SEEK_SET);
630 // basic check: check if the first zone has type=1, length=14 and begins with QPW9
631 if (libwps::readU16(input)!=1 || libwps::readU16(input)!=0xe || libwps::readU32(input)!=0x39575051)
632 return false;
633 if (strict)
634 {
635 input->seek(0,librevenge::RVNG_SEEK_SET);
636 for (int i=0; i < 6; ++i)
637 {
638 if (!readZone(stream)) return false;
639 if (m_state->m_isEncrypted) break;
640 }
641 }
642 ascFile.addPos(0);
643 ascFile.addNote(f.str().c_str());
644
645 return true;
646 }
647
648 bool Quattro9Parser::readZones()
649 {
650 m_graphParser->cleanState();
651 m_spreadsheetParser->cleanState();
652 m_state->initZoneNameMap();
653
654 auto stream=std::make_shared<WPSStream>(getInput(), ascii());
655 RVNGInputStreamPtr &input = stream->m_input;
656 input->seek(0, librevenge::RVNG_SEEK_SET);
657 while (stream->checkFilePosition(input->tell()+4))
658 {
659 if (!readZone(stream))
660 break;
661 if (m_state->m_isEncrypted && !m_state->m_isDecoded)
662 throw(libwps::PasswordException());
663 }
664 if (!input->isEnd())
665 {
666 WPS_DEBUG_MSG(("Quattro9Parser::readZones: find extra data\n"));
667 libwps::DebugFile &ascFile=stream->m_ascii;
668 ascFile.addPos(input->tell());
669 ascFile.addNote("Entries(Unknown):###");
670 }
671 parseOLEStream(getFileInput(), "NativeContent_MAIN");
672 return m_spreadsheetParser->getNumSpreadsheets();
673 }
674
675 bool Quattro9Parser::parseOLEStream(RVNGInputStreamPtr input, std::string const &avoid)
676 {
677 if (!input || !input->isStructured())
678 {
679 WPS_DEBUG_MSG(("Quattro9Parser::parseOLEStream: oops, can not find the input stream\n"));
680 return false;
681 }
682 std::map<std::string,size_t> dirToIdMap;
683 WPSOLEParser oleParser(avoid, libwps_tools_win::Font::WIN3_WEUROPE,
684 [&dirToIdMap](std::string const &dir)
685 {
686 if (dirToIdMap.find(dir)==dirToIdMap.end())
687 dirToIdMap[dir]=dirToIdMap.size();
688 return int(dirToIdMap.find(dir)->second);
689 });
690 oleParser.parse(input);
691 oleParser.updateMetaData(m_state->m_metaData);
692 auto objectMap=oleParser.getObjectsMap();
693 std::map<librevenge::RVNGString,WPSEmbeddedObject> nameToObjectsMap;
694 for (auto it : dirToIdMap)
695 {
696 if (it.first.empty()) continue;
697 auto linkName=it.first;
698 auto pos = linkName.find_last_of('/');
699 if (pos != std::string::npos)
700 linkName=linkName.substr(pos+1);
701 if (!linkName.empty())
702 nameToObjectsMap[linkName.c_str()]=objectMap.find(int(it.second))->second;
703 for (int wh=0; wh<2; ++wh)
704 {
705 std::string name=it.first+"/"+(wh==0 ? "LinkInfo" : "BOlePart");
706 RVNGInputStreamPtr cOle(input->getSubStreamByName(name.c_str()));
707 if (!cOle)
708 {
709 WPS_DEBUG_MSG(("Quattro9Parser::parseOLEStream: oops, can not find link info for dir %s\n", name.c_str()));
710 continue;
711 }
712 libwps::DebugFile asciiFile(cOle);
713 asciiFile.open(libwps::Debug::flattenFileName(name));
714 if (wh==1)
715 readOleBOlePart(std::make_shared<WPSStream>(cOle,asciiFile));
716 else
717 readOleLinkInfo(std::make_shared<WPSStream>(cOle,asciiFile));
718 }
719 }
720 if (!nameToObjectsMap.empty())
721 m_graphParser->storeObjects(nameToObjectsMap);
722 return true;
723 }
724
725 bool Quattro9Parser::readZone(std::shared_ptr<WPSStream> &stream)
726 {
727 if (!stream)
728 return false;
729 RVNGInputStreamPtr input = stream->m_input;
730 libwps::DebugFile &ascFile=stream->m_ascii;
731 libwps::DebugStream f;
732 long pos = input->tell();
733 auto id = int(libwps::readU16(input));
734 bool const bigBlock=id&0x8000;
735 long sz = bigBlock ? long(libwps::readU32(input)) : long(libwps::readU16(input));
736 int const headerSize=bigBlock ? 6 : 4;
737 id &= 0x7fff;
738 if (sz<0 || !stream->checkFilePosition(pos+headerSize+sz))
739 {
740 WPS_DEBUG_MSG(("Quattro9Parser::readZone: size is bad\n"));
741 input->seek(pos, librevenge::RVNG_SEEK_SET);
742 return false;
743 }
744
745 auto zIt=m_state->m_idToZoneNameMap.find(id);
746 if (zIt==m_state->m_idToZoneNameMap.end())
747 f << "Entries(Zone" << std::hex << id << std::dec << "A):";
748 else if (zIt->second.m_extra.empty())
749 f << "Entries(" << zIt->second.m_name << "):";
750 else
751 f << "Entries(" << zIt->second.m_name << ")[" << zIt->second.m_extra << "]:";
752 ascFile.addPos(pos);
753 ascFile.addNote(f.str().c_str());
754
755 f.str("");
756 bool ok = true, isParsed = false, needWriteInAscii = false;
757 int val;
758 input->seek(pos, librevenge::RVNG_SEEK_SET);
759 switch (id)
760 {
761 case 0x1:
762 {
763 if (sz!=14) break;
764 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
765 std::string type; // QWP9
766 for (int i=0; i<4; ++i) type+=char(libwps::readU8(input));
767 f << type << ",";
768 val=int(libwps::readU16(input)); // QPW 9: 0, QPW X9: 19
769 m_state->m_version=2000+val+1;
770 if (val) f << "vers=" << val << ",";
771 for (int i=0; i<4; ++i) // f1=ee|201, f4=1-5
772 {
773 val=int(libwps::read16(input));
774 int const expected[]= {0, 1, 0, 0};
775 if (val!=expected[i]) f << "f" << i << "=" << val << ",";
776 }
777 isParsed=needWriteInAscii=true;
778 break;
779 }
780 // no data
781 case 0x400:
782 case 0x481:
783 case 0x4a1:
784 case 0x4a3:
785 if (sz!=0) break;
786 isParsed=needWriteInAscii=true;
787 break;
788
789 // bool
790 case 0x48c: // 1
791 case 0x48d: // 0
792 case 0x4a4: // 0|3|4
793 case 0x4a8: // 0
794 case 0x4aa: // 0
795 case 0x4ab: // 0
796 case 0x4ac: // 0
797 case 0x4ad: // 0
798 case 0x4b2: // 1
799 case 0x4b6: // 1
800 case 0x4b9: // 0
801 if (sz!=1) break;
802 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
803 val=int(libwps::read8(input));
804 if (val)
805 f << "f0=" << val << ",";
806 isParsed=needWriteInAscii=true;
807 break;
808 // int
809 case 0x430: // num spreadsheet?
810 case 0x48a: // 0|3
811 case 0x485: // 64
812 case 0x487: // 0
813 case 0x4b0: // 1
814 case 0x4b4: // 64
815 case 0x4b5: // 1|9 (2 by files)
816 case 0xa03: // 0 (after a01 before c01 a03)
817 if (sz!=2) break;
818 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
819 val=int(libwps::read16(input));
820 if (val)
821 f << "f0=" << val << ",";
822 isParsed=needWriteInAscii=true;
823 break;
824 // 2 int
825 case 0x482: // 0
826 case 0x4ae: // 0
827 case 0x4af: // 0
828 case 0x2374: // 0
829 case 0x2375: // 0
830 if (sz!=4) break;
831 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
832 for (int i=0; i<2; ++i)
833 {
834 val=int(libwps::read16(input));
835 if (val)
836 f << "f" << i << "=" << val << ",";
837 }
838 isParsed=needWriteInAscii=true;
839 break;
840 // 3 int
841 case 0x4a6: // 0
842 case 0x4a7: // 0
843 if (sz!=6) break;
844 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
845 for (int i=0; i<3; ++i)
846 {
847 val=int(libwps::read16(input));
848 if (val)
849 f << "f" << i << "=" << val << ",";
850 }
851 isParsed=needWriteInAscii=true;
852 break;
853
854 // zone with pointer
855
856 // 2 file positions
857 case 0x2: // f0=0, f1=pointer to a zone 402
858 case 0x402: // f0= pointer to a previous zone 401, f1=0
859 {
860 long fPos[2];
861 isParsed=readFilePositions(stream,fPos);
862 break;
863 }
864 case 0x3:
865 if (sz<2) break;
866 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
867 val=int(libwps::readU16(input));
868 if (val==0x20) break; // normal
869 if (val&3) f << "protection=" << (val&3) << ",";
870 if (val&0xffdc)
871 f << "fl=" << std::hex << (val&0xffdc) << std::dec << ",";
872 break;
873 case 0x4:
874 m_state->m_isEncrypted=true;
875 if (sz==20)
876 {
877 m_state->m_isEncrypted=true;
878 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
879 uint16_t fileKey(libwps::readU16(input));
880 f << "pass=" << std::hex << fileKey << std::dec << ",";
881 f << "len=" << int(libwps::readU16(input)) << ",";
882 isParsed = needWriteInAscii = true;
883 std::vector<uint8_t> keys;
884 keys.resize(16);
885 for (auto &k : keys) k=uint8_t(libwps::readU8(input));
886 // to check users password:
887 // call libwps::encodeLotusPassword(m_state->m_password, key, lotusKeys, someDefValues);
888 // and check if int16_t(key<<8|key>>8)==fileKey
889 if (!m_state->m_isDecoded)
890 {
891 auto newInput=decodeStream(input, keys);
892 if (newInput)
893 {
894 // let's replace the current input by the decoded input
895 m_state->m_isDecoded=true;
896 stream->m_input=newInput;
897 stream->m_ascii.setStream(newInput);
898 }
899 }
900 }
901 if (!m_state->m_isDecoded)
902 {
903 WPS_DEBUG_MSG(("Quattro9Parser::parse: can not decode the file\n"));
904 }
905 break;
906 case 0x5:
907 {
908 if (sz<4) break;
909 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
910 for (int i=0; i<2; ++i)
911 {
912 Quattro9ParserInternal::TextEntry entry;
913 if (readPString(stream, pos+headerSize+sz, entry))
914 f << entry.getDebugString(stream) << ",";
915 else
916 {
917 WPS_DEBUG_MSG(("Quattro9Parser::readZone[user]: can not read a string\n"));
918 f << "###";
919 break;
920 }
921 }
922 isParsed=needWriteInAscii=true;
923 break;
924 }
925 case 0x6:
926 isParsed=readFontNames(stream);
927 break;
928 case 0x7:
929 isParsed=readFontStyles(stream);
930 break;
931 case 0x8:
932 {
933 if (sz<6) break;
934 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
935 int fId=int(libwps::readU16(input));
936 f << "id=" << fId << ",";
937 val=int(libwps::readU16(input)); // 0
938 if (val) f << "f0=" << val << ",";
939 std::string format;
940 for (long i=0; i<sz-4; ++i)
941 {
942 auto c = char(libwps::readU8(input));
943 if (c == '\0') break;
944 format.push_back(c);
945 }
946 if (!format.empty())
947 {
948 m_spreadsheetParser->addUserFormat(fId, libwps_tools_win::Font::unicodeString(format, libwps_tools_win::Font::WIN3_WEUROPE));
949 f << format << ",";
950 }
951 if (input->tell()!=pos+headerSize+sz) ascFile.addDelimiter(input->tell(),'|');
952 isParsed=needWriteInAscii=true;
953 break;
954 }
955 case 0x9:
956 {
957 if (sz<2) break;
958 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
959 int N=int(libwps::readU16(input));
960 for (int i=0; i<N; ++i)
961 {
962 int fId=int(libwps::readU16(input));
963 f << "Styl" << fId << "=[";
964 val=int(libwps::readU16(input));
965 if (val!=fId) f << "id2=" << val << ",";
966 Quattro9ParserInternal::TextEntry entry;
967 if (readPString(stream, pos+headerSize+sz, entry))
968 f << entry.getDebugString(stream) << ",";
969 else
970 {
971 WPS_DEBUG_MSG(("Quattro9Parser::readZone[style]: can not read a name\n"));
972 f << "###";
973 break;
974 }
975 f << "],";
976 }
977 isParsed=needWriteInAscii=true;
978 break;
979 }
980 case 0xa:
981 ok=isParsed=m_spreadsheetParser->readCellStyles(stream);
982 break;
983 case 0xb:
984 case 0xc:
985 {
986 if (sz<6) break;
987 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
988 val=int(libwps::readU16(input));
989 f << "id=" << val << ",";
990 Quattro9ParserInternal::TextEntry entry;
991 if (!readPString(stream, pos+headerSize+sz, entry))
992 f << "###";
993 else
994 {
995 m_spreadsheetParser->addDLLIdName(val, entry.getString(stream), id==0xb);
996 f << entry.getDebugString(stream) << ",";
997 }
998 isParsed=needWriteInAscii=true;
999 break;
1000 }
1001 case 0x101: // list of 601|a01|c01 zone...
1002 {
1003 if (sz<6 || (sz%4)!=2) break;
1004 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1005 f << "type=" << std::hex << int(libwps::readU16(input)) << std::dec << ",";
1006 int dim[2];
1007 for (auto &d : dim) d=int(libwps::read16(input));
1008 f << "limits=" << Vec2i(dim[0], dim[1]) << ",";
1009 int N=int((sz-6)/4);
1010 f << "pos=[";
1011 for (int i=0; i<N; ++i)
1012 f << std::hex << libwps::readU32(input) << std::dec << ",";
1013 f << "],";
1014 isParsed=needWriteInAscii=true;
1015 break;
1016 }
1017 case 0x403:
1018 {
1019 if (sz<16) break;
1020 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1021 int lId=int(libwps::readU16(input));
1022 f << "id=" << lId << ",";
1023 for (int i=0; i<2; ++i) // 0
1024 {
1025 val=int(libwps::read16(input));
1026 if (val) f << "f" << i << "=" << val << ",";
1027 }
1028 Quattro9ParserInternal::TextEntry entry;
1029 if (!readPString(stream, pos+headerSize+sz, entry))
1030 f << "###";
1031 else
1032 {
1033 f << entry.getDebugString(stream) << ",";
1034 auto &map = m_state->m_idToExternalFileMap;
1035 if (map.find(lId)!=map.end())
1036 {
1037 WPS_DEBUG_MSG(("Quattro9Parser::readZone[link,file]: a link with id=%d already exists\n", lId));
1038 f << "###dup,";
1039 }
1040 else
1041 map[lId]=entry.getString(stream);
1042 }
1043 isParsed=needWriteInAscii=true;
1044 break;
1045 }
1046 case 0x404:
1047 if (sz!=0) break;
1048 m_state->m_actualStrings.first.reset();
1049 m_state->m_actualStrings.second.clear(); // clean potential external strings
1050 isParsed=needWriteInAscii=true;
1051 break;
1052 case 0x405:
1053 {
1054 if (sz<20) break;
1055 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1056 val=int(libwps::read16(input)); // 0
1057 if (val) f << "f0=" << val << ",";
1058 int lId=int(libwps::readU16(input));
1059 f << "id=" << lId << ",";
1060 for (int i=0; i<2; ++i) // 0, lId
1061 {
1062 val=int(libwps::read16(input));
1063 if (val) f << "f" << i+2 << "=" << val << ",";
1064 }
1065 Quattro9ParserInternal::TextEntry entry;
1066 if (!readPString(stream, pos+headerSize+sz, entry))
1067 f << "###";
1068 else
1069 {
1070 f << entry.getDebugString(stream) << ",";
1071 auto &map = m_state->m_idToExternalNameMap;
1072 if (map.find(lId)!=map.end())
1073 {
1074 WPS_DEBUG_MSG(("Quattro9Parser::readZone[link,name]: a link with id=%d already exists\n", lId));
1075 f << "###dup,";
1076 }
1077 else
1078 map[lId]=entry.getString(stream);
1079 }
1080 isParsed=needWriteInAscii=true;
1081 break;
1082 }
1083 case 0x406:
1084 isParsed=readDocumentFields(stream);
1085 break;
1086 case 0x407:
1087 // used to store the strings which appears in cell, but also some strings which appear in link, ...
1088 ok=isParsed=readDocumentStrings(stream);
1089 break;
1090 case 0x408:
1091 addDocumentStrings();
1092 ok=isParsed=m_spreadsheetParser->readDocumentFormulas(stream);
1093 break;
1094 case 0x411: // always with 0
1095 if (sz<1) break;
1096 val=int(libwps::readU8(input));
1097 if (val) f << "f0=" << val << ",";
1098 addDocumentStrings(); // last time to save the main document strings
1099 isParsed=needWriteInAscii=true;
1100 break;
1101 case 0x601:
1102 ok=isParsed=m_spreadsheetParser->readBeginSheet(stream, m_state->m_actualSheet);
1103 break;
1104 case 0x602:
1105 ok=isParsed=m_spreadsheetParser->readEndSheet(stream);
1106 m_state->m_actualSheet=-1;
1107 break;
1108 case 0x613:
1109 if (sz!=24) break;
1110 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1111 for (int i=0; i<6; ++i) // 0
1112 {
1113 val=int(libwps::read16(input));
1114 if (val) f << "f" << i << "=" << val << ",";
1115 }
1116 for (int i=0; i<4; ++i)
1117 {
1118 val=int(libwps::readU16(input));
1119 int const expected[]= {0x759c,0x8800,0xe43c, 0x7e37};
1120 if (val!=expected[i]) f << "f" << i+6 << "=" << std::hex << val << std::dec << ",";
1121 }
1122 for (int i=0; i<4; ++i)
1123 {
1124 val=int(libwps::read8(input));
1125 int const expected[]= {4,3,5,4};
1126 if (val!=expected[i]) f << "f" << i+10 << "=" << val << ",";
1127 }
1128 isParsed=needWriteInAscii=true;
1129 break;
1130 case 0x617:
1131 isParsed=m_spreadsheetParser->readPageBreak(stream);
1132 break;
1133 case 0x61d:
1134 isParsed=m_spreadsheetParser->readMergedCells(stream);
1135 break;
1136 case 0x631:
1137 case 0x632:
1138 isParsed=m_spreadsheetParser->readColRowDefault(stream);
1139 break;
1140 case 0x633:
1141 case 0x634:
1142 isParsed=m_spreadsheetParser->readColRowDimension(stream);
1143 break;
1144 case 0x635:
1145 case 0x636:
1146 isParsed=m_spreadsheetParser->readColRowDimensions(stream);
1147 break;
1148 case 0x637:
1149 case 0x638: // checkme
1150 if (sz!=6) break;
1151 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1152 f << "id=" << libwps::readU32(input) << ",";
1153 val=int(libwps::readU8(input)); // height/width in dpi?
1154 f << "size?=" << val << ",";
1155 val=int(libwps::readU8(input)); // 0, da, 5b
1156 if (val) f << "fl=" << std::hex << val << std::dec << ",";
1157 isParsed=needWriteInAscii=true;
1158 break;
1159 case 0xa01:
1160 ok=isParsed=m_spreadsheetParser->readBeginColumn(stream);
1161 break;
1162 case 0xa02:
1163 ok=isParsed=m_spreadsheetParser->readEndColumn(stream);
1164 break;
1165 case 0xc01:
1166 ok = isParsed = m_spreadsheetParser->readCellList(stream);
1167 break;
1168 case 0xc02:
1169 isParsed = m_spreadsheetParser->readCellResult(stream);
1170 break;
1171
1172 case 0x1401:
1173 case 0x1402:
1174 isParsed = m_graphParser->readBeginEnd(stream, m_state->m_actualSheet);
1175 break;
1176
1177 case 0x2001:
1178 case 0x2002:
1179 isParsed = m_graphParser->readBeginEndZone(stream);
1180 break;
1181
1182 case 0x2051:
1183 isParsed=m_graphParser->readGraphHeader(stream);
1184 break;
1185
1186 case 0x2131:
1187 isParsed=m_graphParser->readFrameStyle(stream);
1188 break;
1189 case 0x2141:
1190 isParsed=m_graphParser->readFramePattern(stream);
1191 break;
1192 case 0x2171:
1193 isParsed=m_graphParser->readFrameHeader(stream);
1194 break;
1195 case 0x21d1:
1196 isParsed=m_graphParser->readOLEName(stream);
1197 break;
1198 case 0x2221:
1199 case 0x23d1:
1200 isParsed=m_graphParser->readShape(stream);
1201 break;
1202 case 0x2371:
1203 isParsed=m_graphParser->readTextboxStyle(stream);
1204 break;
1205 case 0x2372:
1206 isParsed=m_graphParser->readTextboxText(stream);
1207 break;
1208
1209 // case 0x2371: fSz1,fSz2, 0,0, name1,name2, ....
1210 case 0x2052:
1211 case 0x2073:
1212 case 0x2161:
1213 case 0x2184:
1214 {
1215 if (sz<2) break;
1216 input->seek(pos+headerSize, librevenge::RVNG_SEEK_SET);
1217 Quattro9ParserInternal::TextEntry entry;
1218 if (readPString(stream, pos+headerSize+sz, entry))
1219 f << entry.getDebugString(stream) << ",";
1220 else
1221 {
1222 WPS_DEBUG_MSG(("Quattro9Parser::readZone[name]: can not read a string\n"));
1223 f << "###";
1224 break;
1225 }
1226 isParsed=needWriteInAscii=true;
1227 break;
1228 }
1229
1230 default:
1231 break;
1232 }
1233 if (!ok)
1234 {
1235 input->seek(pos, librevenge::RVNG_SEEK_SET);
1236 return false;
1237 }
1238 input->seek(pos+headerSize+sz, librevenge::RVNG_SEEK_SET);
1239 if (isParsed)
1240 {
1241 if (needWriteInAscii)
1242 {
1243 ascFile.addPos(pos);
1244 ascFile.addNote(f.str().c_str());
1245 }
1246 return true;
1247 }
1248 if (sz)
1249 ascFile.addDelimiter(pos+headerSize,'|');
1250 ascFile.addPos(pos);
1251 ascFile.addNote(f.str().c_str());
1252 return true;
1253 }
1254
1255 ////////////////////////////////////////////////////////////
1256 // generic
1257 ////////////////////////////////////////////////////////////
1258 bool Quattro9Parser::readPString(std::shared_ptr<WPSStream> const &stream, long endPos, Quattro9ParserInternal::TextEntry &entry)
1259 {
1260 RVNGInputStreamPtr input = stream->m_input;
1261 long pos = input->tell();
1262 entry=Quattro9ParserInternal::TextEntry();
1263 if (pos+4>endPos || !stream->checkFilePosition(endPos))
1264 {
1265 WPS_DEBUG_MSG(("Quattro9Parser::readPString: string's size seems bad\n"));
1266 return false;
1267 }
1268 int dSz=int(libwps::readU16(input));
1269 if (pos+4+dSz>endPos)
1270 {
1271 WPS_DEBUG_MSG(("Quattro9Parser::readPString: string's size seems bad\n"));
1272 return false;
1273 }
1274 entry.m_flag=int(libwps::readU8(input));
1275
1276 entry.m_entry.setBegin(input->tell());
1277 entry.m_entry.setLength(dSz);
1278 input->seek(pos+4+dSz, librevenge::RVNG_SEEK_SET);
1279 // entry.m_flag&0x20 frequent no data
1280 if (entry.m_flag&0x2)
1281 {
1282 if (!readTextStyles(stream, endPos, entry))
1283 return false;
1284 }
1285 if (entry.m_flag&0xdd)
1286 {
1287 WPS_DEBUG_MSG(("Quattro9Parser::readPString: find some unknown flag, some data may be lost\n"));
1288 entry.m_extra="";
1289 }
1290 return true;
1291 }
1292
1293 bool Quattro9Parser::readFontNames(std::shared_ptr<WPSStream> const &stream)
1294 {
1295 RVNGInputStreamPtr input = stream->m_input;
1296 libwps::DebugFile &ascFile=stream->m_ascii;
1297 libwps::DebugStream f;
1298 long pos = input->tell();
1299 auto type = int(libwps::readU16(input)&0x7fff);
1300
1301 if (type != 6)
1302 {
1303 WPS_DEBUG_MSG(("Quattro9Parser::readFontNames: not a font zone\n"));
1304 return false;
1305 }
1306 auto sz = long(libwps::readU16(input));
1307 int N=int(libwps::readU16(input));
1308 long endPos=pos+4+sz;
1309 for (int i=0; i<N; ++i)
1310 {
1311 pos=input->tell();
1312 f.str("");
1313 f << "Font-FN" << i << ":";
1314 Quattro9ParserInternal::TextEntry entry;
1315 librevenge::RVNGString font;
1316 if (readPString(stream, endPos, entry))
1317 {
1318 font=entry.getString(stream);
1319 f << entry.getDebugString(stream) << ",";
1320 }
1321 else
1322 {
1323 WPS_DEBUG_MSG(("Quattro9Parser::readFontNames: can not read a string\n"));
1324 f << "###";
1325 ascFile.addPos(pos);
1326 ascFile.addNote(f.str().c_str());
1327 return true;
1328 }
1329 ascFile.addPos(pos);
1330 ascFile.addNote(f.str().c_str());
1331 m_state->m_fontNamesList.push_back(font);
1332 }
1333 return true;
1334 }
1335
1336 bool Quattro9Parser::readFontStyles(std::shared_ptr<WPSStream> const &stream)
1337 {
1338 RVNGInputStreamPtr input = stream->m_input;
1339 libwps::DebugFile &ascFile=stream->m_ascii;
1340 libwps::DebugStream f;
1341 auto type = int(libwps::readU16(input)&0x7fff);
1342
1343 if (type != 7)
1344 {
1345 WPS_DEBUG_MSG(("Quattro9Parser::readFontStyles: not a font zone\n"));
1346 return false;
1347 }
1348 auto sz = long(libwps::readU16(input));
1349 int N=int(libwps::readU16(input));
1350 f << "N=" << N << ",";
1351 if (2+16*N!=sz)
1352 {
1353 WPS_DEBUG_MSG(("Quattro9Parser::readFontStyles: the number of data seems bad\n"));
1354 f << "###";
1355 return false;
1356 }
1357 for (int i=0; i<N; ++i)
1358 {
1359 long pos=input->tell();
1360 f.str("");
1361 f << "Font-F" << i << ":";
1362 WPSFont font;
1363 int fId=int(libwps::readU16(input));
1364 if (fId<int(m_state->m_fontNamesList.size()))
1365 font.m_name=m_state->m_fontNamesList[size_t(fId)];
1366 else
1367 f << "###FN" << fId << ",";
1368 int val=int(libwps::readU16(input)); // system font id?
1369 f << "id" << val << ",";
1370 val=int(libwps::readU16(input)); // 0
1371 if (val) f << "f0=" << val << ",";
1372 auto fSize = int(libwps::readU16(input));
1373 if (fSize >= 1 && fSize <= 50) // check maximumn
1374 font.m_size=double(fSize);
1375 else
1376 f << "###fSize=" << fSize << ",";
1377 val=int(libwps::readU16(input)); // 0
1378 if (val) f << "f1=" << val << ",";
1379
1380 uint32_t attributes = 0;
1381 val=int(libwps::readU16(input));
1382 if (val&1) attributes|=WPS_UNDERLINE_BIT;
1383 if (val&0x10) attributes|=WPS_UNDERLINE_BIT;
1384 if (val&0x20) attributes|=WPS_DOUBLE_UNDERLINE_BIT;
1385 val &= 0xffce;
1386 if (val) f << "f2=" << val << ",";
1387 val=int(libwps::readU16(input));
1388 if (val&1) attributes|=WPS_ITALICS_BIT;
1389 if (val&0x10) attributes|=WPS_STRIKEOUT_BIT;
1390 val &= 0xffee;
1391 if (val) f << "f3=" << val << ",";
1392 val=int(libwps::readU16(input));
1393 if (val==700) attributes|=WPS_BOLD_BIT;
1394 else if (val!=400) // 400=normal
1395 f << "f4=" << val << ",";
1396 font.m_attributes=attributes;
1397 m_state->m_fontsList.push_back(font);
1398 f << font;
1399 ascFile.addPos(pos);
1400 ascFile.addNote(f.str().c_str());
1401 input->seek(pos+16, librevenge::RVNG_SEEK_SET);
1402 }
1403 return true;
1404 }
1405
1406 bool Quattro9Parser::readTextStyles(std::shared_ptr<WPSStream> const &stream, long endPos, Quattro9ParserInternal::TextEntry &entry)
1407 {
1408 RVNGInputStreamPtr input = stream->m_input;
1409 long pos=input->tell();
1410 if (pos+2>endPos)
1411 {
1412 WPS_DEBUG_MSG(("Quattro9Parser::readTextStyles: the zone is too short\n"));
1413 return false;
1414 }
1415 int dSz=int(libwps::readU16(input));
1416 if (dSz<6 || pos+dSz>endPos)
1417 {
1418 WPS_DEBUG_MSG(("Quattro9Parser::readTextStyles: the zone size is bad\n"));
1419 return false;
1420 }
1421 endPos=pos+dSz;
1422 libwps::DebugFile &ascFile=stream->m_ascii;
1423 libwps::DebugStream f;
1424 f << "Entries(TextStyle):";
1425 int nPos=int(libwps::readU16(input));
1426 f << "n[pos]=" << nPos << ",";
1427 int nFont=int(libwps::readU16(input));
1428 f << "n[font]=" << nFont << ",";
1429 if (dSz<6+4*nPos+42*nFont)
1430 {
1431 WPS_DEBUG_MSG(("Quattro9Parser::readTextStyles: the number of position seems bad\n"));
1432 f << "###";
1433 nPos=nFont=0;
1434 }
1435 int actC=0;
1436 for (int i=0; i<nPos; ++i)
1437 {
1438 int nC=int(libwps::readU16(input));
1439 int id=int(libwps::readU16(input));
1440 entry.m_posFontIdMap[actC]=id;
1441 f << actC << ":Ft" << id << ",";
1442 actC+=nC;
1443 }
1444 entry.m_fontsList.resize(size_t(nFont));
1445 int dataSz=nFont>0 ? (dSz-6-4*nPos)/nFont : 42;
1446 for (auto &font : entry.m_fontsList)
1447 {
1448 if (readTextFontStyles(stream, dataSz, font))
1449 continue;
1450 break;
1451 }
1452 ascFile.addPos(pos);
1453 ascFile.addNote(f.str().c_str());
1454 input->seek(endPos, librevenge::RVNG_SEEK_SET);
1455 return true;
1456 }
1457
1458 bool Quattro9Parser::readTextFontStyles(std::shared_ptr<WPSStream> const &stream, int dataSz, WPSFont &font)
1459 {
1460 font=WPSFont();
1461 RVNGInputStreamPtr input = stream->m_input;
1462 long pos=input->tell();
1463 if (dataSz<42 || !stream->checkFilePosition(pos+dataSz))
1464 {
1465 WPS_DEBUG_MSG(("Quattro9Parser::readTextFontStyles: the zone is too short\n"));
1466 return false;
1467 }
1468 libwps::DebugFile &ascFile=stream->m_ascii;
1469 libwps::DebugStream f;
1470 f << "TextStyle[font]";
1471 auto fSize = int(libwps::readU16(input));
1472 if (fSize >= 1 && fSize <= 50) // check maximumn
1473 font.m_size=double(fSize);
1474 else
1475 f << "###fSize=" << fSize << ",";
1476 uint32_t attributes = 0;
1477 auto flags = int(libwps::readU16(input));
1478 if (flags & 1) attributes |= WPS_BOLD_BIT;
1479 if (flags & 2) attributes |= WPS_ITALICS_BIT;
1480 if (flags & 4) attributes |= WPS_UNDERLINE_BIT;
1481 if (flags & 8) attributes |= WPS_SUBSCRIPT_BIT; // reserved
1482 if (flags & 0x10) attributes |= WPS_SUPERSCRIPT_BIT; // reserved
1483 if (flags & 0x20) attributes |= WPS_STRIKEOUT_BIT;
1484 if (flags & 0x40) attributes |= WPS_DOUBLE_UNDERLINE_BIT; // reserved
1485 if (flags & 0x80) attributes |= WPS_OUTLINE_BIT; // reserved
1486 if (flags & 0x100) attributes |= WPS_SHADOW_BIT; // reserved
1487 font.m_attributes=attributes;
1488 if (flags&0xfe00)
1489 f << "##fl=" << std::hex << (flags&0xfe00) << std::dec << ",";
1490
1491 auto const fontType = getDefaultFontType();
1492 std::string name;
1493 for (long i=0; i<32; ++i)
1494 {
1495 auto c = char(libwps::readU8(input));
1496 if (c == '\0') break;
1497 name.push_back(c);
1498 }
1499 if (!name.empty())
1500 font.m_name=libwps_tools_win::Font::unicodeString(name, fontType);
1501 input->seek(pos+36, librevenge::RVNG_SEEK_SET);
1502 unsigned char col[4];
1503 for (auto &c: col) c=static_cast<unsigned char>(libwps::readU8(input));
1504 font.m_color=WPSColor(col[0],col[1],col[2]);
1505 f << font;
1506 if (dataSz==42)
1507 {
1508 int val=int(libwps::readU16(input));
1509 if (val!=flags) f << "fl2=" << std::hex << val << std::dec << ",";
1510 }
1511 else
1512 {
1513 ascFile.addDelimiter(input->tell(),'|');
1514 input->seek(pos+dataSz, librevenge::RVNG_SEEK_SET);
1515 }
1516 ascFile.addPos(pos);
1517 ascFile.addNote(f.str().c_str());
1518 return true;
1519 }
1520
1521 bool Quattro9Parser::readDocumentFields(std::shared_ptr<WPSStream> const &stream)
1522 {
1523 RVNGInputStreamPtr input = stream->m_input;
1524 libwps::DebugFile &ascFile=stream->m_ascii;
1525 libwps::DebugStream f;
1526
1527 long pos = input->tell();
1528 auto type = long(libwps::readU16(input)&0x7fff);
1529 if (type !=0x406)
1530 {
1531 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentFields: not a spreadsheet zone\n"));
1532 return false;
1533 }
1534 long sz = libwps::readU16(input);
1535 long endPos=pos+4+sz;
1536 long N=long(libwps::readU16(input));
1537 f << "N=" << N << ",";
1538 if (sz<2 || 2+N*28>sz || !stream->checkFilePosition(endPos))
1539 {
1540 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentFields: the size seems bad\n"));
1541 return false;
1542 }
1543 ascFile.addPos(pos);
1544 ascFile.addNote(f.str().c_str());
1545
1546 auto fontType=getDefaultFontType();
1547 for (long i=0; i<N; ++i)
1548 {
1549 pos=input->tell();
1550 if (pos+28>endPos) break;
1551 f.str("");
1552 f << "Document[fields]:Field" << i+1 << ",";
1553 int fSz=int(libwps::readU16(input));
1554 long endFieldPos=pos+fSz;
1555 if (fSz<28 || endFieldPos>endPos)
1556 {
1557 input->seek(pos, librevenge::RVNG_SEEK_SET);
1558 break;
1559 }
1560 bool hasRef=false;
1561 for (int j=0; j<3; ++j)
1562 {
1563 int val=int(libwps::readU16(input));
1564 if (!val) continue;
1565 if (j==1)
1566 {
1567 if (val&0x40)
1568 {
1569 f << "hasRef,";
1570 hasRef=true;
1571 }
1572 val &= 0xffbf;
1573 }
1574 if (val)
1575 f << "f" << j << "=" << val << ",";
1576 }
1577 Quattro9ParserInternal::TextEntry entry;
1578 bool ok=true;
1579 if (!readPString(stream, endPos, entry) || input->tell()+16>endFieldPos)
1580 {
1581 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentFields: can not read the field name\n"));
1582 f << "###";
1583 ok=false;
1584 }
1585 else
1586 f << entry.getDebugString(stream) << ",";
1587 if (ok && hasRef)
1588 {
1589 QuattroFormulaInternal::CellReference instr;
1590 if (!m_spreadsheetParser->readCellReference(stream, endFieldPos, instr))
1591 {
1592 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentFields: can not read some reference\n"));
1593 f << "###";
1594 ok=false;
1595 }
1596 else
1597 {
1598 f << instr;
1599 m_state->m_idToFieldMap[int(i+1)]=
1600 std::pair<librevenge::RVNGString,QuattroFormulaInternal::CellReference>(entry.getString(stream, fontType), instr);
1601 }
1602 }
1603 if (ok && input->tell()+16<=endFieldPos)
1604 {
1605 for (int j=0; j<8; ++j) // 0
1606 {
1607 int val=int(libwps::readU16(input));
1608 if (!val) continue;
1609 f << "g" << j << "=" << val << ",";
1610 }
1611 }
1612 if (input->tell()!=endFieldPos)
1613 ascFile.addDelimiter(input->tell(),'|');
1614 ascFile.addPos(pos);
1615 ascFile.addNote(f.str().c_str());
1616 input->seek(endFieldPos, librevenge::RVNG_SEEK_SET);
1617 }
1618 if (input->tell()!=endPos)
1619 {
1620 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentFields: find extra data\n"));
1621 ascFile.addPos(input->tell());
1622 ascFile.addNote("Document[fields]:###extra");
1623 }
1624 return true;
1625 }
1626
1627 bool Quattro9Parser::readDocumentStrings(std::shared_ptr<WPSStream> const &stream)
1628 {
1629 m_state->m_actualStrings.first=stream;
1630 auto &entries=m_state->m_actualStrings.second;
1631 entries.clear();
1632 RVNGInputStreamPtr input = stream->m_input;
1633 libwps::DebugFile &ascFile=stream->m_ascii;
1634 libwps::DebugStream f;
1635
1636 long pos = input->tell();
1637 auto type = long(libwps::readU16(input));
1638 bool const bigBlock=type&0x8000;
1639 int const headerSize = bigBlock ? 6 : 4;
1640 if ((type&0x7fff) !=0x407)
1641 {
1642 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentStrings: not a spreadsheet zone\n"));
1643 return false;
1644 }
1645 long sz = bigBlock ? long(libwps::readU32(input)) : long(libwps::readU16(input));
1646 long endPos=pos+headerSize+sz;
1647 long N=long(libwps::readU32(input));
1648 f << "N=" << N << ",";
1649 if (sz<12 || N<0 || (sz-headerSize-8)/4<N || !stream->checkFilePosition(endPos))
1650 {
1651 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentStrings: the size seems bad\n"));
1652 return false;
1653 }
1654 f << "f0=" << libwps::readU32(input) << ",";
1655 f << "f1=" << libwps::readU32(input) << ",";
1656 ascFile.addPos(pos);
1657 ascFile.addNote(f.str().c_str());
1658
1659 entries.reserve(size_t(N));
1660 for (long i=0; i<N; ++i)
1661 {
1662 pos=input->tell();
1663 librevenge::RVNGString text;
1664 f.str("");
1665 f << "Document[strings]:Str" << i+1 << ",";
1666 Quattro9ParserInternal::TextEntry entry;
1667 if (!readPString(stream, endPos, entry))
1668 {
1669 input->seek(pos, librevenge::RVNG_SEEK_SET);
1670 break;
1671 }
1672 entries.push_back(entry);
1673 f << entry.getDebugString(stream) << ",";
1674 ascFile.addPos(pos);
1675 ascFile.addNote(f.str().c_str());
1676 }
1677 if (input->tell()!=endPos)
1678 {
1679 if (int(entries.size())==N)
1680 {
1681 WPS_DEBUG_MSG(("Quattro9Parser::readDocumentStrings: find extra data\n"));
1682 }
1683 ascFile.addPos(input->tell());
1684 ascFile.addNote("Document[strings]:###extra");
1685 }
1686 return true;
1687 }
1688
1689 bool Quattro9Parser::readFilePositions(std::shared_ptr<WPSStream> const &stream, long (&filePos)[2])
1690 {
1691 RVNGInputStreamPtr input = stream->m_input;
1692 libwps::DebugFile &ascFile=stream->m_ascii;
1693 libwps::DebugStream f;
1694
1695 long pos = input->tell();
1696 if (!stream->checkFilePosition(pos+12))
1697 {
1698 WPS_DEBUG_MSG(("Quattro9Parser::readFilePositions: the zone is too short\n"));
1699 return false;
1700 }
1701 auto type = long(libwps::readU16(input)&0x7fff);
1702 if ((type&0xf) !=0x2)
1703 {
1704 WPS_DEBUG_MSG(("Quattro9Parser::readFilePositions: unexpected type\n"));
1705 return false;
1706 }
1707 long sz = libwps::readU16(input);
1708 long endPos=pos+4+sz;
1709 if (sz<8 || !stream->checkFilePosition(endPos))
1710 {
1711 WPS_DEBUG_MSG(("Quattro9Parser::readFilePositions: the size seems bad\n"));
1712 return false;
1713 }
1714 for (int i=0; i<2; ++i)
1715 {
1716 auto &lPos=filePos[i];
1717 lPos=long(libwps::readU32(input));
1718 if (lPos==0) continue;
1719 if (lPos<0 || !stream->checkFilePosition(lPos))
1720 {
1721 filePos[i]=0;
1722 WPS_DEBUG_MSG(("Quattro9Parser::readFilePositions: a position seems bad\n"));
1723 f << "###";
1724 }
1725 f << "pos" << i << "=" << std::hex << lPos << std::dec << ",";
1726 }
1727 if (sz!=8)
1728 {
1729 WPS_DEBUG_MSG(("Quattro9Parser::readFilePositions: find extra data\n"));
1730 f << "###";
1731 ascFile.addDelimiter(input->tell(),'|');
1732 }
1733 ascFile.addPos(pos);
1734 ascFile.addNote(f.str().c_str());
1735 return true;
1736 }
1737 // ----------------------------------------------------------------------
1738 // Header/Footer
1739 // ----------------------------------------------------------------------
1740 void Quattro9Parser::sendHeaderFooter(bool /*header*/)
1741 {
1742 if (!m_listener)
1743 {
1744 WPS_DEBUG_MSG(("Quattro9Parser::sendHeaderFooter: can not find the listener\n"));
1745 return;
1746 }
1747 WPS_DEBUG_MSG(("Quattro9Parser::sendHeaderFooter: not implemented\n"));
1748 m_listener->setFont(m_state->getDefaultFont());
1749 }
1750
1751 ////////////////////////////////////////////////////////////
1752 // ole stream
1753 ////////////////////////////////////////////////////////////
1754 bool Quattro9Parser::readOleLinkInfo(std::shared_ptr<WPSStream> stream)
1755 {
1756 if (!stream || !stream->checkFilePosition(4))
1757 {
1758 WPS_DEBUG_MSG(("Quattro9Parser::readLinkInfo: unexpected zone\n"));
1759 return false;
1760 }
1761 RVNGInputStreamPtr input = stream->m_input;
1762 libwps::DebugFile &ascFile=stream->m_ascii;
1763 libwps::DebugStream f;
1764 f << "Entries(LinkInfo):";
1765 int val=libwps::readU8(input);
1766 if (val!=0x53)
1767 f << "f0=" << std::hex << val << std::dec << ",";
1768 val=libwps::readU16(input); // 2 or 3
1769 if (val) f << "f1=" << val << ",";
1770 std::string name;
1771 while (!input->isEnd())
1772 {
1773 char c=char(libwps::readU8(input));
1774 if (!c) break;
1775 name+=c;
1776 }
1777 if (!name.empty())
1778 f << "name=" << name << ",";
1779 ascFile.addPos(0);
1780 ascFile.addNote(f.str().c_str());
1781 return true;
1782 }
1783
1784 bool Quattro9Parser::readOleBOlePart(std::shared_ptr<WPSStream> stream)
1785 {
1786 if (!stream || !stream->checkFilePosition(20))
1787 {
1788 WPS_DEBUG_MSG(("Quattro9Parser::readOleBOlePart: unexpected zone\n"));
1789 return false;
1790 }
1791 RVNGInputStreamPtr input = stream->m_input;
1792 libwps::DebugFile &ascFile=stream->m_ascii;
1793 libwps::DebugStream f;
1794 f << "Entries(BOlePart):";
1795 for (int i=0; i<5; ++i) // f0=1, f1=f2=small int(often 1), f3=f4=small int(often 1)
1796 {
1797 auto val=int(libwps::read32(input));
1798 if (val!=1) f << "f" << i << "=" << val << ",";
1799 }
1800 ascFile.addPos(0);
1801 ascFile.addNote(f.str().c_str());
1802 return true;
1803 }
1804
1805 ////////////////////////////////////////////////////////////
1806 // decode
1807 ////////////////////////////////////////////////////////////
1808 RVNGInputStreamPtr Quattro9Parser::decodeStream(RVNGInputStreamPtr input, std::vector<uint8_t> const &key)
1809 {
1810 //int const vers=version();
1811 if (!input || key.size()!=16)
1812 {
1813 WPS_DEBUG_MSG(("Quattro9Parser::decodeStream: the arguments seems bad\n"));
1814 return RVNGInputStreamPtr();
1815 }
1816 long actPos=input->tell();
1817 input->seek(0,librevenge::RVNG_SEEK_SET);
1818 librevenge::RVNGBinaryData data;
1819 if (!libwps::readDataToEnd(input, data) || !data.getDataBuffer())
1820 {
1821 WPS_DEBUG_MSG(("Quattro9Parser::decodeStream: can not read the original input\n"));
1822 return RVNGInputStreamPtr();
1823 }
1824 auto *buf=const_cast<unsigned char *>(data.getDataBuffer());
1825 auto endPos=long(data.size());
1826 input->seek(actPos,librevenge::RVNG_SEEK_SET);
1827 std::stack<long> stack;
1828 stack.push(endPos);
1829 while (!input->isEnd() && !stack.empty())
1830 {
1831 long pos=input->tell();
1832 if (pos+4>stack.top()) break;
1833 auto id=libwps::readU16(input);
1834 bool const bigBlock=id&0x8000;
1835 id &= 0x7fff;
1836 auto sSz=bigBlock ? long(libwps::readU32(input)) : long(libwps::readU16(input));
1837 int const headerSize=bigBlock ? 6 : 4;
1838 if (sSz<0 || pos+headerSize+sSz>stack.top())
1839 {
1840 input->seek(pos,librevenge::RVNG_SEEK_SET);
1841 break;
1842 }
1843 uint32_t d7=uint32_t(input->tell())&0xf;
1844 for (int i=0; i<sSz; ++i)
1845 {
1846 auto c=uint8_t(libwps::readU8(input));
1847 c=(c^key[(d7++)&0xf]);
1848 buf[pos+headerSize+i]=uint8_t((c>>5)|(c<<3));
1849 }
1850 // main zone ends with zone 2
1851 if (id==2)
1852 {
1853 input->seek(stack.top(),librevenge::RVNG_SEEK_SET);
1854 stack.pop();
1855 }
1856 }
1857 if (input->tell()!=endPos)
1858 {
1859 WPS_DEBUG_MSG(("Quattro9Parser::decodeStream: can not decode the end of the file, data may be bad %lx %lx\n", static_cast<unsigned long>(input->tell()), static_cast<unsigned long>(endPos)));
1860 }
1861 RVNGInputStreamPtr res(new WPSStringStream(data.getDataBuffer(), static_cast<unsigned int>(endPos)));
1862 res->seek(actPos, librevenge::RVNG_SEEK_SET);
1863 return res;
1864 }
1865
1866 /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */