Debian Codegraph @

src/lib/Multiplan.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 <cmath>
26 #include <set>
27 #include <sstream>
28
29 #include <librevenge-stream/librevenge-stream.h>
30
31 #include "libwps_internal.h"
32 #include "libwps_tools_win.h"
33
34 #include "WKSContentListener.h"
35 #include "WKSSubDocument.h"
36
37 #include "WPSCell.h"
38 #include "WPSEntry.h"
39 #include "WPSFont.h"
40 #include "WPSHeader.h"
41 #include "WPSPageSpan.h"
42 #include "WPSStringStream.h"
43 #include "WPSTable.h"
44
45 #include "Multiplan.h"
46
47 namespace libwps
48 {
49
50 //! Internal: namespace to define internal class of MultiplanParser
51 namespace MultiplanParserInternal
52 {
53 //! the font of a MultiplanParser
54 struct Font final : public WPSFont
55 {
56 //! constructor
57 explicit Font(libwps_tools_win::Font::Type type) : WPSFont(), m_type(type)
58 {
59 }
60 //! destructor
61 ~Font() final;
62 //! font encoding type
63 libwps_tools_win::Font::Type m_type;
64 };
65
66 Font::~Font()
67 {
68 }
69
70 //! a cellule of a Lotus spreadsheet
71 class Cell final : public WPSCell
72 {
73 public:
74 /// constructor
75 Cell() : WPSCell() { }
76 //! call when a cell must be send
77 bool send(WPSListenerPtr &/*listener*/) final;
78
79 //! call when the content of a cell must be send
80 bool sendContent(WPSListenerPtr &/*listener*/) final
81 {
82 WPS_DEBUG_MSG(("MultiplanInternal::Cell::sendContent: must not be called\n"));
83 return false;
84 }
85 };
86 bool Cell::send(WPSListenerPtr &/*listener*/)
87 {
88 WPS_DEBUG_MSG(("MultiplanInternal::Cell::send: must not be called\n"));
89 return false;
90 }
91 //! a data cell zone
92 struct Zone
93 {
94 //! the different enum type
95 enum Type { Zone0=0, Link, FileName, SharedData, Name,
96 CellData, CellPosition, Undef
97 };
98 //! constructor
99 Zone()
100 : m_entry()
101 , m_positionsSet()
102 {
103 }
104 //! returns true if the zone entry is valid
105 bool isValid() const
106 {
107 return m_entry.valid();
108 }
109 //! returns the name corresponding to a type
110 static std::string getName(int type)
111 {
112 char const *wh[]= { "Zone0", "Link", "FileName", "SharedData", "Names",
113 "CellData", "CellPos", "UndefZone"
114 };
115 if (type<0 || type>=int(WPS_N_ELEMENTS(wh)))
116 {
117 WPS_DEBUG_MSG(("MultiplanInternal::Zone::getName: called with unexpected type=%d\n", type));
118 return "UndefZone";
119 }
120 return wh[type];
121 }
122 //! the zone data
123 WPSEntry m_entry;
124 //! list of position in the zone
125 std::set<int> m_positionsSet;
126 };
127 //! the state of MultiplanParser
128 struct State
129 {
130 //! constructor
131 State(libwps_tools_win::Font::Type fontType, char const *password)
132 : m_eof(-1)
133 , m_version(-1)
134 , m_fontType(fontType)
135 , m_maximumCell()
136 , m_columnWidths()
137 , m_zonesList(1, Zone())
138 , m_cellPositionsMap()
139 , m_posToLinkMap()
140 , m_posToNameMap()
141 , m_posToSharedDataSeen()
142
143 , m_password(password)
144 , m_hash(0)
145 , m_checksum(0)
146 {
147 for (auto &k : m_keys) k=0;
148 }
149 //! return the default font style
150 libwps_tools_win::Font::Type getDefaultFontType() const
151 {
152 if (m_fontType != libwps_tools_win::Font::UNKNOWN)
153 return m_fontType;
154 return libwps_tools_win::Font::CP_437;
155 }
156
157 //! returns a default font (Courier12) with file's version to define the default encoding */
158 static WPSFont getDefaultFont()
159 {
160 WPSFont res;
161 res.m_name="Courier";
162 res.m_size=12;
163 return res;
164 }
165 //! returns the column width in point
166 std::vector<WPSColumnFormat> getColumnsWidth() const;
167
168 //! the last file position
169 long m_eof;
170 //! the file version
171 int m_version;
172 //! the user font type
173 libwps_tools_win::Font::Type m_fontType;
174 //! the maximumCell
175 Vec2i m_maximumCell;
176 //! the columns width in char, 0 means default
177 std::vector<int> m_columnWidths;
178 //! the list of cell's data zone
179 std::vector<Zone> m_zonesList;
180 //! the positions of each cell: a vector for each row
181 std::map<int,std::vector<int> > m_cellPositionsMap;
182 //! the different main spreadsheet zones
183 WPSEntry m_entries[5];
184 //! the list of link instruction
185 std::map<int, WKSContentListener::FormulaInstruction> m_posToLinkMap;
186 //! the map name's pos to name's cell instruction
187 std::map<int, WKSContentListener::FormulaInstruction> m_posToNameMap;
188 //! a set a shared data already seen
189 std::set<int> m_posToSharedDataSeen;
190
191 //! the password (if known)
192 char const *m_password;
193 //! the file hash
194 int m_hash;
195 //! the file checksum
196 int m_checksum;
197 //! the list of decoding keys
198 uint8_t m_keys[16];
199 private:
200 State(State const &) = delete;
201 State &operator=(State const &) = delete;
202 };
203
204 std::vector<WPSColumnFormat> State::getColumnsWidth() const
205 {
206 std::vector<WPSColumnFormat> res;
207 WPSColumnFormat const defFormat(64);
208 for (auto p : m_columnWidths)
209 {
210 if (p<0 || p>=255)
211 res.push_back(defFormat);
212 else
213 res.push_back(WPSColumnFormat(float(8*p)));
214 }
215 if (res.size()<64) res.resize(64, defFormat);
216 return res;
217 }
218 }
219
220 // constructor, destructor
221 MultiplanParser::MultiplanParser(RVNGInputStreamPtr &input, WPSHeaderPtr &header,
222 libwps_tools_win::Font::Type encoding, char const *password)
223 : WKSParser(input, header)
224 , m_listener()
225 , m_state(new MultiplanParserInternal::State(encoding, password))
226 {
227 }
228
229 MultiplanParser::~MultiplanParser()
230 {
231 }
232
233 int MultiplanParser::version() const
234 {
235 return m_state->m_version;
236 }
237
238 bool MultiplanParser::checkFilePosition(long pos)
239 {
240 if (m_state->m_eof < 0)
241 {
242 RVNGInputStreamPtr input = getInput();
243 long actPos = input->tell();
244 input->seek(0, librevenge::RVNG_SEEK_END);
245 m_state->m_eof=input->tell();
246 input->seek(actPos, librevenge::RVNG_SEEK_SET);
247 }
248 return pos <= m_state->m_eof;
249 }
250
251 libwps_tools_win::Font::Type MultiplanParser::getDefaultFontType() const
252 {
253 return m_state->getDefaultFontType();
254 }
255
256 ////////////////////////////////////////////////////////////
257 // main function to parse the document
258 ////////////////////////////////////////////////////////////
259 void MultiplanParser::parse(librevenge::RVNGSpreadsheetInterface *documentInterface)
260 {
261 RVNGInputStreamPtr input=getInput();
262 if (!input)
263 {
264 WPS_DEBUG_MSG(("MultiplanParser::parse: does not find input!!!\n"));
265 throw (libwps::ParseException());
266 }
267
268 if (!checkHeader(nullptr)) throw(libwps::ParseException());
269
270 bool ok=false;
271 try
272 {
273 ascii().setStream(input);
274 ascii().open("MN0");
275
276 if (checkHeader(nullptr) && readZones())
277 m_listener=createListener(documentInterface);
278 if (m_listener)
279 {
280 m_listener->startDocument();
281 sendSpreadsheet();
282 m_listener->endDocument();
283 ok = true;
284 }
285 }
286 catch (libwps::PasswordException())
287 {
288 ascii().reset();
289 WPS_DEBUG_MSG(("MultiplanParser::parse: password exception catched when parsing MN0\n"));
290 throw (libwps::PasswordException());
291 }
292 catch (...)
293 {
294 WPS_DEBUG_MSG(("MultiplanParser::parse: exception catched when parsing MN0\n"));
295 throw (libwps::ParseException());
296 }
297
298 m_listener.reset();
299 ascii().reset();
300 if (!ok)
301 throw(libwps::ParseException());
302 }
303
304 std::shared_ptr<WKSContentListener> MultiplanParser::createListener(librevenge::RVNGSpreadsheetInterface *interface)
305 {
306 std::vector<WPSPageSpan> pageList;
307 WPSPageSpan ps;
308 pageList.push_back(ps);
309 return std::shared_ptr<WKSContentListener>(new WKSContentListener(pageList, interface));
310 }
311
312 ////////////////////////////////////////////////////////////
313 // low level
314 ////////////////////////////////////////////////////////////
315 // read the header
316 ////////////////////////////////////////////////////////////
317 bool MultiplanParser::checkHeader(WPSHeader *header, bool strict)
318 {
319 libwps::DebugStream f;
320
321 RVNGInputStreamPtr input = getInput();
322 if (!checkFilePosition(0x29a))
323 {
324 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: file is too short\n"));
325 return false;
326 }
327
328 input->seek(0,librevenge::RVNG_SEEK_SET);
329 int fileSign=int(libwps::readU16(input));
330 auto &vers=m_state->m_version;
331 if (fileSign==0xe708)
332 vers=1;
333 else if (fileSign==0xec0c)
334 vers=2;
335 else if (fileSign==0xed0c)
336 vers=3;
337 else
338 return false;
339 f << "FileHeader:vers=" << vers << ",";
340 if (vers==3)
341 {
342 input->seek(22, librevenge::RVNG_SEEK_SET);
343 m_state->m_hash=int(libwps::readU16(input));
344 m_state->m_checksum=int(libwps::readU16(input));
345 if (m_state->m_hash || m_state->m_checksum)
346 {
347 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: the file is protected with a password\n"));
348 }
349 }
350 long const endHeader=vers== 1 ? 0xfa : 0x112;
351 if (strict)
352 {
353 // read the spreadsheet dimension
354 input->seek(endHeader, librevenge::RVNG_SEEK_SET);
355 int dim[2];
356 for (auto &d : dim) d=int(libwps::readU16(input));
357 if (dim[0]==0 || dim[0]>=(vers==1 ? 256 : 4096) || dim[1]==0 || dim[1]>=256)
358 {
359 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: the spreadsheet dimension is bad\n"));
360 return false;
361 }
362 if (vers==1)
363 {
364 // read the last zone list position and check that it corresponds to a valid position
365 input->seek(0x28a, librevenge::RVNG_SEEK_SET);
366 int lastPos=0;
367 for (int i=0; i<8; ++i)
368 {
369 int newPos=int(libwps::readU16(input));
370 if (i==4) newPos+=lastPos; // length
371 if (i==5)
372 {
373 lastPos=newPos;
374 continue;
375 }
376 if (newPos<lastPos)
377 {
378 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: find bad position\n"));
379 return false;
380 }
381 if (i==1 && newPos-lastPos!=2*dim[0]*dim[1])
382 {
383 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: the first zone size seems bad\n"));
384 return false;
385 }
386 lastPos=newPos;
387 }
388 if (lastPos<4 || !checkFilePosition(0x29a+lastPos))
389 {
390 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: can not find last spreadsheet position\n"));
391 return false;
392 }
393 }
394 else
395 {
396 // check if we can find the spreadsheet's data zone
397 if (!checkFilePosition(0x3c7))
398 {
399 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: can not find the data main position\n"));
400 return false;
401 }
402 input->seek(0x3c5, librevenge::RVNG_SEEK_SET);
403 long dataPos=long(libwps::readU16(input));
404 if (dataPos<0x3c7 || !checkFilePosition(dataPos+20))
405 {
406 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: the data main position seems bad\n"));
407 return false;
408 }
409 input->seek(dataPos+2, librevenge::RVNG_SEEK_SET);
410 int actType=6;
411 // check if we can read the main spreadsheet zone
412 while (!input->isEnd())
413 {
414 long pos=input->tell();
415 bool ok=checkFilePosition(pos+6);
416 int val=ok ? int(libwps::readU16(input)) : 0;
417 if (val==6 && actType==12) // row zone, ok if we have find some cell's data zones
418 {
419 input->seek(pos, librevenge::RVNG_SEEK_SET);
420 break;
421 }
422 if (val<=12 && (val>actType || val==12)) // we can have main cell data's zone
423 {
424 actType=val;
425 input->seek(2, librevenge::RVNG_SEEK_CUR);
426 int dSz=int(libwps::readU16(input));
427 if (dSz>=6 && checkFilePosition(pos+dSz))
428 {
429 input->seek(pos+dSz, librevenge::RVNG_SEEK_SET);
430 continue;
431 }
432 }
433 WPS_DEBUG_MSG(("MultiplanParser::checkHeader: can not read some zone\n"));
434 return false;
435 }
436 }
437 }
438 ascii().addPos(0);
439 ascii().addNote(f.str().c_str());
440 input->seek(vers==1 ? 0x2 : 0x1a, librevenge::RVNG_SEEK_SET);
441 for (int i=0; i<8; ++i)
442 {
443 long pos=input->tell();
444 f.str("");
445 f << "Entries(LinkFiles)[" << i << "]:";
446 std::string file;
447 for (int c=0; c<0x1f; ++c)
448 {
449 char ch=char(libwps::readU8(input));
450 if (!ch) break;
451 file += ch;
452 }
453 f << file;
454 ascii().addPos(pos);
455 if (file.empty())
456 ascii().addNote("_");
457 else
458 ascii().addNote(f.str().c_str());
459 input->seek(pos+0x1f, librevenge::RVNG_SEEK_SET);
460 }
461 if (header)
462 {
463 header->setMajorVersion(uint8_t(vers));
464 header->setCreator(libwps::WPS_MULTIPLAN);
465 header->setKind(libwps::WPS_SPREADSHEET);
466 header->setNeedEncoding(true);
467 header->setIsEncrypted(m_state->m_hash || m_state->m_checksum);
468 }
469 return true;
470 }
471
472 bool MultiplanParser::readZones()
473 {
474 int const vers=version();
475 if (!readZoneB()) return false;
476 auto input = getInput();
477 long pos=input->tell();
478 libwps::DebugStream f;
479 long const zoneCSz=vers==1 ? 22 : 28;
480 if (!checkFilePosition(pos+zoneCSz*8))
481 {
482 WPS_DEBUG_MSG(("MultiplanParser::readZones: can not read zone C\n"));
483 ascii().addPos(pos);
484 ascii().addNote("Entries(Unknown):###extra");
485 return false;
486 }
487 ascii().addPos(pos);
488 ascii().addNote("Entries(ZoneC):");
489 for (int i=0; i<8; ++i)
490 {
491 pos=input->tell();
492 f.str("");
493 f << "ZoneC" << i << ":";
494 ascii().addPos(pos);
495 ascii().addNote(f.str().c_str());
496 input->seek(pos+zoneCSz, librevenge::RVNG_SEEK_SET);
497 }
498 if (!readColumnsWidth())
499 return false;
500 pos=input->tell();
501 if (!checkFilePosition(pos+29))
502 {
503 WPS_DEBUG_MSG(("MultiplanParser::readZones: can not read zone D\n"));
504 ascii().addPos(pos);
505 ascii().addNote("Entries(Unknown):###extra");
506 return false;
507 }
508 f.str("");
509 f << "Entries(ZoneD):";
510 if (m_state->m_version==1)
511 {
512 ascii().addPos(pos);
513 ascii().addNote(f.str().c_str());
514 input->seek(pos+29, librevenge::RVNG_SEEK_SET);
515 }
516 else
517 {
518 input->seek(pos+27, librevenge::RVNG_SEEK_SET);
519 long newPos=int(libwps::readU16(input));
520 f << "pos=" << std::hex << newPos << std::dec << ",";
521 ascii().addPos(pos);
522 ascii().addNote(f.str().c_str());
523 if (newPos<input->tell() || !checkFilePosition(newPos))
524 {
525 WPS_DEBUG_MSG(("MultiplanParser::readZones: bad position\n"));
526 ascii().addPos(pos);
527 ascii().addNote("###");
528 return false;
529 }
530 while (!input->isEnd())
531 {
532 pos=input->tell();
533 if (pos>=newPos) break;
534 ascii().addPos(pos);
535 ascii().addNote("Entries(ZoneD):");
536 input->seek(pos+50, librevenge::RVNG_SEEK_SET);
537 }
538 input->seek(newPos, librevenge::RVNG_SEEK_SET);
539 if (!readZonesListV2())
540 return false;
541 input=getInput();
542 if (vers==2)
543 readFunctionNamesList();
544 else if (checkFilePosition(input->tell()+12*92))
545 {
546 // unsure, seems like a list of block of size 12 mixed
547 // with other block of different sizes...
548 //
549 // this zone probably contains many junk data
550 ascii().addPos(input->tell());
551 ascii().addNote("Entries(ZoneE):");
552 for (int i=0; i<93; ++i)
553 {
554 pos=input->tell();
555 f.str("");
556 f << "ZoneE" << i << ":";
557 ascii().addPos(pos);
558 ascii().addNote(f.str().c_str());
559 input->seek(pos+12, librevenge::RVNG_SEEK_SET);
560 }
561 }
562 if (!input->isEnd())
563 {
564 ascii().addPos(input->tell());
565 ascii().addNote("Entries(Unknown):###extra");
566 WPS_DEBUG_MSG(("MultiplanParser::readZones: find extra data\n"));
567 }
568 return !m_state->m_cellPositionsMap.empty();
569 }
570 if (!readZonesList())
571 return false;
572 if (!input->isEnd())
573 {
574 WPS_DEBUG_MSG(("MultiplanParser::readZones: find extra data\n"));
575 ascii().addPos(input->tell());
576 ascii().addNote("Entries(Unknown):###extra");
577 }
578 return true;
579 }
580
581 bool MultiplanParser::readColumnsWidth()
582 {
583 auto input = getInput();
584 long pos = input->tell();
585 int const vers=version();
586 int const numCols=vers==1 ? 63 : 255;
587 if (!checkFilePosition(pos+numCols))
588 {
589 WPS_DEBUG_MSG(("MultiplanParser::readColumnsWidth: the zone seems too short\n"));
590 return false;
591 }
592 libwps::DebugStream f;
593 f << "Entries(ColWidth):width=[";
594 for (int i=0; i<numCols; ++i)
595 {
596 int val=int(libwps::readU8(input));
597 if (vers<=2 && val==0) val=255;
598 m_state->m_columnWidths.push_back(val);
599 if (val!=255)
600 f << m_state->m_columnWidths.back() << ",";
601 else
602 f << "_,";
603 }
604 f << "],";
605 ascii().addPos(pos);
606 ascii().addNote(f.str().c_str());
607 return true;
608 }
609
610 bool MultiplanParser::readZonesList()
611 {
612 auto input = getInput();
613 long pos = input->tell();
614 if (!checkFilePosition(pos+16))
615 {
616 WPS_DEBUG_MSG(("MultiplanParser::readZonesList: the zone seems too short\n"));
617 return false;
618 }
619 libwps::DebugStream f;
620 f << "Entries(ZonesList):";
621 int lastPos=0;
622 f << "zones=[";
623 WPSEntry cellPosEntry;
624 for (int i=0; i<8; ++i)
625 {
626 int newPos=int(libwps::readU16(input));
627 if (i==4) newPos+=lastPos; // length
628 if (i==5)
629 {
630 lastPos=newPos;
631 continue;
632 }
633 if (newPos>lastPos)
634 {
635 if (!checkFilePosition(pos+16+newPos))
636 {
637 WPS_DEBUG_MSG(("MultiplanParser::readZonesList: find a bad position"));
638 f << "###";
639 }
640 else
641 {
642 WPSEntry entry;
643 entry.setBegin(pos+16+lastPos);
644 entry.setEnd(pos+16+newPos);
645 MultiplanParserInternal::Zone::Type const what[]=
646 {
647 MultiplanParserInternal::Zone::Zone0,
648 MultiplanParserInternal::Zone::CellPosition,
649 MultiplanParserInternal::Zone::Link,
650 MultiplanParserInternal::Zone::FileName,
651 MultiplanParserInternal::Zone::CellData,
652 MultiplanParserInternal::Zone::Undef, // beg of shared data
653 MultiplanParserInternal::Zone::SharedData,
654 MultiplanParserInternal::Zone::Name,
655 };
656 auto w=what[i];
657 if (w==MultiplanParserInternal::Zone::CellData)
658 {
659 m_state->m_zonesList[0].m_entry=entry;
660 ascii().addPos(pos+16+lastPos);
661 ascii().addNote("Entries(CellData)");
662 }
663 else if (w==MultiplanParserInternal::Zone::CellPosition)
664 cellPosEntry=entry;
665 else
666 m_state->m_entries[w]=entry;
667 }
668 f << std::hex << lastPos << "<->" << newPos << std::dec << ",";
669 lastPos=newPos;
670 }
671 else
672 f << "_,";
673 }
674 f << "],";
675 ascii().addPos(pos);
676 ascii().addNote(f.str().c_str());
677 bool ok=readCellDataPosition(cellPosEntry);
678 for (int i=0; i<5; ++i)
679 {
680 if (!m_state->m_entries[i].valid()) continue;
681 f.str("");
682 f << "Entries(" << MultiplanParserInternal::Zone::getName(i) << "):";
683 ascii().addPos(m_state->m_entries[i].begin());
684 ascii().addNote(f.str().c_str());
685 ascii().addPos(m_state->m_entries[i].end());
686 ascii().addNote("_");
687 input->seek(m_state->m_entries[i].end(), librevenge::RVNG_SEEK_SET);
688 }
689 return ok;
690 }
691
692 bool MultiplanParser::readZonesListV2()
693 {
694 auto input = getInput();
695 long pos = input->tell();
696 if (!checkFilePosition(pos+2+5*6))
697 {
698 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: the zone seems too short\n"));
699 return false;
700 }
701 libwps::DebugStream f;
702 f << "Entries(ZonesList):";
703 int N=int(libwps::readU16(input));
704 f << "N[row]=" << N << ",";
705 ascii().addPos(pos);
706 ascii().addNote(f.str().c_str());
707
708 // time to decode the different crypted zones
709 if (m_state->m_hash || m_state->m_checksum)
710 {
711 if (!m_state->m_password || !checkPassword(m_state->m_password))
712 {
713 if (!retrievePasswordKeys())
714 {
715 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find the password to decode data\n"));
716 throw (libwps::PasswordException());
717 }
718 }
719 input->seek(pos+2, librevenge::RVNG_SEEK_SET);
720 auto newInput=decodeStream(input);
721 if (!newInput) throw (libwps::ParseException());
722 input=newInput;
723 resetInput(newInput);
724 ascii().setStream(newInput);
725 }
726
727 for (int i=0; i<6; ++i)
728 {
729 pos=input->tell();
730 if (!checkFilePosition(pos+6))
731 {
732 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find zone %d\n", i));
733 return false;
734 }
735 int val=int(libwps::readU16(input));
736 if (val<7 || val>12)
737 {
738 input->seek(pos, librevenge::RVNG_SEEK_SET);
739 break;
740 }
741 int type=val-7;
742 MultiplanParserInternal::Zone::Type const what[]=
743 {
744 MultiplanParserInternal::Zone::Zone0,
745 MultiplanParserInternal::Zone::Link,
746 MultiplanParserInternal::Zone::FileName,
747 MultiplanParserInternal::Zone::Name,
748 MultiplanParserInternal::Zone::SharedData,
749 MultiplanParserInternal::Zone::CellData
750 };
751 auto wh=what[type];
752 auto &entry=wh==MultiplanParserInternal::Zone::CellData ?
753 m_state->m_zonesList[0].m_entry : m_state->m_entries[wh];
754 if (entry.valid())
755 {
756 input->seek(pos, librevenge::RVNG_SEEK_SET);
757 break;
758 }
759 f.str("");
760 f << "Entries(" << MultiplanParserInternal::Zone::getName(wh) << "):";
761 val=int(libwps::readU16(input));
762 f << "f0=" << std::hex << val << std::dec << ",";
763 int dSz=int(libwps::readU16(input));
764 if (dSz<6 || !checkFilePosition(pos+dSz))
765 {
766 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find zone %d\n", i));
767 return false;
768 }
769 entry.setBegin(pos);
770 entry.setLength(dSz);
771 ascii().addPos(pos);
772 ascii().addNote(f.str().c_str());
773 input->seek(pos+dSz, librevenge::RVNG_SEEK_SET);
774 if (type==5) break;
775 }
776 while (checkFilePosition(input->tell()+6))
777 {
778 pos=input->tell();
779 if (libwps::readU16(input)!=0xc)
780 {
781 input->seek(pos, librevenge::RVNG_SEEK_SET);
782 break;
783 }
784 f.str("");
785 f << "Entries(CellData)[extra]:";
786 int val=int(libwps::readU16(input));
787 f << "f0=" << std::hex << val << std::dec << ",";
788 int dSz=int(libwps::readU16(input));
789 if (dSz<6 || !checkFilePosition(pos+dSz))
790 {
791 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find extra data cell zone\n"));
792 return false;
793 }
794 m_state->m_zonesList.push_back(MultiplanParserInternal::Zone());
795 auto &entry=m_state->m_zonesList.back().m_entry;
796 entry.setBegin(pos);
797 entry.setLength(dSz);
798 ascii().addPos(pos);
799 ascii().addNote(f.str().c_str());
800 input->seek(pos+dSz, librevenge::RVNG_SEEK_SET);
801 }
802 pos=input->tell();
803 if (!checkFilePosition(pos+2)||int(libwps::readU16(input))!=6)
804 {
805 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find row header\n"));
806 return false;
807 }
808 f.str("");
809 f << "Entries(Row):";
810 ascii().addPos(pos);
811 ascii().addNote(f.str().c_str());
812 for (int i=0; i<N; ++i)
813 {
814 pos=input->tell();
815 if (!checkFilePosition(pos+6))
816 {
817 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find row %d\n", i));
818 return false;
819 }
820 f.str("");
821 f << "Row" << i << ":";
822 int val=int(libwps::readU16(input));
823 if (val!=6) f << "f0=" << val << ",";
824 int dSz=int(libwps::readU16(input));
825 if (dSz<4 || !checkFilePosition(pos+2*dSz))
826 {
827 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find row %d\n", i));
828 return false;
829 }
830 int num=int(libwps::readU16(input));
831 if (8+3*num>2*dSz)
832 {
833 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: can not find row %d\n", i));
834 return false;
835 }
836 int r=int(libwps::readU16(input));
837 if (m_state->m_cellPositionsMap.find(r)!=m_state->m_cellPositionsMap.end())
838 {
839 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: oops, row %d already exists\n", r));
840 return !m_state->m_cellPositionsMap.empty();
841 }
842 f << "row=" << r << ",";
843 std::vector<int> cellPos;
844 f << "data=[";
845 for (int d=0; d<num; ++d)
846 {
847 val=int(libwps::readU16(input));
848 int z=int(libwps::readU8(input));
849 val+=0x10000*z;
850 if (z >= int(m_state->m_zonesList.size()))
851 {
852 WPS_DEBUG_MSG(("MultiplanParser::readZonesListV2: oops, find bad cell pos for row%d\n", r));
853 f << "##" << std::hex << val << std::dec << ",";
854 cellPos.push_back(0);
855 continue;
856 }
857 cellPos.push_back(val);
858 if (val==0)
859 {
860 f << "_,";
861 continue;
862 }
863 f << std::hex << val << std::dec << ",";
864 m_state->m_zonesList[size_t(z)].m_positionsSet.insert(val&0xffff);
865 }
866 m_state->m_cellPositionsMap[r]=cellPos;
867 if (input->tell()!=pos+2*dSz)
868 ascii().addDelimiter(input->tell(),'|');
869 ascii().addPos(pos);
870 ascii().addNote(f.str().c_str());
871 input->seek(pos+2*dSz, librevenge::RVNG_SEEK_SET);
872 }
873 return true;
874 }
875
876 bool MultiplanParser::readFunctionNamesList()
877 {
878 auto input = getInput();
879 if (input->isEnd()) return true;
880 long pos=input->tell();
881 libwps::DebugStream f;
882 f << "Entries(NamFunctions):";
883 while (!input->isEnd())
884 {
885 long actPos=input->tell();
886 int cSz=int(libwps::readU8(input));
887 if (cSz==0 || !checkFilePosition(actPos+1+cSz))
888 {
889 input->seek(actPos, librevenge::RVNG_SEEK_SET);
890 break;
891 }
892 std::string name;
893 for (int i=0; i<cSz; ++i) name+=char(libwps::readU8(input));
894 f << name << ",";
895 }
896 ascii().addPos(pos);
897 ascii().addNote(f.str().c_str());
898 return true;
899 }
900
901 ////////////////////////////////////////////////////////////
902 // double
903 ////////////////////////////////////////////////////////////
904 bool MultiplanParser::readDouble(double &value)
905 {
906 auto input = getInput();
907 long pos=input->tell();
908 value=0;
909 if (!checkFilePosition(pos+8))
910 {
911 WPS_DEBUG_MSG(("MultiplanParser::readDouble: the zone is too short\n"));
912 return false;
913 }
914 if (version()>=2)
915 {
916 bool isNan;
917 if (!libwps::readDouble8(input,value,isNan))
918 {
919 value=0;
920 input->seek(pos+8, librevenge::RVNG_SEEK_SET);
921 }
922 return true;
923 }
924 int exponant=int(libwps::readU8(input));
925 double sign=1;
926 if (exponant&0x80)
927 {
928 exponant&=0x7f;
929 sign=-1;
930 }
931 bool ok=true;
932 double factor=1;
933 for (int i=0; i<7; ++i)
934 {
935 int val=int(libwps::readU8(input));
936 for (int d=0; d<2; ++d)
937 {
938 int v= d==0 ? (val>>4) : (val&0xf);
939 if (v>=10)
940 {
941 WPS_DEBUG_MSG(("MultiplanParser::readDouble: oops find a bad digits\n"));
942 ok=false;
943 break;
944 }
945 factor/=10.;
946 value+=factor*v;
947 }
948 if (!ok) break;
949 }
950 value *= sign*std::pow(10.,exponant-0x40);
951 input->seek(pos+8, librevenge::RVNG_SEEK_SET);
952 return ok;
953 }
954
955 ////////////////////////////////////////////////////////////
956 // formula
957 ////////////////////////////////////////////////////////////
958 namespace MultiplanParserInternal
959 {
960 struct Functions
961 {
962 char const *m_name;
963 int m_arity;
964 };
965
966 static Functions const s_listOperators[] =
967 {
968 // 0
969 { "", -2}, { "", -2}, { "", -2}, { "", -2},
970 { "", -2}, { "", -2}, { "", -2}, { "", -2},
971 { "", -2}, { "", -2}, { "", -2}, { "", -2},
972 { "", -2}, { "", -2}, { "", -2}, { "", -2},
973 // 1
974 { "", -2}, { "", -2}, { "", -2}, { "", -2},
975 { "", -2}, { "", -2}, { "", -2}, { "", -2},
976 { "", -2}, { "", -2}, { "", -2}, { "", -2},
977 { "", -2}, { "", -2}, { "", -2}, { "", -2},
978 // 2
979 { "", -2}, { "", -2}, { "", -2}, { "", -2},
980 { "", -2}, { ":", 2}, { "", -2}, { "", -2},
981 { "", -2}, { "", -2}, { "", -2}, { "", -2},
982 { "", -2}, { ":", 2}, { "", -2}, { "", -2},
983 // 3
984 { "", -2}, { "", -2}, { "", -2}, { "", -2},
985 { "", -2}, { "", -2}, { "", -2}, { "", -2},
986 { "", -2}, { "", -2}, { "", -2}, { "", -2},
987 { "", -2}, { "", -2}, { "", -2}, { "", -2},
988 // 4
989 { "", -2}, { "", -2}, { "", -2}, { "", -2},
990 { "", -2}, { "", -2}, { "", -2}, { "", -2},
991 { "", -2}, { "", -2}, { "", -2}, { "", -2},
992 { "", -2}, { ":", 2}, { "", -2}, { "", -2},
993 // 5
994 { "&", 2}, { "", -2}, { "", -2}, { "", -2},
995 { "", -2}, { "", -2}, { "", -2}, { "", -2},
996 { "", -2}, { "", -2}, { "", -2}, { "", -2},
997 { "", -2}, { "", -2}, { "", -2}, { "", -2},
998 // 6
999 { "<", 2}, { "", -2}, { "<=", 2}, { "", -2},
1000 { "=", 2}, { "", -2}, { ">=", 2}, { "", -2},
1001 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1002 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1003 // 7
1004 { ">", 2}, { "", -2}, { "<>", 2}, { "", -2},
1005 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1006 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1007 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1008 // 8
1009 { "", -2}, { "", -2}, { "+", 2}, { "", -2},
1010 { "-", 2}, { "", -2}, { "*", 2}, { "", -2},
1011 { "/", 2}, { "", -2}, { "^", 2}, { "", -2},
1012 { "+", 1}, { "", -2}, { "-", 1}, { "", -2},
1013 // 9
1014 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1015 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1016 { "%", 1}, { "", -2}, { "", -2}, { "", -2},
1017 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1018 };
1019
1020 static char const *s_listFunctions[]=
1021 {
1022 // 0
1023 "Count", "If", "IsNA", "IsError",
1024 "Sum", "Average", "Min", "Max",
1025 "Row", "Column", "NA", "NPV",
1026 "Stdev", "Dollar", "Fixed", "Sin",
1027 // 1
1028 "Cos", "Tan", "Atan", "Pi",
1029 "Sqrt", "Exp", "Ln", "Log",
1030 "Abs", "Int", "Sign", "Round",
1031 "Lookup", "Index", "Rept", "Mid",
1032 // 2
1033 "Len", "Value", "True", "False",
1034 "And", "Or", "Not", "Mod",
1035 // mac v1 new functions
1036 "IterCnt", "Delta", "PV", "FV",
1037 "NPer", "PMT", "Rate", "MIRR",
1038 // 3
1039 "Irr", nullptr, nullptr, nullptr,
1040 nullptr, nullptr, nullptr, nullptr,
1041 nullptr, nullptr, nullptr, nullptr,
1042 nullptr, nullptr, nullptr, nullptr,
1043 };
1044 }
1045
1046 bool MultiplanParser::readFormula(Vec2i const &cellPos, std::vector<WKSContentListener::FormulaInstruction> &formula, long endPos, std::string &error)
1047 {
1048 formula.clear();
1049 auto input = getInput();
1050 std::vector<std::vector<WKSContentListener::FormulaInstruction> > stack;
1051 auto const &listOperators=MultiplanParserInternal::s_listOperators;
1052 int const numOperators=int(WPS_N_ELEMENTS(listOperators));
1053 auto const &listFunctions=MultiplanParserInternal::s_listFunctions;
1054 int const numFunctions=int(WPS_N_ELEMENTS(listFunctions));
1055 bool ok=true;
1056 int closeDelayed=0;
1057 bool checkForClose=false;
1058 while (input->tell()<=endPos)
1059 {
1060 long pos=input->tell();
1061 int wh=pos==endPos ? -1 : int(libwps::readU8(input));
1062 bool needCloseParenthesis=closeDelayed && (checkForClose || pos==endPos);
1063 ok=true;
1064 if (closeDelayed && !needCloseParenthesis && wh!=0x3c)
1065 needCloseParenthesis=wh>=numOperators || listOperators[wh].m_arity!=2;
1066 while (needCloseParenthesis && closeDelayed>0)
1067 {
1068 auto len=stack.size();
1069 if (len<2)
1070 {
1071 error="##closedParenthesis,";
1072 ok=false;
1073 break;
1074 }
1075 auto &dParenthesisFunc=stack[len-2];
1076 if (dParenthesisFunc.size()!=1 || dParenthesisFunc[0].m_type!=dParenthesisFunc[0].F_Operator ||
1077 dParenthesisFunc[0].m_content!="(")
1078 {
1079 error="##closedParenthesis,";
1080 ok=false;
1081 break;
1082 }
1083 dParenthesisFunc.insert(dParenthesisFunc.end(),stack.back().begin(), stack.back().end());
1084 WKSContentListener::FormulaInstruction instr;
1085 instr.m_type=instr.F_Operator;
1086 instr.m_content=")";
1087 dParenthesisFunc.push_back(instr);
1088 stack.resize(len-1);
1089 --closeDelayed;
1090 }
1091 if (!ok || pos==endPos)
1092 break;
1093 int arity=0;
1094 WKSContentListener::FormulaInstruction instr;
1095 ok=false;
1096 bool noneInstr=false, closeFunction=false;
1097 switch (wh)
1098 {
1099 case 0:
1100 {
1101 if (pos+3>endPos)
1102 break;
1103 ok=readLink(int(libwps::readU16(input)), instr);
1104 break;
1105 }
1106 case 0x12:
1107 {
1108 if (pos+2>endPos)
1109 break;
1110 ok=true;
1111 instr.m_type=instr.F_Function;
1112 int id=int(libwps::readU8(input));
1113 if (id<numFunctions && listFunctions[id])
1114 instr.m_content=listFunctions[id];
1115 else
1116 {
1117 std::stringstream s;
1118 s << "Funct" << std::hex << id << std::dec;
1119 instr.m_content=s.str();
1120 }
1121 std::vector<WKSContentListener::FormulaInstruction> child;
1122 child.push_back(instr);
1123 stack.push_back(child);
1124 instr.m_type=instr.F_Operator;
1125 instr.m_content="(";
1126 break;
1127 }
1128 case 0x67:
1129 case 0x87:
1130 case 0xc7:
1131 closeFunction=ok=true;
1132 break;
1133 case 0x1c: // use before %
1134 case 0x1e: // use for <> A 1e B "code <>"
1135 case 0x34: // use for <=,>= ... A 34 B "code <=,..."
1136 case 0x36: // use before -unary
1137 case 0x38: // use before +unary
1138 noneInstr=ok=true;
1139 break;
1140 case 0x3a:
1141 ok=true;
1142 instr.m_type=instr.F_Operator;
1143 instr.m_content=";";
1144 break;
1145 case 0x3c:
1146 noneInstr=ok=true;
1147 ++closeDelayed;
1148 break;
1149 case 0x3e:
1150 ok=true;
1151 instr.m_type=instr.F_Operator;
1152 instr.m_content="(";
1153 break;
1154 case 0x56:
1155 {
1156 int dSz=int(libwps::readU8(input));
1157 if (pos+2+dSz>endPos)
1158 break;
1159 instr.m_type=instr.F_Text;
1160 instr.m_content=libwps_tools_win::Font::unicodeString(input.get(), unsigned(dSz), m_state->getDefaultFontType()).cstr();
1161 ok=true;
1162 break;
1163 }
1164 case 0x2d:
1165 case 0xed: // example C2
1166 if (pos+5>endPos)
1167 break;
1168 WPS_DEBUG_MSG(("MultiplanParser::readFormula: find column/row solitary definition\n"));
1169 error="###RorC";
1170 ok=false;
1171 break;
1172 case 0xe1: // example C2 R1
1173 WPS_DEBUG_MSG(("MultiplanParser::readFormula: find union operator\n"));
1174 error="###union";
1175 ok=false;
1176 break;
1177 case 0x37: // use for list cell
1178 case 0x53:
1179 case 0x73:
1180 case 0x93: // basic cell
1181 case 0xf3:
1182 {
1183 if (pos+3>endPos)
1184 break;
1185 instr.m_type=instr.F_Cell;
1186 instr.m_positionRelative[0]=Vec2b(true,true);
1187 int val=int(libwps::readU16(input));
1188 auto &newPos=instr.m_position[0];
1189 if (val&0x8000)
1190 newPos[1]=cellPos[1]-(val&0xff);
1191 else
1192 newPos[1]=cellPos[1]+(val&0xff);
1193 if (val&0x4000)
1194 newPos[0]=cellPos[0]-((val>>8)&0x3f);
1195 else
1196 newPos[0]=cellPos[0]+((val>>8)&0x3f);
1197 ok=newPos[0]>=0 && newPos[1]>=0;
1198 break;
1199 }
1200 case 0x94:
1201 if (pos+9>endPos || !readDouble(instr.m_doubleValue))
1202 break;
1203 instr.m_type=instr.F_Double;
1204 ok=true;
1205 break;
1206 case 0x35:
1207 case 0x8f:
1208 case 0xef:
1209 if (pos+3>endPos)
1210 break;
1211 instr.m_type=instr.F_Cell;
1212 instr.m_positionRelative[0]=Vec2b(false,false);
1213 instr.m_position[0][1]=int(libwps::readU8(input));
1214 instr.m_position[0][0]=int(libwps::readU8(input));
1215 ok=(instr.m_position[0][0]<63) && (instr.m_position[0][1]<255);
1216 if (!ok)
1217 {
1218 error="###RorC";
1219 WPS_DEBUG_MSG(("MultiplanParser::readFormula: find only row/column reference\n"));
1220 }
1221 break;
1222 case 0xeb:
1223 if (pos+3>endPos || !readName(int(libwps::readU16(input)), instr))
1224 break;
1225 ok=true;
1226 break;
1227 default:
1228 if (wh<numOperators && listOperators[wh].m_arity!=-2)
1229 {
1230 instr.m_content=listOperators[wh].m_name;
1231 instr.m_type=instr.F_Function;
1232 arity=listOperators[wh].m_arity;
1233 }
1234 if (instr.m_content.empty())
1235 {
1236 WPS_DEBUG_MSG(("MultiplanParser::readFormula: find unknown type %x\n", wh));
1237 std::stringstream s;
1238 s << "##unkn[func]=" << std::hex << wh << std::dec << ",";
1239 error=s.str();
1240 break;
1241 }
1242 ok=true;
1243 break;
1244 }
1245 if (!ok)
1246 {
1247 input->seek(pos, librevenge::RVNG_SEEK_SET);
1248 break;
1249 }
1250 checkForClose=!noneInstr && closeDelayed>0;
1251 if (noneInstr) continue;
1252 if (closeFunction)
1253 {
1254 ok=false;
1255 if (stack.empty())
1256 {
1257 error="##closed,";
1258 break;
1259 }
1260 auto it=stack.end();
1261 --it;
1262 for (; it!=stack.begin(); --it)
1263 {
1264 if (it->size()!=1) continue;
1265 auto const &dInstr=(*it)[0];
1266 if (dInstr.m_type!=dInstr.F_Operator || dInstr.m_content!="(") continue;
1267 auto fIt=it;
1268 --fIt;
1269 auto &functionStack=*fIt;
1270 if (functionStack.size()!=1 || functionStack[0].m_type!=functionStack[0].F_Function) continue;
1271 ok=true;
1272 for (; it!=stack.end(); ++it)
1273 functionStack.insert(functionStack.end(), it->begin(), it->end());
1274 ++fIt;
1275 stack.erase(fIt, stack.end());
1276 break;
1277 }
1278 if (!ok)
1279 {
1280 error="##closed";
1281 break;
1282 }
1283 instr.m_type=instr.F_Operator;
1284 instr.m_content=")";
1285 stack.back().push_back(instr);
1286 continue;
1287 }
1288 if (instr.m_type!=WKSContentListener::FormulaInstruction::F_Function)
1289 {
1290 std::vector<WKSContentListener::FormulaInstruction> child;
1291 child.push_back(instr);
1292 stack.push_back(child);
1293 continue;
1294 }
1295 size_t numElt = stack.size();
1296 if (static_cast<int>(numElt) < arity)
1297 {
1298 std::stringstream s;
1299 s << instr.m_content << "[##" << arity << "]";
1300 error=s.str();
1301 input->seek(pos, librevenge::RVNG_SEEK_SET);
1302 ok=false;
1303 break;
1304 }
1305 if (arity==1)
1306 {
1307 instr.m_type=WKSContentListener::FormulaInstruction::F_Operator;
1308 if (instr.m_content=="%")
1309 stack[numElt-1].push_back(instr);
1310 else
1311 stack[numElt-1].insert(stack[numElt-1].begin(), instr);
1312 continue;
1313 }
1314 if (arity==2)
1315 {
1316 instr.m_type=WKSContentListener::FormulaInstruction::F_Operator;
1317 stack[numElt-2].push_back(instr);
1318 stack[numElt-2].insert(stack[numElt-2].end(), stack[numElt-1].begin(), stack[numElt-1].end());
1319 stack.resize(numElt-1);
1320 continue;
1321 }
1322 ok=false;
1323 error = "### unexpected arity";
1324 input->seek(pos, librevenge::RVNG_SEEK_SET);
1325 break;
1326 }
1327 long pos=input->tell();
1328 if (pos!=endPos || !ok || closeDelayed || stack.size()!=1 || stack[0].empty())
1329 {
1330 WPS_DEBUG_MSG(("MultiplanParser::readFormula: can not read a formula\n"));
1331 ascii().addDelimiter(pos, '|');
1332 input->seek(endPos, librevenge::RVNG_SEEK_SET);
1333
1334 std::stringstream s;
1335 if (!error.empty())
1336 s << error;
1337 else
1338 s << "##unknownError";
1339 s << "[";
1340 for (auto const &i : stack)
1341 {
1342 for (auto const &j : i)
1343 s << j << ",";
1344 }
1345 s << "],";
1346 error=s.str();
1347 return true;
1348 }
1349 formula=stack[0];
1350 return true;
1351 }
1352
1353 namespace MultiplanParserInternal
1354 {
1355 static Functions const s_listOperatorsV2[] =
1356 {
1357 // 0
1358 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1359 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1360 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1361 { "", -2}, { "-", 1}, { "+", 1}, { "%", 1},
1362 // 1
1363 { "", -2}, { "+", 2}, { "-", 2}, { "*", 2},
1364 { "/", 2}, { "^", 2}, { "<", 2}, { ">", 2},
1365 { "<=", 2}, { ">=", 2}, { "=", 2}, { "<>", 2},
1366 { "&", 2}, { "", -2}, { "", -2}, { "", -2},
1367 // 2
1368 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1369 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1370 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1371 { "", -2}, { "", -2}, { "", -2}, { "", -2},
1372 };
1373
1374 static char const *s_listFunctionsV2[]=
1375 {
1376 // 0
1377 nullptr /* special Row */, nullptr/* special Column*/, nullptr/* checkme: unknown*/, nullptr/* checkme: unknown*/,
1378 nullptr /* special Index */, nullptr/* special LookUp*/, "Count", "If",
1379 "IsNa", "IsError", "Sum", "Average",
1380 "Min", "Max", "NA", "NPV",
1381 // 1
1382 "StDev", "Dollar", "Fixed", "Sin",
1383 "Cos", "Tan", "Atan", "Pi",
1384 "Sqrt", "Exp", "Ln", "Log10",
1385 "Abs", "Int", "Sign", "Round",
1386 // 2
1387 "Rept", "Mid", "Len", "Value",
1388 "True", "False", "And", "Or",
1389 "Not", "Mod", "PV", "NV",
1390 "NPER", "PMT", "Rate", "Mirr",
1391 // 3
1392 "Irr", nullptr /* special Now */, nullptr /* checkme: unknown */, "Date",
1393 "Time", "Day", "Month", "WeekDay",
1394 "Year", "Hour", "Minute", "Second",
1395 nullptr, nullptr, nullptr, nullptr,
1396 };
1397 }
1398
1399 bool MultiplanParser::readFormulaV2(Vec2i const &cellPos, std::vector<WKSContentListener::FormulaInstruction> &formula, long endZonePos, std::string &error)
1400 {
1401 formula.clear();
1402 auto input = getInput();
1403 long pos=input->tell();
1404 int dSz=int(libwps::readU8(input));
1405 long endPos=pos+2*dSz;
1406 if (dSz==0 || endPos>endZonePos)
1407 {
1408 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: the zone seems bad\n"));
1409 return false;
1410 }
1411 if (endZonePos!=endPos)
1412 ascii().addDelimiter(endPos, '|');
1413 long dataPos=-1;
1414 long dataSize=0;
1415 if (endZonePos>endPos+2)
1416 {
1417 input->seek(endPos+1, librevenge::RVNG_SEEK_SET);
1418 dSz=int(libwps::readU8(input));
1419 if (dSz && endPos+2+2*dSz<=endZonePos)
1420 {
1421 dataSize=dSz;
1422 dataPos=endPos+2;
1423 }
1424 }
1425 std::vector<std::vector<WKSContentListener::FormulaInstruction> > stack;
1426 auto const &listOperators=MultiplanParserInternal::s_listOperatorsV2;
1427 int const numOperators=int(WPS_N_ELEMENTS(MultiplanParserInternal::s_listOperatorsV2));
1428 auto const &listFunctions=MultiplanParserInternal::s_listFunctionsV2;
1429 int const numFunctions=int(WPS_N_ELEMENTS(MultiplanParserInternal::s_listFunctionsV2));
1430 bool ok=true;
1431 input->seek(pos+1, librevenge::RVNG_SEEK_SET);
1432 while (input->tell()<endPos)
1433 {
1434 pos=input->tell();
1435 int code=int(libwps::readU8(input));
1436 if (code==0) break;
1437 WKSContentListener::FormulaInstruction instr;
1438 ok=false;
1439 int arity=0, cellId=-1;
1440 bool noneInstr=false;
1441 switch (code)
1442 {
1443 case 1:
1444 {
1445 if (pos+1>endPos)
1446 break;
1447 dSz=int(libwps::readU8(input));
1448 if (dSz==0 || pos+1+dSz>endPos)
1449 break;
1450 double mantisse = 0;
1451 for (int i = 0; i < dSz-2; i++)
1452 mantisse = mantisse/256 + double(readU8(input));
1453 auto mantExp = dSz>=2 ? int(readU8(input)) : 0;
1454 mantisse = (mantisse/256 + double(0x10+(mantExp & 0x0F)))/16;
1455 int exp = ((mantExp&0xF0)>>4)+int(readU8(input)<<4);
1456 int sign = 1;
1457 if (exp & 0x800)
1458 {
1459 exp &= 0x7ff;
1460 sign = -1;
1461 }
1462 exp -= 0x3ff;
1463 instr.m_type=instr.F_Double;
1464 instr.m_doubleValue = sign * std::ldexp(mantisse, exp);
1465 ok=true;
1466 break;
1467 }
1468 case 2:
1469 {
1470 if (pos+1>endPos)
1471 break;
1472 dSz=int(libwps::readU8(input));
1473 if (pos+1+dSz>endPos)
1474 break;
1475 instr.m_type=instr.F_Text;
1476 instr.m_content=libwps_tools_win::Font::unicodeString(input.get(), unsigned(dSz), m_state->getDefaultFontType()).cstr();
1477 ok=true;
1478 break;
1479 }
1480 case 0x4: // cell in function
1481 case 0x6: // cell in basic formula
1482 if (pos+2>endPos)
1483 break;
1484 cellId=libwps::readU8(input);
1485 break;
1486 case 0x7: // function without argument
1487 case 0x8: // function with argument
1488 case 0x9: // special
1489 case 0xa: // special with arg
1490 {
1491 if (pos+2>endPos)
1492 break;
1493 instr.m_type=instr.F_Function;
1494 int id=int(libwps::readU8(input));
1495 if (code==9 || code==0xa)
1496 {
1497 int fId=-1;
1498 if (id+1<=dataSize)
1499 {
1500 input->seek(dataPos+2*id, librevenge::RVNG_SEEK_SET);
1501 int val=int(libwps::readU8(input));
1502 if (val==6) fId=int(libwps::readU8(input));
1503 input->seek(pos+2, librevenge::RVNG_SEEK_SET);
1504 }
1505 char const *wh[]= { "Row", "Column", nullptr, nullptr, "Index", "LookUp" };
1506 if (fId>=0 && fId<int(WPS_N_ELEMENTS(wh)) && wh[fId])
1507 instr.m_content=wh[fId];
1508 else if (fId==0x31)
1509 instr.m_content="Now";
1510 else
1511 {
1512 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: can not find a function id\n"));
1513 error += "###fId";
1514 std::stringstream s;
1515 s << "FunctId" << fId;
1516 instr.m_content=s.str();
1517 }
1518 }
1519 else if (id<numFunctions && listFunctions[id])
1520 instr.m_content=listFunctions[id];
1521 else
1522 {
1523 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: can not find a function %d\n", id));
1524 error += "###fId";
1525 }
1526 if (instr.m_content.empty())
1527 {
1528 std::stringstream s;
1529 s << "Funct" << std::hex << id << std::dec;
1530 instr.m_content=s.str();
1531 }
1532 std::vector<WKSContentListener::FormulaInstruction> child;
1533 child.push_back(instr);
1534 instr.m_type=instr.F_Operator;
1535 instr.m_content="(";
1536 if ((code%2)==0)
1537 {
1538 stack.push_back(child);
1539 ok=true;
1540 break;
1541 }
1542 child.push_back(instr);
1543 instr.m_content=")";
1544 child.push_back(instr);
1545 stack.push_back(child);
1546 ok=noneInstr=true;
1547 break;
1548 }
1549 case 0xb: // close 0x8: 1 arg
1550 case 0xc: // close 0x8: >=2 arg
1551 {
1552 if (code==0xc) // ignore the num arg
1553 {
1554 if (pos+2>endPos)
1555 break;
1556 input->seek(1, librevenge::RVNG_SEEK_CUR);
1557 }
1558 if (stack.empty())
1559 {
1560 error="##closed,";
1561 break;
1562 }
1563 auto it=stack.end();
1564 --it;
1565 for (; it!=stack.begin(); --it)
1566 {
1567 if (it->size()!=1) continue;
1568 auto const &dInstr=(*it)[0];
1569 if (dInstr.m_type!=dInstr.F_Operator || dInstr.m_content!="(") continue;
1570 auto fIt=it;
1571 --fIt;
1572 auto &functionStack=*fIt;
1573 if (functionStack.size()!=1 || functionStack[0].m_type!=functionStack[0].F_Function) continue;
1574 ok=true;
1575 for (; it!=stack.end(); ++it)
1576 functionStack.insert(functionStack.end(), it->begin(), it->end());
1577 ++fIt;
1578 stack.erase(fIt, stack.end());
1579 break;
1580 }
1581 if (!ok)
1582 {
1583 error="##closed";
1584 break;
1585 }
1586 instr.m_type=instr.F_Operator;
1587 instr.m_content=")";
1588 stack.back().push_back(instr);
1589 noneInstr=true;
1590 break;
1591 }
1592 case 0x21:
1593 instr.m_type=instr.F_Operator;
1594 instr.m_content=";";
1595 ok=true;
1596 break;
1597 case 0x22:
1598 ok=true;
1599 arity=1;
1600 instr.m_type=instr.F_Function;
1601 instr.m_content=")";
1602 break;
1603 case 3: // begin of parenthesis
1604 case 0x23: // associate with -
1605 case 0x24: // associate with +
1606 case 0x25:
1607 case 0x26:
1608 noneInstr=ok=true;
1609 break;
1610 case 0x28:
1611 if (pos+3>endPos)
1612 break;
1613 ok=readLink(int(libwps::readU16(input)), instr);
1614 break;
1615 default:
1616 {
1617 if (code<numOperators && listOperators[code].m_arity!=-2)
1618 {
1619 instr.m_content=listOperators[code].m_name;
1620 instr.m_type=instr.F_Function;
1621 arity=listOperators[code].m_arity;
1622 }
1623 if (!instr.m_content.empty())
1624 {
1625 ok=true;
1626 break;
1627 }
1628 if (code>=0x80)
1629 {
1630 cellId=code-0x80;
1631 break;
1632 }
1633 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: find unknown type %x\n", code));
1634 std::stringstream s;
1635 s << "##unkn[func]=" << std::hex << code << std::dec << ",";
1636 error=s.str();
1637 break;
1638 }
1639 }
1640 if (!ok && cellId>=0 && cellId+2<=dataSize)
1641 {
1642 long actPos=input->tell();
1643 input->seek(dataPos+2*cellId, librevenge::RVNG_SEEK_SET);
1644 int headerVal=int(libwps::readU8(input));
1645 int numCell=(headerVal&5)==5 ? 2 : 1;
1646 if (numCell==2 && actPos+6>=endPos)
1647 {
1648 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: oops can not reserve extra space\n"));
1649 error="###extraSz,";
1650 }
1651 else
1652 {
1653 if (numCell==2)
1654 endPos-=6;
1655 int actCellId=2*cellId+1;
1656 if (numCell==2) // small number maybe rel/abs
1657 {
1658 input->seek(1, librevenge::RVNG_SEEK_CUR);
1659 ++actCellId;
1660 }
1661 instr.m_type=numCell==1 ? instr.F_Cell : instr.F_CellList;
1662 for (int c=0; c<numCell; ++c)
1663 {
1664 int val=headerVal;
1665 if (numCell==2)
1666 {
1667 val=int(libwps::readU8(input));
1668 ++actCellId;
1669 }
1670 if ((val&3)==1 || (val&3)==2) // 1: row, 2:col
1671 {
1672 error="##RorC";
1673 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: find only row/column reference\n"));
1674 break;
1675 }
1676 if (val&4)
1677 {
1678 if (actCellId+3>2*dataSize) break;
1679 input->seek(1, librevenge::RVNG_SEEK_CUR);
1680 WKSContentListener::FormulaInstruction nameInstr;
1681 if (!readName(int(libwps::readU16(input)), nameInstr))
1682 break;
1683 if (nameInstr.m_type==nameInstr.F_Text)
1684 instr=nameInstr;
1685 else
1686 {
1687 for (int d=0; d+c<2; ++d)
1688 {
1689 if (d==1)
1690 {
1691 if (nameInstr.m_type!=nameInstr.F_CellList || numCell==2)
1692 break;
1693 instr.m_type=instr.F_CellList;
1694 }
1695 instr.m_position[c+d]=nameInstr.m_position[d];
1696 instr.m_positionRelative[c+d]=nameInstr.m_positionRelative[d];
1697 }
1698 }
1699 ok=c+1==numCell;
1700 continue;
1701 }
1702 if (actCellId+3>2*dataSize) break;
1703 int col=int(libwps::readU8(input));
1704 val=int(libwps::readU16(input));
1705 if (val&0x4000)
1706 {
1707 if (val&0x1000)
1708 instr.m_position[c][0]=cellPos[0]-col;
1709 else
1710 instr.m_position[c][0]=cellPos[0]+col;
1711 instr.m_positionRelative[c][0]=true;
1712 }
1713 else
1714 {
1715 instr.m_position[c][0]=col;
1716 instr.m_positionRelative[c][0]=false;
1717 }
1718 int row=val&0xfff;
1719 if (val&0x8000)
1720 {
1721 if (val&0x2000)
1722 instr.m_position[c][1]=cellPos[1]-row;
1723 else
1724 instr.m_position[c][1]=cellPos[1]+row;
1725 instr.m_positionRelative[c][1]=true;
1726 }
1727 else
1728 {
1729 instr.m_position[c][1]=row;
1730 instr.m_positionRelative[c][1]=false;
1731 }
1732 if (instr.m_position[c][0]<0 || instr.m_position[c][0]>=255 ||
1733 instr.m_position[c][1]<0 || instr.m_position[c][1]>=4095)
1734 break;
1735 ok=c+1==numCell;
1736 }
1737 }
1738 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1739 if (!ok)
1740 {
1741 WPS_DEBUG_MSG(("MultiplanParser::readFormulaV2: can not find a cell id[%d]\n", cellId));
1742 std::stringstream s;
1743 s << "###cell" << std::hex << code << std::dec;
1744 error+=s.str();
1745 break;
1746 }
1747 }
1748 if (!ok)
1749 {
1750 input->seek(pos,librevenge::RVNG_SEEK_SET);
1751 break;
1752 }
1753 if (noneInstr) continue;
1754 if (instr.m_type!=WKSContentListener::FormulaInstruction::F_Function)
1755 {
1756 std::vector<WKSContentListener::FormulaInstruction> child;
1757 child.push_back(instr);
1758 stack.push_back(child);
1759 continue;
1760 }
1761 size_t numElt = stack.size();
1762 if (static_cast<int>(numElt) < arity)
1763 {
1764 std::stringstream s;
1765 s << instr.m_content << "[##" << arity << "]";
1766 error=s.str();
1767 input->seek(pos, librevenge::RVNG_SEEK_SET);
1768 ok=false;
1769 break;
1770 }
1771 if (arity==1)
1772 {
1773 instr.m_type=WKSContentListener::FormulaInstruction::F_Operator;
1774 if (instr.m_content=="%")
1775 stack[numElt-1].push_back(instr);
1776 else if (instr.m_content==")")
1777 {
1778 stack[numElt-1].push_back(instr);
1779 instr.m_content="(";
1780 stack[numElt-1].insert(stack[numElt-1].begin(), instr);
1781 }
1782 else
1783 stack[numElt-1].insert(stack[numElt-1].begin(), instr);
1784 continue;
1785 }
1786 if (arity==2)
1787 {
1788 instr.m_type=WKSContentListener::FormulaInstruction::F_Operator;
1789 stack[numElt-2].push_back(instr);
1790 stack[numElt-2].insert(stack[numElt-2].end(), stack[numElt-1].begin(), stack[numElt-1].end());
1791 stack.resize(numElt-1);
1792 continue;
1793 }
1794 ok=false;
1795 error = "### unexpected arity";
1796 input->seek(pos, librevenge::RVNG_SEEK_SET);
1797 break;
1798 }
1799 pos=input->tell();
1800 if (pos!=endPos || !ok || stack.size()!=1 || stack[0].empty())
1801 {
1802 WPS_DEBUG_MSG(("MultiplanParser::readFormula: can not read a formula\n"));
1803 ascii().addDelimiter(pos, '|');
1804 input->seek(endPos, librevenge::RVNG_SEEK_SET);
1805
1806 std::stringstream s;
1807 if (!error.empty())
1808 s << error;
1809 else
1810 s << "##unknownError";
1811 s << "[";
1812 for (auto const &i : stack)
1813 {
1814 for (auto const &j : i)
1815 s << j << ",";
1816 }
1817 s << "],";
1818 error=s.str();
1819 return true;
1820 }
1821 formula=stack[0];
1822 return true;
1823 }
1824 ////////////////////////////////////////////////////////////
1825 // generic
1826 ////////////////////////////////////////////////////////////
1827 bool MultiplanParser::readCellDataPosition(WPSEntry const &entry)
1828 {
1829 if (m_state->m_maximumCell[0]<=0 || m_state->m_maximumCell[1]<=0 ||
1830 entry.length()/2/m_state->m_maximumCell[0]<m_state->m_maximumCell[1])
1831 {
1832 WPS_DEBUG_MSG(("MultiplanParser::readCellDataPosition: the zone seems bad\n"));
1833 return false;
1834 }
1835 auto input = getInput();
1836 input->seek(entry.begin(), librevenge::RVNG_SEEK_SET);
1837 libwps::DebugStream f;
1838 f << "Entries(CellPos):";
1839 auto &posSet=m_state->m_zonesList[0].m_positionsSet;
1840 for (int i=0; i<m_state->m_maximumCell[0]; ++i)
1841 {
1842 f << "[" << std::hex;
1843 bool hasValues=false;
1844 std::vector<int> cellPos;
1845 for (int j=0; j<m_state->m_maximumCell[1]; ++j)
1846 {
1847 cellPos.push_back(int(libwps::readU16(input)));
1848 posSet.insert(cellPos.back());
1849 if (cellPos.back())
1850 {
1851 hasValues=true;
1852 f << cellPos.back() << ",";
1853 }
1854 else
1855 f << "_,";
1856 }
1857 f << std::dec << "],";
1858 if (hasValues)
1859 m_state->m_cellPositionsMap[i]=cellPos;
1860 }
1861 if (input->tell()!=entry.end())
1862 {
1863 WPS_DEBUG_MSG(("MultiplanParser::readCellDataPosition: find extra data\n"));
1864 f << "###extra";
1865 ascii().addDelimiter(input->tell(),'|');
1866 }
1867 ascii().addPos(entry.begin());
1868 ascii().addNote(f.str().c_str());
1869 return true;
1870 }
1871
1872 bool MultiplanParser::readLink(int pos, WKSContentListener::FormulaInstruction &instruction)
1873 {
1874 auto it=m_state->m_posToLinkMap.find(pos);
1875 if (it!=m_state->m_posToLinkMap.end())
1876 {
1877 instruction=it->second;
1878 return true;
1879 }
1880 int const vers=version();
1881 auto const &entry=m_state->m_entries[MultiplanParserInternal::Zone::Link];
1882 if (!entry.valid() || pos<0 || pos+9>entry.length())
1883 {
1884 WPS_DEBUG_MSG(("MultiplanParser::readLink: the pos %d seems bad\n", pos));
1885 return false;
1886 }
1887 auto input = getInput();
1888 long actPos=input->tell();
1889 long begPos=entry.begin()+pos;
1890 input->seek(begPos, librevenge::RVNG_SEEK_SET);
1891 libwps::DebugStream f;
1892 f << "Link-" << std::hex << pos << std::dec << "[pos]:";
1893 int val=libwps::readU16(input);
1894 int dSz=(val&0x1f);
1895 int type=(val>>5);
1896 if ((val>>5)!=2) f << "type=" << (val>>5) << ",";
1897 val=libwps::readU16(input);
1898 librevenge::RVNGString filename;
1899 if (pos+(vers==1 ? 8 : 10)+dSz>entry.length() || !readFilename(val, filename))
1900 {
1901 WPS_DEBUG_MSG(("MultiplanParser::readLink: the pos %d seems bad\n", pos));
1902 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1903 return false;
1904 }
1905 int rows[2];
1906 for (auto &r : rows) r=vers==1 ? int(libwps::readU8(input)) : int(libwps::readU16(input));
1907 int cols[2];
1908 for (auto &c : cols) c=int(libwps::readU8(input));
1909 if (rows[0]==rows[1] && cols[0]==cols[1]) // used position?
1910 f << "pos=" << Vec2i(cols[0],rows[0]) << ",";
1911 else
1912 f << "pos=" << WPSBox2i(Vec2i(cols[0],rows[0]),Vec2i(cols[1],rows[1])) << ",";
1913 bool ok=true;
1914 switch (type)
1915 {
1916 case 2: // file + cell's name
1917 // we can not a named reference to a link, so store the reference in a text zone
1918 filename.append(':');
1919 filename.append(libwps_tools_win::Font::unicodeString(input.get(), unsigned(dSz), m_state->getDefaultFontType()));
1920 instruction.m_type=instruction.F_Text;
1921 instruction.m_content=filename.cstr();
1922 break;
1923 case 3: // file + cell's reference
1924 if ((vers==1 && dSz!=4) || (vers>1 && dSz!=6))
1925 {
1926 WPS_DEBUG_MSG(("MultiplanParser::readLink: unexpected size\n"));
1927 f << "##";
1928 ok=false;
1929 break;
1930 }
1931 instruction.m_fileName=filename;
1932 instruction.m_sheetName[0]=instruction.m_sheetName[1]="Sheet0";
1933 for (auto &r : rows) r=vers==1 ? int(libwps::readU8(input)) : int(libwps::readU16(input));
1934 for (auto &c : cols) c=int(libwps::readU8(input));
1935 for (int i=0; i<2; ++i)
1936 {
1937 instruction.m_position[i]=Vec2i(cols[i], rows[i]);
1938 instruction.m_positionRelative[i]=Vec2b(false,false);
1939 }
1940 instruction.m_type=instruction.m_position[0]==instruction.m_position[1] ? instruction.F_Cell : instruction.F_CellList;
1941 f << instruction << ",";
1942 break;
1943 default:
1944 WPS_DEBUG_MSG(("MultiplanParser::readFilename: unknown type\n"));
1945 f << "##";
1946 ok=false;
1947 break;
1948 }
1949 if (ok)
1950 m_state->m_posToLinkMap[pos]=instruction;
1951 ascii().addPos(begPos);
1952 ascii().addNote(f.str().c_str());
1953 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1954 return true;
1955 }
1956
1957 bool MultiplanParser::readFilename(int pos, librevenge::RVNGString &filename)
1958 {
1959 filename.clear();
1960 auto const &entry=m_state->m_entries[MultiplanParserInternal::Zone::FileName];
1961 if (!entry.valid() || pos<0 || pos+3>entry.length())
1962 {
1963 WPS_DEBUG_MSG(("MultiplanParser::readFilename: the pos %d seems bad\n", pos));
1964 return false;
1965 }
1966 auto input = getInput();
1967 long actPos=input->tell();
1968 long begPos=entry.begin()+pos;
1969 input->seek(begPos, librevenge::RVNG_SEEK_SET);
1970 libwps::DebugStream f;
1971 f << "FileName-" << std::hex << pos << std::dec << ":";
1972 int val=libwps::readU16(input);
1973 int dSz=(val&0x1f);
1974 if (pos+2+dSz>entry.length())
1975 {
1976 WPS_DEBUG_MSG(("MultiplanParser::readFilename: the pos %d seems bad\n", pos));
1977 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1978 return false;
1979 }
1980 if (val>>5) f << "f0=" << (val>>5) << ",";
1981 filename=libwps_tools_win::Font::unicodeString(input.get(), unsigned(dSz), m_state->getDefaultFontType());
1982 ascii().addDelimiter(input->tell(),'|');
1983 ascii().addPos(begPos);
1984 ascii().addNote(f.str().c_str());
1985 input->seek(actPos, librevenge::RVNG_SEEK_SET);
1986 return !filename.empty();
1987 }
1988
1989 bool MultiplanParser::readName(int pos, WKSContentListener::FormulaInstruction &instruction)
1990 {
1991 int const vers=version();
1992 auto it=m_state->m_posToNameMap.find(pos);
1993 if (it!=m_state->m_posToNameMap.end())
1994 {
1995 instruction=it->second;
1996 return true;
1997 }
1998 auto const &entry=m_state->m_entries[MultiplanParserInternal::Zone::Name];
1999 if (!entry.valid() || pos<0 || pos+9>=entry.length())
2000 {
2001 WPS_DEBUG_MSG(("MultiplanParser::readName: the pos %d seeems bad\n", pos));
2002 return false;
2003 }
2004 auto input = getInput();
2005 long actPos=input->tell();
2006 long begPos=entry.begin()+pos;
2007 input->seek(begPos, librevenge::RVNG_SEEK_SET);
2008 libwps::DebugStream f;
2009 f << "Names-" << std::hex << pos << std::dec << ":";
2010 int val;
2011 if (vers==1)
2012 {
2013 val=int(libwps::readU16(input));
2014 f << "unkn=" << std::hex << val << std::dec << ",";
2015 }
2016 val=int(libwps::readU8(input));
2017 int dSz=(val&0x1f);
2018 if (dSz<=0 || begPos+8+dSz>entry.end())
2019 {
2020 input->seek(actPos, librevenge::RVNG_SEEK_SET);
2021 WPS_DEBUG_MSG(("MultiplanParser::readName: the pos %d seeems bad\n", pos));
2022 return false;
2023 }
2024 if (val>>5) f << "f0=" << (val>>5) << ",";
2025 val=int(libwps::readU8(input)); // v1: 0|40, v2: 0|4
2026 if (val) f << "f1=" << std::hex << val << std::dec << ",";
2027 int type=6;
2028 if (vers>=2)
2029 {
2030 type=int(libwps::read16(input));
2031 if (type!=6) f << "type=" << type << ",";
2032 f << "unk=[";
2033 for (int i=0; i<2; ++i) // _,_
2034 {
2035 val=int(libwps::read16(input));
2036 if (val)
2037 f << val << ",";
2038 else
2039 f << "_,";
2040 }
2041 f << "],";
2042 }
2043 bool ok=true;
2044 if (type==6)
2045 {
2046 if (input->tell()+(vers==1 ? 4 : 6)+dSz<=entry.end())
2047 {
2048 int rows[2];
2049 for (auto &r : rows) r=vers==1 ? int(libwps::readU8(input)) : int(libwps::readU16(input));
2050 int cols[2];
2051 for (auto &c : cols) c=int(libwps::readU8(input));
2052 for (int i=0; i<2; ++i)
2053 {
2054 instruction.m_position[i]=Vec2i(cols[i], rows[i]);
2055 instruction.m_positionRelative[i]=Vec2b(false,false);
2056 }
2057 instruction.m_type=instruction.m_position[0]==instruction.m_position[1] ? instruction.F_Cell : instruction.F_CellList;
2058 f << instruction << ",";
2059 }
2060 else
2061 {
2062 f << "###";
2063 WPS_DEBUG_MSG(("MultiplanParser::readName: the pos %d seeems bad\n", pos));
2064 }
2065 }
2066 std::string name;
2067 for (int c=0; c<dSz; ++c) name+=char(libwps::readU8(input));
2068 f << name << ",";
2069 switch (type)
2070 {
2071 case 0: // bad name?
2072 instruction.m_type=instruction.F_Text;
2073 instruction.m_content=name;
2074 break;
2075 case 6: // cell list
2076 break;
2077 default:
2078 f << "###";
2079 WPS_DEBUG_MSG(("MultiplanParser::readName: unknown type for pos %d\n", pos));
2080 ok=false;
2081 break;
2082 }
2083 if (ok)
2084 m_state->m_posToNameMap[pos]=instruction;
2085 ascii().addPos(begPos);
2086 ascii().addNote(f.str().c_str());
2087
2088 input->seek(actPos, librevenge::RVNG_SEEK_SET);
2089 return true;
2090 }
2091
2092 bool MultiplanParser::readSharedData(int pos, int cellType, Vec2i const &cellPos, WKSContentListener::CellContent &content)
2093 {
2094 int const vers=version();
2095 auto const &entry=m_state->m_entries[MultiplanParserInternal::Zone::SharedData];
2096 if (!entry.valid() || pos<0 || pos+(vers==1 ? 3 : 4) >entry.length())
2097 {
2098 WPS_DEBUG_MSG(("MultiplanParser::readSharedData: the pos %d seems bad\n", pos));
2099 return false;
2100 }
2101 auto input = getInput();
2102 long actPos=input->tell();
2103 long begPos=entry.begin()+pos;
2104 input->seek(begPos, librevenge::RVNG_SEEK_SET);
2105 libwps::DebugStream f;
2106 f << "SharedData-" << std::hex << pos << std::dec << ":";
2107 int val=int(libwps::readU16(input)), N=val;
2108 int type=0;
2109 if (vers==1)
2110 {
2111 type=(val>>15);
2112 N &= 0x7fff;
2113 }
2114 if (type) f << "type=" << std::hex << type << std::dec << ",";
2115 if (N!=2) f << "used=" << N << ",";
2116 if (vers>=2)
2117 {
2118 // checkme
2119 val=int(libwps::readU8(input));
2120 f << "type=" << std::hex << val << std::dec << ",";
2121 type = (val&4) ? 1 : 0;
2122 }
2123 int dSz=int(libwps::readU8(input));
2124 if (vers>=2) dSz*=2;
2125 long endPos=input->tell()+dSz;
2126 if (endPos>entry.end())
2127 {
2128 WPS_DEBUG_MSG(("MultiplanParser::readSharedData: the pos %d seems bad\n", pos));
2129 input->seek(actPos, librevenge::RVNG_SEEK_SET);
2130 return false;
2131 }
2132 bool ok=true;
2133 switch (type)
2134 {
2135 case 0:
2136 switch (cellType&3)
2137 {
2138 case 0:
2139 {
2140 double value;
2141 if (dSz!=8 || !readDouble(value))
2142 ok=false;
2143 else
2144 {
2145 content.m_contentType=content.C_NUMBER;
2146 content.setValue(value);
2147 f << value << ",";
2148 }
2149 break;
2150 }
2151 case 1:
2152 {
2153 content.m_contentType=content.C_TEXT;
2154 content.m_textEntry.setBegin(input->tell());
2155 content.m_textEntry.setLength(dSz);
2156 std::string name;
2157 for (int c=0; c<dSz; ++c)
2158 {
2159 char ch=char(libwps::readU8(input));
2160 if (vers>=2 && ch==0 && c+1==dSz)
2161 {
2162 content.m_textEntry.setEnd(input->tell()-1);
2163 break;
2164 }
2165 name+=ch;
2166 }
2167 f << name << ",";
2168 break;
2169 }
2170 case 2:
2171 if (dSz!=8)
2172 ok=false;
2173 else
2174 {
2175 f << "Nan" << libwps::readU8(input) << ",";
2176 input->seek(7, librevenge::RVNG_SEEK_CUR);
2177 content.m_contentType=content.C_NUMBER;
2178 content.setValue(std::nan(""));
2179 }
2180 break;
2181 case 3:
2182 default:
2183 if (dSz!=8)
2184 ok=false;
2185 else
2186 {
2187 val=int(libwps::readU8(input));
2188 content.m_contentType=content.C_NUMBER;
2189 content.setValue(val);
2190 if (val==0)
2191 f << "false,";
2192 else if (val==1)
2193 f << "true,";
2194 else
2195 f << "##bool=" << val << ",";
2196 input->seek(7, librevenge::RVNG_SEEK_CUR);
2197 }
2198 break;
2199 }
2200 break;
2201 case 1:
2202 {
2203 std::string err;
2204 if ((vers==1 && !readFormula(cellPos, content.m_formula, endPos, err)) ||
2205 (vers>=2 && !readFormulaV2(cellPos, content.m_formula, endPos, err)))
2206 f << "###";
2207 else
2208 content.m_contentType=content.C_FORMULA;
2209 for (auto const &fo : content.m_formula) f << fo;
2210 f << ",";
2211 f << err;
2212 break;
2213 }
2214 default:
2215 ok=false;
2216 break;
2217 }
2218 if (!ok)
2219 {
2220 WPS_DEBUG_MSG(("MultiplanParser::readSharedData: can not read data for the pos %d\n", pos));
2221 f << "###";
2222 }
2223 if (m_state->m_posToSharedDataSeen.find(pos)==m_state->m_posToSharedDataSeen.end())
2224 {
2225 m_state->m_posToSharedDataSeen.insert(pos);
2226 if (input->tell()!=endPos)
2227 ascii().addDelimiter(input->tell(),'|');
2228 ascii().addPos(begPos);
2229 ascii().addNote(f.str().c_str());
2230 }
2231 input->seek(actPos, librevenge::RVNG_SEEK_SET);
2232 return true;
2233 }
2234 ////////////////////////////////////////////////////////////
2235 // Unknown
2236 ////////////////////////////////////////////////////////////
2237 bool MultiplanParser::readZoneB()
2238 {
2239 auto input = getInput();
2240 long pos = input->tell();
2241 int const vers=version();
2242 long endPos=pos+(vers==1 ? 0x84 : 0xb9);
2243 if (!checkFilePosition(endPos))
2244 {
2245 WPS_DEBUG_MSG(("MultiplanParser::readZoneB: the zone seems too short\n"));
2246 return false;
2247 }
2248 libwps::DebugStream f;
2249 f << "Entries(ZoneB):";
2250 int dim[2];
2251 for (auto &d : dim) d=int(libwps::readU16(input));
2252 m_state->m_maximumCell=Vec2i(dim[0],dim[1]);
2253 f << "cell[max]=" << m_state->m_maximumCell << ",";
2254 int val;
2255 for (int i=0; i<11; ++i)
2256 {
2257 if (i==2 && vers==1) continue;
2258 val=int(libwps::read16(input));
2259 int const expected[]= {0,0,0xfff, 0xff, 0, 0, 5, 6, 0x46, 0x36, 0x42};
2260 if (val!=expected[i])
2261 f << "f" << i << "=" << val << ",";
2262 }
2263 for (int i=0; i<(vers==1 ? 11 : 16); ++i)
2264 {
2265 val=int(libwps::read16(input));
2266 if (!val) continue;
2267 f << "g" << i << "=" << val << ",";
2268 }
2269 if (vers>=2)
2270 {
2271 val=int(libwps::read8(input));
2272 if (val)
2273 f << "h0=" << val << ",";
2274 }
2275 ascii().addPos(pos);
2276 ascii().addNote(f.str().c_str());
2277
2278 pos=input->tell();
2279 f.str("");
2280 f << "ZoneB[II]:";
2281 for (int i=0; i<8; ++i)
2282 {
2283 if ((i==3||i==5) && vers==1) continue;
2284 val=int(libwps::read8(input));
2285 int const expected[]= {1, 0, 0, 0, -2, 0xf, 0, 0x3e};
2286 if (val!=expected[i]) f << "f" << i << "=" << val << ",";
2287 }
2288 for (int i=0; i<(vers==1 ? 40 : 59); ++i) // 0
2289 {
2290 val=int(libwps::read16(input));
2291 if (val) f << "g" << i << "=" << val << ",";
2292 }
2293 if (input->tell()!=endPos)
2294 {
2295 ascii().addDelimiter(input->tell(),'|');
2296 input->seek(endPos, librevenge::RVNG_SEEK_SET);
2297 }
2298 ascii().addPos(pos);
2299 ascii().addNote(f.str().c_str());
2300 return true;
2301 }
2302
2303 ////////////////////////////////////////////////////////////
2304 // send data
2305 ////////////////////////////////////////////////////////////
2306 bool MultiplanParser::sendCell(Vec2i const &cellPos, int p)
2307 {
2308 if (!m_listener)
2309 {
2310 WPS_DEBUG_MSG(("MultiplanParser::sendCell: I can not find the m_listener\n"));
2311 return false;
2312 }
2313 int const vers=version();
2314 int zoneId=(p>>16);
2315 if (zoneId<0 || zoneId>=int(m_state->m_zonesList.size()))
2316 {
2317 WPS_DEBUG_MSG(("MultiplanParser::sendCell: can not find the zone data zone for position %d\n", p));
2318 return false;
2319 }
2320 p&=0xffff;
2321 auto const &zone=m_state->m_zonesList[size_t(zoneId)];
2322 auto const &entry=zone.m_entry;
2323 auto it=zone.m_positionsSet.find(p);
2324 if (it!=zone.m_positionsSet.end()) ++it;
2325 long endPos=it!=zone.m_positionsSet.end() ? entry.begin()+*it : entry.end();
2326 if (p<=0 || p>entry.length())
2327 {
2328 WPS_DEBUG_MSG(("MultiplanParser::sendCell: unexpected position %d\n", p));
2329 return false;
2330 }
2331 libwps::DebugStream f;
2332 f << "CellData[C" << cellPos[0]+1 << "R" << cellPos[1]+1 << "]:";
2333 MultiplanParserInternal::Cell cell;
2334 WKSContentListener::CellContent content;
2335 cell.setPosition(cellPos);
2336 cell.setFont(m_state->getDefaultFont());
2337 long pos=entry.begin()+p;
2338 if (endPos-pos<4)
2339 {
2340 WPS_DEBUG_MSG(("MultiplanParser::sendCell: a cell %d seems to short\n", p));
2341 f << "###";
2342 ascii().addPos(pos);
2343 ascii().addNote(f.str().c_str());
2344 return false;
2345 }
2346 auto input=getInput();
2347 input->seek(pos, librevenge::RVNG_SEEK_SET);
2348 int formSize=int(libwps::readU8(input));
2349 if (vers>=2) formSize*=2;
2350 if (formSize) f << "form[size]=" << std::hex << formSize << std::dec << ",";
2351 int val=int(libwps::readU8(input));
2352 int digits=(val>>4);
2353 if (digits) f << "decimal=" << digits << ",";
2354 int form=(val>>1)&7;
2355 int subFormat=0;
2356 switch (form)
2357 {
2358 case 0: // default
2359 break;
2360 case 1: // cont
2361 subFormat=1;
2362 cell.setDigits(digits);
2363 f << "decimal,";
2364 break;
2365 case 2:
2366 subFormat=2;
2367 cell.setDigits(digits);
2368 f << "scientific,";
2369 break;
2370 case 3:
2371 subFormat=6;
2372 cell.setDigits(digits);
2373 f << "fixed,";
2374 break;
2375 case 4: // generic
2376 break;
2377 case 5:
2378 subFormat=4;
2379 cell.setDigits(digits);
2380 f << "currency,";
2381 break;
2382 case 6: // a bar
2383 f << "bar,";
2384 break;
2385 case 7:
2386 subFormat=3;
2387 cell.setDigits(digits);
2388 f << "percent,";
2389 break;
2390 default:
2391 f << "format=" << form << ",";
2392 break;
2393 }
2394 if (val&1)
2395 {
2396 cell.setProtected(true);
2397 f << "protected,";
2398 }
2399 int dSz=0, extraSize=(vers>=2 && formSize) ? 4 : 0;
2400 if (vers==1)
2401 {
2402 val=int(libwps::readU8(input));
2403 dSz=int(libwps::readU8(input));
2404 }
2405 else
2406 {
2407 dSz=int(libwps::readU8(input));
2408 val=int(libwps::readU8(input));
2409 }
2410 if (endPos<pos+4+dSz+extraSize)
2411 {
2412 WPS_DEBUG_MSG(("MultiplanParser::sendCell: a cell seems to short\n"));
2413 f << "###";
2414 ascii().addPos(pos);
2415 ascii().addNote(f.str().c_str());
2416 return false;
2417 }
2418 int type=(val>>6)&3;
2419 switch (type)
2420 {
2421 case 0:
2422 f << "double,";
2423 cell.setFormat(WPSCell::F_NUMBER, subFormat);
2424 content.m_contentType=content.C_NUMBER;
2425 break;
2426 case 1:
2427 cell.setFormat(WPSCell::F_TEXT);
2428 content.m_contentType=content.C_TEXT;
2429 f << "text,";
2430 break;
2431 case 2:
2432 cell.setFormat(WPSCell::F_NUMBER);
2433 content.m_contentType=content.C_NUMBER;
2434 f << "nan,";
2435 break;
2436 case 3: // or nothing
2437 cell.setFormat(WPSCell::F_BOOLEAN);
2438 content.m_contentType=content.C_NUMBER;
2439 f << "bool,";
2440 break;
2441 default: // impossible
2442 break;
2443 }
2444 int align=(val>>3)&7;
2445 bool hasTimeDate=false;
2446 switch (align)
2447 {
2448 case 1:
2449 cell.setHAlignment(cell.HALIGN_CENTER);
2450 f << "center,";
2451 break;
2452 case 0: // default
2453 case 2: // generic
2454 break;
2455 case 3:
2456 cell.setHAlignment(cell.HALIGN_LEFT);
2457 f << "left,";
2458 break;
2459 case 4:
2460 cell.setHAlignment(cell.HALIGN_RIGHT);
2461 f << "right,";
2462 break;
2463 case 7:
2464 if (vers>=3)
2465 {
2466 f << "timeDate,";
2467 hasTimeDate=true;
2468 break;
2469 }
2470 WPS_FALLTHROUGH;
2471 default:
2472 f << "#align=" << align << ",";
2473 break;
2474 }
2475 bool hasShared=false;
2476 if (val&2)
2477 {
2478 f << "shared,";
2479 hasShared=true;
2480 }
2481 if ((val&4)==0) f << "no[4],";
2482 val &= 0x1;
2483 if (val) f << "f1=" << std::hex << val << std::dec << ",";
2484 if (hasTimeDate && pos+4+dSz+extraSize+4 <= endPos)
2485 {
2486 endPos-=4;
2487 long actPos=input->tell();
2488 input->seek(endPos, librevenge::RVNG_SEEK_SET);
2489 f << "dateTime=[";
2490 val=int(libwps::readU8(input));
2491 if (val!=2) f << "f0=" << val << ",";
2492 val=int(libwps::readU8(input));
2493 switch (val&7)
2494 {
2495 case 1:
2496 cell.setHAlignment(cell.HALIGN_CENTER);
2497 f << "center,";
2498 break;
2499 case 0: // default
2500 case 2: // generic
2501 break;
2502 case 3:
2503 cell.setHAlignment(cell.HALIGN_LEFT);
2504 f << "left,";
2505 break;
2506 case 4:
2507 cell.setHAlignment(cell.HALIGN_RIGHT);
2508 f << "right,";
2509 break;
2510 default:
2511 f << "#align=" << (val&7) << ",";
2512 break;
2513 }
2514 val &=0xf8;
2515 if (val!=0x90) f << "f1=" << std::hex << val << std::dec << ",";
2516 int format=int(libwps::readU16(input));
2517 char const *dtFormat[]=
2518 {
2519 nullptr, "%m/%d/%y", "%m/%d", "%d-%b-%y",
2520 "%d-%b", "%b-%y", "%I:%M%p", "%I:%M:%S%p",
2521 "%H:%M", "%H:%M:%S", "%m/%d/%y %H:%M"
2522 };
2523 switch (format)
2524 {
2525 case 1:
2526 case 2:
2527 case 3:
2528 case 4:
2529 case 5:
2530 case 10:
2531 cell.setDTFormat(WPSCell::F_DATE, dtFormat[format]);
2532 f << dtFormat[format] << ",";
2533 break;
2534 case 6:
2535 case 7:
2536 case 8:
2537 case 9:
2538 cell.setDTFormat(WPSCell::F_TIME, dtFormat[format]);
2539 f << dtFormat[format] << ",";
2540 break;
2541 default:
2542 WPS_DEBUG_MSG(("MultiplanParser::sendCell: unknown data format\n"));
2543 f << "###format=" << format << ",";
2544 }
2545 f << "],";
2546 input->seek(actPos, librevenge::RVNG_SEEK_SET);
2547 }
2548 else if (hasTimeDate)
2549 {
2550 f << "###";
2551 WPS_DEBUG_MSG(("MultiplanParser::sendCell: can not find the time value data\n"));
2552 }
2553 if (vers>=2 && formSize)
2554 {
2555 f << "form=[";
2556 for (int i=0; i<2; ++i) f << libwps::read16(input) << ",";
2557 f << "],";
2558 }
2559 if (type==0 && dSz==8)
2560 {
2561 double value;
2562 if (!readDouble(value))
2563 f << "###";
2564 else
2565 content.setValue(value);
2566 f << value << ",";
2567 }
2568 else if (type==1 && dSz && pos+4+dSz+extraSize+(hasShared ? 2 : 0) <= endPos)
2569 {
2570 content.m_textEntry.setBegin(input->tell());
2571 content.m_textEntry.setLength(dSz);
2572 std::string name;
2573 for (int c=0; c<dSz; ++c) name+=char(libwps::readU8(input));
2574 f << name << ",";
2575 }
2576 else if (type==2 && dSz==8)
2577 {
2578 content.setValue(std::nan(""));
2579 f << "Nan" << int(libwps::readU8(input)) << ",";
2580 input->seek(7, librevenge::RVNG_SEEK_CUR);
2581 }
2582 else if (type==3 && dSz==8)
2583 {
2584 val=int(libwps::readU8(input));
2585 content.setValue(val);
2586 if (val==0)
2587 f << "false,";
2588 else if (val==1)
2589 f << "true,";
2590 else
2591 f << "##bool=" << val << ",";
2592 input->seek(7, librevenge::RVNG_SEEK_CUR);
2593 }
2594 if (hasShared && input->tell()+2<=endPos && (formSize==0 || formSize==2))
2595 {
2596 if ((input->tell()-pos)%2)
2597 input->seek(1, librevenge::RVNG_SEEK_CUR);
2598 int nPos=int(libwps::readU16(input));
2599 if (!readSharedData(nPos, type, cellPos, content))
2600 f << "###";
2601 f << "sharedData-" << std::hex << nPos << std::dec << ",";
2602 }
2603 else if (!hasShared && formSize && input->tell()+formSize<=endPos)
2604 {
2605 auto endFPos=input->tell()+formSize;
2606 std::string err;
2607 if ((vers==1 && !readFormula(cellPos, content.m_formula, endFPos, err)) ||
2608 (vers>=2 && !readFormulaV2(cellPos, content.m_formula, endFPos, err)))
2609 {
2610 ascii().addDelimiter(input->tell(),'|');
2611 f << "###";
2612 }
2613 else
2614 content.m_contentType=content.C_FORMULA;
2615
2616 for (auto const &fo : content.m_formula) f << fo;
2617 f << ",";
2618 f << err;
2619 input->seek(endFPos, librevenge::RVNG_SEEK_SET);
2620 }
2621 else if (formSize)
2622 {
2623 WPS_DEBUG_MSG(("MultiplanParser::sendCell: can not read a formula\n"));
2624 f << "###form";
2625 }
2626 m_listener->openSheetCell(cell, content);
2627 if (content.m_textEntry.valid())
2628 {
2629 auto fontType=m_state->getDefaultFontType();
2630 m_listener->setFont(cell.getFont());
2631 input->seek(content.m_textEntry.begin(), librevenge::RVNG_SEEK_SET);
2632 std::string text;
2633 while (input->tell()<=content.m_textEntry.end())
2634 {
2635 bool last=input->isEnd() || input->tell()>=content.m_textEntry.end();
2636 auto c=last ? '\0' : char(libwps::readU8(input));
2637 if ((c==0 || c==0x9 || c==0xa || c==0xd) && !text.empty())
2638 {
2639 m_listener->insertUnicodeString(libwps_tools_win::Font::unicodeString(text, fontType));
2640 text.clear();
2641 }
2642 if (last) break;
2643 if (c==0x9)
2644 m_listener->insertTab();
2645 else if (c==0xa || c==0xd)
2646 m_listener->insertEOL();
2647 else if (c)
2648 text.push_back(c);
2649 }
2650 }
2651 m_listener->closeSheetCell();
2652 if (vers==1 && input->tell()!=endPos)
2653 ascii().addDelimiter(input->tell(),'|');
2654
2655 ascii().addPos(pos);
2656 ascii().addNote(f.str().c_str());
2657 return true;
2658 }
2659
2660 bool MultiplanParser::sendSpreadsheet()
2661 {
2662 if (!m_listener)
2663 {
2664 WPS_DEBUG_MSG(("MultiplanParser::sendSpreadsheet: I can not find the m_listener\n"));
2665 return false;
2666 }
2667 for (auto &z : m_state->m_zonesList)
2668 z.m_positionsSet.insert(int(z.m_entry.length()));
2669 m_listener->openSheet(m_state->getColumnsWidth(), "Sheet0");
2670 WPSRowFormat rowFormat(16);
2671 rowFormat.m_isMinimalHeight=true;
2672 int lastRow=0;
2673 for (auto const &it : m_state->m_cellPositionsMap)
2674 {
2675 int r=it.first;
2676 auto const &row = it.second;
2677 if (r>lastRow)
2678 {
2679 m_listener->openSheetRow(rowFormat,r-lastRow);
2680 m_listener->closeSheetRow();
2681 }
2682 lastRow=r+1;
2683 m_listener->openSheetRow(rowFormat);
2684 for (size_t col=0; col<row.size(); ++col)
2685 {
2686 int zId=(row[col]>>24);
2687 int p=row[col]&0xffff;
2688 if (zId<0 || zId>=int(m_state->m_zonesList.size()) ||
2689 p<0 || p>=m_state->m_zonesList[size_t(zId)].m_entry.length())
2690 {
2691 WPS_DEBUG_MSG(("MultiplanParser::sendSpreadsheet: find some bad data\n"));
2692 continue;
2693 }
2694 if (!p) continue;
2695 Vec2i cellPos(static_cast<int>(col), static_cast<int>(r));
2696 sendCell(cellPos, row[col]);
2697 }
2698 m_listener->closeSheetRow();
2699 }
2700 m_listener->closeSheet();
2701 return true;
2702 }
2703
2704 ////////////////////////////////////////////////////////////
2705 // password
2706 ////////////////////////////////////////////////////////////
2707 bool MultiplanParser::checkPassword(char const *password) const
2708 {
2709 char const endPassword[]=
2710 {
2711 0x0A, 0x4E, 0x51, 0x6F, 0x6E, 0x61, 0x70, 0x32, 0x33, 0x71, 0x5B,
2712 0x30, 0x23, 0x7A
2713 };
2714 if (!password || !password[0])
2715 {
2716 WPS_DEBUG_MSG(("MultiplanParser::checkPassword: can not find the password\n"));
2717 return false;
2718 }
2719 // set password length to 15 by adding endPassword's data if needed
2720 char pw[16];
2721 int w=0;
2722 while (*password)
2723 {
2724 if (w>=15) break;
2725 pw[w++]=*(password++);
2726 }
2727 for (int r=0; w<15;) pw[w++]=char(endPassword[r++]);
2728 pw[15]=char(0);
2729
2730 // permutate the solution
2731 int const which=(m_state->m_hash&0xf);
2732 if (which!=15) ++pw[which]; // never seem which=15, maybe a special case
2733 int const perm[]= { 9, 4, 1, 3, 14, 11, 6, 0, 12, 7, 2, 10, 8, 13, 5 };
2734 uint8_t res[16];
2735 for (int i=0; i<15; ++i) res[i]=uint8_t(pw[perm[(i+which)%15]]);
2736 res[15]=0;
2737
2738 int len=0;
2739 while (res[len]) ++len;
2740 if (len!=15)
2741 {
2742 WPS_DEBUG_MSG(("MultiplanParser::checkPassword: unexpected size for the password\n"));
2743 return false;
2744 }
2745
2746 // time to check if the checksum is ok or not
2747 int const data[]=
2748 {
2749 0x4ec3, 0xaefc, 0x4dd9, 0x9bb2, 0x2745, 0x4e8a, 0x9d14, 0x2a09,
2750 0x7b61, 0xf6c2, 0xfda5, 0xeb6b, 0xc6f7, 0x9dcf, 0x2bbf, 0x4563,
2751 0x8ac6, 0x05ad, 0x0b5a, 0x16b4, 0x2d68, 0x5ad0, 0x0375, 0x06ea,
2752 0x0dd4, 0x1ba8, 0x3750, 0x6ea0, 0xdd40, 0xd849, 0xa0b3, 0x5147,
2753 0xa28e, 0x553d, 0xaa7a, 0x44d5, 0x6f45, 0xde8a, 0xad35, 0x4a4b,
2754 0x9496, 0x390d, 0x721a, 0xeb23, 0xc667, 0x9cef, 0x29ff, 0x53fe,
2755 0xa7fc, 0x5fd9, 0x47d3, 0x8fa6, 0x0f6d, 0x1eda, 0x3db4, 0x7b68,
2756 0xf6d0, 0xb861, 0x60e3, 0xc1c6, 0x93ad, 0x377b, 0x6ef6, 0xddec,
2757 0x45a0, 0x8b40, 0x06a1, 0x0d42, 0x1a84, 0x3508, 0x6a10, 0xaa51,
2758 0x4483, 0x8906, 0x022d, 0x045a, 0x08b4, 0x1168, 0x76b4, 0xed68,
2759 0xcaf1, 0x85c3, 0x1ba7, 0x374e, 0x6e9c, 0x3730, 0x6e60, 0xdcc0,
2760 0xa9a1, 0x4363, 0x86c6, 0x1dad, 0x3331, 0x6662, 0xccc4, 0x89a9,
2761 0x0373, 0x06e6, 0x0dcc, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231,
2762 0x2462, 0x48c4
2763 };
2764 int const *dataPtr=data;
2765 int val=*(dataPtr++);
2766 for (auto r : res)
2767 {
2768 for (int byte=1, dec=0; dec<7; byte<<=1, ++dec)
2769 {
2770 if (r&byte)
2771 val^=*dataPtr;
2772 dataPtr++;
2773 }
2774 }
2775 if (val!=m_state->m_checksum)
2776 {
2777 WPS_DEBUG_MSG(("MultiplanParser::checkPassword: can not check the password\n"));
2778 return false;
2779 }
2780 // create the decoding keys
2781 res[15]=uint8_t(0xbb);
2782 for (int i=0; i<16; ++i)
2783 {
2784 auto v=res[i]^((i%2)==0 ? (m_state->m_checksum&0xFF) : (m_state->m_checksum>>8));
2785 m_state->m_keys[i]=uint8_t((v>>1)|(v<<7));
2786 }
2787 // original password in 14d6:2220, final keys 14d6:49cb
2788 return true;
2789 }
2790
2791 bool MultiplanParser::retrievePasswordKeys()
2792 {
2793 auto input=getInput();
2794 long actPos=input->tell();
2795 // too short or not the zone0 zone
2796 if (!checkFilePosition(actPos+6) || libwps::readU16(input)!=7)
2797 {
2798 input->seek(actPos,librevenge::RVNG_SEEK_SET);
2799 return false;
2800 }
2801 input->seek(2,librevenge::RVNG_SEEK_CUR);
2802 int dSz=int(libwps::readU16(input));
2803 // not enough data to retrieve the keys final block
2804 if (dSz<22 || !checkFilePosition(actPos+dSz))
2805 {
2806 input->seek(actPos,librevenge::RVNG_SEEK_SET);
2807 return false;
2808 }
2809 uint8_t res[16];
2810 for (int i=0; i<16; ++i)
2811 {
2812 auto key=uint8_t(readU8(input));
2813 if (i==0) key^=8; // first value is normally 8, other 0
2814 auto r=uint8_t((key<<1)|(key>>7));
2815 res[(i+6)&0xf]=uint8_t(r^((i%2)==0 ? (m_state->m_checksum&0xFF) : (m_state->m_checksum>>8)));
2816 }
2817 if (res[15]!=0xbb) // last value must be bb
2818 {
2819 input->seek(actPos,librevenge::RVNG_SEEK_SET);
2820 return false;
2821 }
2822 // inverse the initial permutation
2823 char pw[16];
2824 int const perm[]= { 9, 4, 1, 3, 14, 11, 6, 0, 12, 7, 2, 10, 8, 13, 5 };
2825 int const which=(m_state->m_hash&0xf);
2826 for (int i=0; i<15; ++i) pw[perm[(i+which)%15]]=char(res[i]);
2827 if (which!=15) --pw[which];
2828 pw[15]=0;
2829 std::string password;
2830 for (auto c : pw)
2831 {
2832 if (c==0 || c==0xa) break;
2833 password+=c;
2834 }
2835 bool ok=!password.empty() && checkPassword(password.c_str());
2836 input->seek(actPos,librevenge::RVNG_SEEK_SET);
2837 return ok;
2838 }
2839
2840 RVNGInputStreamPtr MultiplanParser::decodeStream(RVNGInputStreamPtr input)
2841 {
2842 if (!input)
2843 {
2844 WPS_DEBUG_MSG(("MultiplanParser::decodeStream: the arguments seems bad\n"));
2845 return RVNGInputStreamPtr();
2846 }
2847 long actPos=input->tell();
2848 input->seek(0,librevenge::RVNG_SEEK_SET);
2849 librevenge::RVNGBinaryData data;
2850 if (!libwps::readDataToEnd(input, data) || !data.getDataBuffer())
2851 {
2852 WPS_DEBUG_MSG(("MultiplanParser::decodeStream: can not read the original input\n"));
2853 return RVNGInputStreamPtr();
2854 }
2855 auto *buf=const_cast<unsigned char *>(data.getDataBuffer());
2856 input->seek(actPos,librevenge::RVNG_SEEK_SET);
2857 auto const &keys=m_state->m_keys;
2858 while (!input->isEnd())
2859 {
2860 long pos=input->tell();
2861 if (!checkFilePosition(pos+6)) break;
2862 int type=int(libwps::readU16(input));
2863 if (type<7 || type>12) break;
2864 input->seek(2, librevenge::RVNG_SEEK_CUR);
2865 int dSz=int(libwps::readU16(input));
2866 if (dSz<6 || !checkFilePosition(pos+dSz)) break;
2867 if (dSz==6) continue;
2868 for (int i=6; i<dSz; ++i)
2869 buf[pos+i]^=keys[i&0xf];
2870 input->seek(dSz-6,librevenge::RVNG_SEEK_CUR);
2871 }
2872 RVNGInputStreamPtr res(new WPSStringStream(data.getDataBuffer(), static_cast<unsigned int>(data.size())));
2873 res->seek(actPos, librevenge::RVNG_SEEK_SET);
2874 return res;
2875 }
2876
2877 }
2878
2879 /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */