Debian Codegraph @

src/lib/MsWksSSParser.cxx

raw
1 /* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */
2
3 /* libmwaw
4 * Version: MPL 2.0 / LGPLv2+
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 2.0 (the "License"); you may not use this file except in compliance with
8 * the License or as specified alternatively below. You may obtain a copy of
9 * the License at http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * Major Contributor(s):
17 * Copyright (C) 2002 William Lachance ([email protected])
18 * Copyright (C) 2002,2004 Marc Maurer ([email protected])
19 * Copyright (C) 2004-2006 Fridrich Strba ([email protected])
20 * Copyright (C) 2006, 2007 Andrew Ziem
21 * Copyright (C) 2011, 2012 Alonso Laurent ([email protected])
22 *
23 *
24 * All Rights Reserved.
25 *
26 * For minor contributions see the git repository.
27 *
28 * Alternatively, the contents of this file may be used under the terms of
29 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
30 * in which case the provisions of the LGPLv2+ are applicable
31 * instead of those above.
32 */
33
34 #include <iomanip>
35 #include <iostream>
36 #include <limits>
37 #include <sstream>
38
39 #include <librevenge/librevenge.h>
40
41
42 #include "MWAWCell.hxx"
43 #include "MWAWFont.hxx"
44 #include "MWAWFontConverter.hxx"
45 #include "MWAWHeader.hxx"
46 #include "MWAWOLEParser.hxx"
47 #include "MWAWPrinter.hxx"
48 #include "MWAWSpreadsheetListener.hxx"
49 #include "MWAWSubDocument.hxx"
50
51 #include "MsWksGraph.hxx"
52 #include "MsWks3Text.hxx"
53 #include "MsWksDocument.hxx"
54
55 #include "MsWksSSParser.hxx"
56
57 /** Internal: the structures of a MsWksSSParser */
58 namespace MsWksSSParserInternal
59 {
60 /** a cell of a MsWksSSParser */
61 class Cell final : public MWAWCell
62 {
63 public:
64 /// constructor
65 Cell()
66 : m_content()
67 , m_noteId(0)
68 {
69 }
70 Cell(Cell const &)=default;
71 Cell &operator=(Cell const &)=default;
72 Cell &operator=(Cell &&)=default;
73 //! destructor
74 ~Cell() final;
75 //! returns true if the cell do contain any content
76 bool isEmpty() const
77 {
78 return m_content.empty() && !hasBorders() && !m_noteId;
79 }
80
81 //! operator<<
82 friend std::ostream &operator<<(std::ostream &o, Cell const &cell);
83
84 //! the cell content
85 MWAWCellContent m_content;
86
87 /** the note id */
88 int m_noteId;
89 };
90
91 //! operator<<
92 std::ostream &operator<<(std::ostream &o, Cell const &cell)
93 {
94 o << static_cast<MWAWCell const &>(cell);
95
96 if (cell.m_noteId) o << ", noteId=" << cell.m_noteId;
97 return o;
98 }
99
100 /** the spreadsheet of a of a MsWksSSParser */
101 class Spreadsheet
102 {
103 public:
104 //! constructor
105 Spreadsheet()
106 : m_font(3,12)
107 , m_widthCols()
108 , m_cells()
109 , m_listPageBreaks()
110 , m_idNoteMap()
111 , m_name("Sheet0")
112 {
113 }
114 //! convert the m_widthCols in a vector of of point size
115 std::vector<float> convertInPoint(std::vector<int> const &list, float defSize) const
116 {
117 auto numCols=size_t(getRightBottomPosition()[0]+1);
118 std::vector<float> res;
119 res.resize(numCols);
120 for (size_t i = 0; i < numCols; i++) {
121 if (i>=list.size() || list[i] < 0) res[i] = defSize;
122 else res[i] = float(list[i]);
123 }
124 return res;
125 }
126
127 /** the default font */
128 MWAWFont m_font;
129 /** the column size in pixels(?) */
130 std::vector<int> m_widthCols;
131 /** the list of not empty cells */
132 std::vector<Cell> m_cells;
133 /** the list of page break */
134 std::vector<int> m_listPageBreaks;
135 /** a map id->note content */
136 std::map<int,MWAWEntry> m_idNoteMap;
137 /** the spreadsheet name */
138 std::string m_name;
139 protected:
140 /** returns the last Right Bottom cell position */
141 MWAWVec2i getRightBottomPosition() const
142 {
143 int maxX = 0, maxY = 0;
144 for (auto const &cell : m_cells) {
145 MWAWVec2i const &p = cell.position();
146 if (p[0] > maxX) maxX = p[0];
147 if (p[1] > maxY) maxY = p[1];
148 }
149 return MWAWVec2i(maxX, maxY);
150 }
151 };
152
153 Cell::~Cell()
154 {
155 }
156
157 ////////////////////////////////////////
158 //! Internal: the state of a MsWksSSParser
159 struct State {
160 //! constructor
161 State()
162 : m_spreadsheet()
163 , m_actPage(0)
164 , m_numPages(0)
165 , m_pageLength(-1)
166 {
167 }
168
169 /** the spreadsheet */
170 Spreadsheet m_spreadsheet;
171 int m_actPage /** the actual page */, m_numPages /** the number of page of the final document */;
172
173 //! the page length in point (if known)
174 int m_pageLength;
175 };
176
177 ////////////////////////////////////////
178 //! Internal: the subdocument of a MsWksSSParser
179 class SubDocument final : public MWAWSubDocument
180 {
181 public:
182 SubDocument(MsWksSSParser &pars, MWAWInputStreamPtr const &input, int zoneId)
183 : MWAWSubDocument(&pars, input, MWAWEntry())
184 ,m_id(zoneId)
185 {
186 }
187
188 //! destructor
189 ~SubDocument() final {}
190
191 //! operator!=
192 bool operator!=(MWAWSubDocument const &doc) const final;
193
194 //! the parser function
195 void parse(MWAWListenerPtr &listener, libmwaw::SubDocumentType type) final;
196
197 protected:
198 /** the subdocument id*/
199 int m_id;
200 };
201
202 void SubDocument::parse(MWAWListenerPtr &listener, libmwaw::SubDocumentType /*type*/)
203 {
204 if (!listener.get()) {
205 MWAW_DEBUG_MSG(("MsWksSSParserInternal::SubDocument::parse: no listener\n"));
206 return;
207 }
208 auto *parser = dynamic_cast<MsWksSSParser *>(m_parser);
209 if (!parser) {
210 MWAW_DEBUG_MSG(("MsWksSSParserInternal::SubDocument::parse: no parser\n"));
211 return;
212 }
213 long pos = m_input->tell();
214 parser->sendNote(m_id);
215 m_input->seek(pos, librevenge::RVNG_SEEK_SET);
216 }
217
218 bool SubDocument::operator!=(MWAWSubDocument const &doc) const
219 {
220 if (MWAWSubDocument::operator!=(doc)) return true;
221 auto const *sDoc = dynamic_cast<SubDocument const *>(&doc);
222 if (!sDoc) return true;
223 if (m_id != sDoc->m_id) return true;
224 return false;
225 }
226 }
227
228
229 ////////////////////////////////////////////////////////////
230 // constructor/destructor, ...
231 ////////////////////////////////////////////////////////////
232 MsWksSSParser::MsWksSSParser(MWAWInputStreamPtr const &input, MWAWRSRCParserPtr const &rsrcParser, MWAWHeader *header)
233 : MWAWSpreadsheetParser(input, rsrcParser, header)
234 , m_state()
235 , m_listZones()
236 , m_document()
237 {
238 MWAWInputStreamPtr mainInput=input;
239 if (!input) return;
240 if (input->isStructured()) {
241 MWAWInputStreamPtr mainOle = input->getSubStreamByName("MN0");
242 if (mainOle)
243 mainInput=mainOle;
244 }
245 m_document.reset(new MsWksDocument(mainInput, *this));
246 init();
247 }
248
249 MsWksSSParser::~MsWksSSParser()
250 {
251 }
252
253 void MsWksSSParser::init()
254 {
255 resetSpreadsheetListener();
256 setAsciiName("main-1");
257
258 m_state.reset(new MsWksSSParserInternal::State);
259
260 // reduce the margin (in case, the page is not defined)
261 getPageSpan().setMargins(0.1);
262 }
263
264 ////////////////////////////////////////////////////////////
265 // the parser
266 ////////////////////////////////////////////////////////////
267 void MsWksSSParser::parse(librevenge::RVNGSpreadsheetInterface *docInterface)
268 {
269 if (!m_document || !m_document->getInput() || !checkHeader(nullptr)) throw(libmwaw::ParseException());
270 bool ok = true;
271 try {
272 #ifdef DEBUG
273 MWAWInputStreamPtr &input= getInput();
274 if (input->isStructured()) {
275 std::shared_ptr<MWAWOLEParser> oleParser(new MWAWOLEParser("MN0", getParserState()->m_fontConverter, 3));
276 oleParser->parse(input);
277 }
278 #endif
279 // create the asciiFile
280 m_document->initAsciiFile(asciiName());
281
282 checkHeader(nullptr);
283 createZones();
284 ok=!m_state->m_spreadsheet.m_cells.empty();
285 if (ok) {
286 createDocument(docInterface);
287 sendSpreadsheet();
288 }
289 }
290 catch (...) {
291 MWAW_DEBUG_MSG(("MsWksSSParser::parse: exception catched when parsing\n"));
292 ok = false;
293 }
294 m_document->ascii().reset();
295
296 resetSpreadsheetListener();
297 if (!ok) throw(libmwaw::ParseException());
298 }
299
300 void MsWksSSParser::sendNote(int noteId)
301 {
302 MWAWListenerPtr listener=getSpreadsheetListener();
303 if (!listener||
304 m_state->m_spreadsheet.m_idNoteMap.find(noteId)==m_state->m_spreadsheet.m_idNoteMap.end()) {
305 MWAW_DEBUG_MSG(("MsWksSSParser::sendNote: can not send note %d\n", noteId));
306 return;
307 }
308 MWAWEntry const &entry=m_state->m_spreadsheet.m_idNoteMap.find(noteId)->second;
309 int const vers=version();
310 if (!entry.valid()) return;
311 MWAWInputStreamPtr input = m_document->getInput();
312 input->seek(entry.begin(), librevenge::RVNG_SEEK_SET);
313 while (1) {
314 long pos=input->tell();
315 if (input->isEnd() || pos>=entry.end()) return;
316 auto c = static_cast<int>(input->readULong(1));
317 switch (c) {
318 case 0x9:
319 listener->insertTab();
320 break;
321 case 0x10: // cursor pos
322 case 0x11:
323 break;
324 default:
325 if (c >= 0x15 && c <= 0x19 && vers >= 3) {
326 int sz = (c==0x19) ? 0 : (c == 0x18) ? 1 : 2;
327 if (sz && pos+1+sz <= entry.end())
328 input->seek(sz, librevenge::RVNG_SEEK_CUR);
329 switch (c) {
330 case 0x19:
331 listener->insertField(MWAWField(MWAWField::Title));
332 break;
333 case 0x18:
334 listener->insertField(MWAWField(MWAWField::PageNumber));
335 break;
336 case 0x16:
337 listener->insertField(MWAWField(MWAWField::Time));
338 break;
339 case 0x17: // id = 0 : short date ; id=9 : long date
340 listener->insertField(MWAWField(MWAWField::Date));
341 break;
342 case 0x15:
343 MWAW_DEBUG_MSG(("MsWksSSParser::sendNote: find unknown field type 0x15\n"));
344 break;
345 default:
346 break;
347 }
348 }
349 else if (c <= 0x1f) {
350 MWAW_DEBUG_MSG(("MsWksSSParser::sendNote: find char=%x\n", static_cast<unsigned int>(c)));
351 }
352 else
353 listener->insertCharacter(static_cast<unsigned char>(c), input, entry.end());
354 break;
355 }
356
357 }
358 }
359
360 ////////////////////////////////////////////////////////////
361 // create the document
362 ////////////////////////////////////////////////////////////
363 void MsWksSSParser::createDocument(librevenge::RVNGSpreadsheetInterface *documentInterface)
364 {
365 if (!documentInterface) return;
366 if (getSpreadsheetListener()) {
367 MWAW_DEBUG_MSG(("MsWksSSParser::createDocument: listener already exist\n"));
368 return;
369 }
370
371 std::vector<MWAWPageSpan> pageList;
372 m_state->m_actPage = 0;
373 m_document->getPageSpanList(pageList, m_state->m_numPages);
374 MWAWSpreadsheetListenerPtr listen(new MWAWSpreadsheetListener(*getParserState(), pageList, documentInterface));
375 setSpreadsheetListener(listen);
376 listen->startDocument();
377 // time to send page information the graph parser and the text parser
378 m_document->getGraphParser()->setPageLeftTop
379 (MWAWVec2f(72.f*float(getPageSpan().getMarginLeft()),
380 72.f*float(getPageSpan().getMarginTop())+m_document->getHeaderFooterHeight(true)));
381 }
382
383
384 ////////////////////////////////////////////////////////////
385 //
386 // Intermediate level
387 //
388 ////////////////////////////////////////////////////////////
389 bool MsWksSSParser::createZones()
390 {
391 if (getInput()->isStructured())
392 m_document->createOLEZones(getInput());
393 MWAWInputStreamPtr input = m_document->getInput();
394 const int vers=version();
395 long pos;
396 if (vers>2) {
397 pos = input->tell();
398 if (!m_document->readDocumentInfo(0x9a))
399 m_document->getInput()->seek(pos, librevenge::RVNG_SEEK_SET);
400 pos = input->tell();
401 if (m_document->hasHeader() && !m_document->readGroupHeaderFooter(true,99))
402 input->seek(pos, librevenge::RVNG_SEEK_SET);
403 pos = input->tell();
404 if (m_document->hasFooter() && !m_document->readGroupHeaderFooter(false,99))
405 input->seek(pos, librevenge::RVNG_SEEK_SET);
406 }
407 readSSheetZone();
408
409 auto &typeZoneMap=m_document->getTypeZoneMap();
410 // fixme: getNewZoneId here
411 int mainId=MsWksDocument::Z_MAIN;
412 typeZoneMap.insert(std::multimap<int,MsWksDocument::Zone>::value_type
413 (MsWksDocument::Z_MAIN,MsWksDocument::Zone(MsWksDocument::Z_MAIN, mainId)));
414 pos = input->tell();
415 libmwaw::DebugFile &ascFile = m_document->ascii();
416 if (input->isEnd() || input->readLong(2)!=0)
417 input->seek(pos, librevenge::RVNG_SEEK_SET);
418 else {
419 MWAWEntry group;
420 group.setId(mainId);
421 group.setName("RBDR");
422 if (!m_document->m_graphParser->readRB(input,group,1)) {
423 MWAW_DEBUG_MSG(("MsWksSSParser::createZones: can not read RBDR group\n"));
424 ascFile.addPos(pos+2);
425 ascFile.addNote("Entries(RBDR):###");
426 input->seek(pos, librevenge::RVNG_SEEK_SET);
427 }
428 }
429
430 // normally, the file is now parsed, let check for potential remaining zones
431 while (!input->isEnd()) {
432 MWAW_DEBUG_MSG(("MsWksSSParser::createZones: find some unexpected data\n"));
433 pos = input->tell();
434 MsWksDocument::Zone unknown;
435 if (!m_document->readZone(unknown) || input->tell() <= pos) {
436 ascFile.addPos(pos);
437 ascFile.addNote("Entries(End)");
438 ascFile.addPos(pos+100);
439 ascFile.addNote("_");
440 break;
441 }
442 }
443
444 // ok, prepare the data
445 m_state->m_numPages = 1;
446 std::vector<int> linesH, pagesH;
447 m_document->getGraphParser()->computePositions(mainId, linesH, pagesH);
448 return true;
449 }
450
451 ////////////////////////////////////////////////////////////
452 // read a spreadsheet zone
453 ////////////////////////////////////////////////////////////
454 bool MsWksSSParser::readSSheetZone()
455 {
456 auto &sheet=m_state->m_spreadsheet;
457 sheet=MsWksSSParserInternal::Spreadsheet();
458 int const vers=version();
459
460 MWAWInputStreamPtr input=m_document->getInput();
461 libmwaw::DebugFile &ascFile=m_document->ascii();
462 long pos = input->tell(), sheetDebPos=pos;
463 if (!input->checkPosition(pos+0x30+0x30+0x408)) {
464 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part A/B\n"));
465 input->seek(pos, librevenge::RVNG_SEEK_SET);
466 return false;
467 }
468
469 ascFile.addPos(pos);
470 libmwaw::DebugStream f, f2;
471 f << "Entries(SSheet): v0=["; // always 8, -1 ?
472 for (int i = 0; i < 2; i++)
473 f << input->readLong(1) << ",";
474 f << "],";
475
476 int N[2]; // max col, max row
477 for (auto &n : N) n = static_cast<int>(input->readLong(2));
478 f << "maxCol=" << N[0] << "," << "maxRow=" << N[1] << ",";
479
480 f << "unk0=" << std::hex << input->readULong(4) << std::dec << ","; // big number
481
482 int zoneSize[3];
483 zoneSize[0] = static_cast<int>(input->readLong(2));
484 if (zoneSize[0]) f << "zone[SheetF]=" << std::hex << zoneSize[0] << std::dec << ",";
485 auto numPageBreak = static_cast<int>(input->readLong(2));
486 if (numPageBreak) f << "nPgBreak=" << numPageBreak << ",";
487 auto numColBreak = static_cast<int>(input->readLong(2));
488 if (numColBreak) f << "nColBreak=" << numColBreak << ",";
489 zoneSize[1]= static_cast<int>(input->readLong(2));
490 if (zoneSize[1]) f << "zone[DocInfo]=" << zoneSize[1] << ",";
491 f << "unk1=" << std::hex << input->readULong(4) << std::dec << ","; // big number
492 f << std::dec;
493
494 int val;
495 for (int i = 0; i < 2; i++) {
496 val = static_cast<int>(input->readLong(2));
497 if (val)
498 f << "w" << i << "=" << val << ",";
499 }
500 f << "v2=["; // [_,_,_,_,_,_,] or [_,1,3,_,1,3,] or [_,5,5,_,4,2,]
501 for (int i = 0; i < 6; i++) {
502 val = static_cast<int>(input->readLong(1));
503 if (val)
504 f << val << ",";
505 else
506 f << "_,";
507 }
508 f << "]";
509 f << ", v3=["; // [_,_,_,_,] or [_,_,_,1,] or [_,_,_,11,]
510 for (int i = 0; i < 4; i++) {
511 val = static_cast<int>(input->readLong(2));
512 if (val)
513 f << val << ",";
514 else
515 f << "_,";
516 }
517 f << "]";
518
519 f << ", v4=[" << std::hex;
520 for (int i = 0; i < 4; i++) {
521 val = static_cast<int>(input->readLong(2));
522 if (val)
523 f << val << ",";
524 else
525 f << "_,";
526 }
527 f << "]" << std::dec;
528
529 ascFile.addNote(f.str().c_str());
530
531 pos = input->tell();
532 f.str("");
533 ascFile.addPos(pos);
534 f << "SSheetB: ";
535
536 std::vector<int> colPos;
537
538 int prevW = -1;
539 bool ok = true;
540 for (int i = 0; i < 257; i++) {
541 auto col = static_cast<int>(input->readULong(2));
542 if ((col & 0xFFF) != i+1) {
543 ok = false;
544 break;
545 }
546 auto w = static_cast<int>(input->readLong(2));
547 if (w > 0) {
548 if (prevW > w && i < 200) {
549 ok = false;
550 break;
551 }
552 if (prevW > w) w = prevW;
553 else prevW = w;
554 }
555 colPos.push_back(w);
556 }
557
558 if (!ok) {
559 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part B\n"));
560 input->seek(pos, librevenge::RVNG_SEEK_SET);
561 return false;
562 }
563
564 f << "lastN=" << input->readULong(2);
565 f << ", lastV=" << input->readULong(2);
566 f << ", width=[";
567 std::vector<int> &colSize = sheet.m_widthCols;
568 colSize.resize(256);
569 for (size_t i = 0; i < 257; i++) {
570 int cPos = colPos[i];
571 int lastPos = (i == 0) ? 0 : colPos[i-1];
572 if (cPos == 0) f << "_";
573 else if (cPos == -1) {
574 f << "Inf";
575 cPos = 0;
576 }
577 else f << cPos-lastPos;
578
579 if (i< 256) {
580 if (cPos) colSize[i]=cPos-lastPos;
581 else colSize[i]=0;
582 }
583
584 f << ",";
585 }
586 f << "]" << std::dec;
587 ascFile.addNote(f.str().c_str());
588
589 pos = input->tell();
590 f.str("");
591 ascFile.addPos(pos);
592 long endPos=pos+256;
593 f << "SSheetC:";
594 int numCharts=0;
595 for (int i=0; i < 8; ++i) {
596 // the chart names in v2, can we have more than 8 charts ?
597 long cPos=input->tell();
598 val = static_cast<int>(input->readLong(2));
599 auto sSz=static_cast<int>(input->readULong(1));
600 if (!sSz || sSz>32-7) {
601 input->seek(cPos, librevenge::RVNG_SEEK_SET);
602 break;
603 }
604 ++numCharts;
605 f << "Chart" << i << "=[";
606 if (val) f << "unkn=" << val << ",";
607 std::string name("");
608 for (int c=0; c<sSz; ++c)
609 name += char(input->readULong(1));
610 f << name << ",";
611 if ((sSz%2)==0) input->seek(1, librevenge::RVNG_SEEK_CUR);
612 f << "id=" << std::hex << input->readULong(4) << std::dec << "],";
613 input->seek(cPos+32, librevenge::RVNG_SEEK_SET);
614 }
615 int numRemains=int(endPos-input->tell())/2;
616 for (int i = 0; i < numRemains; i++) {
617 val = static_cast<int>(input->readLong(2));
618 if (val) f << "f" << i << "=" << val << ",";
619 }
620 ascFile.addNote(f.str().c_str());
621 input->seek(endPos, librevenge::RVNG_SEEK_SET);
622
623 pos = input->tell();
624 f.str("");
625 ascFile.addPos(pos);
626
627 if (!input->checkPosition(pos+52)) {
628 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part D\n"));
629 input->seek(pos, librevenge::RVNG_SEEK_SET);
630 return false;
631 }
632
633 f << "SSheetD:";
634 for (int i = 0; i < 5; i++) {
635 val = static_cast<int>(input->readLong(2));
636 if (i==3) {
637 if (val==44) continue;
638 f << "unkn=" << val << ",";
639 }
640 else if (val)
641 f << "f" << i << "=" << val << ",";
642 }
643 f << "dim?=["; // in general 1,1,1,1 but can be X,X,1,1
644 for (int i = 0; i < 4; i++)
645 f << input->readLong(2) << ",";
646 f << "]";
647
648 // always g0=3ffe, g1=100 ?
649 for (int i = 0; i < 2; i++) {
650 f << ", g" << i << "=" << std::hex << input->readLong(2) << std::dec;
651 }
652 auto fId = static_cast<int>(input->readLong(2));
653 auto fSize = static_cast<int>(input->readLong(2));
654 sheet.m_font = MWAWFont(fId, float(fSize));
655 f << ", [" << sheet.m_font.getDebugString(getParserState()->m_fontConverter) << "]";
656 // , [0,{33|255},] ?
657 f << ", unk=[" << std::dec;
658 for (int i = 0; i < 2; i++)
659 f << input->readLong(2) << ",";
660 f << "]";
661 int numRemain=int(sheetDebPos+m_document->getLengthOfFileHeader3()-input->tell())/2;
662 for (int i = 0; i < numRemain; i++) {
663 val = static_cast<int>(input->readLong(2));
664 if (val) f << "f" << i << "=" << val << ",";
665 }
666 ascFile.addNote(f.str().c_str());
667 input->seek(sheetDebPos+m_document->getLengthOfFileHeader3(), librevenge::RVNG_SEEK_SET);
668
669 // part E
670 MWAWVec2i cellPos(0,0);
671 while (1) {
672 if (cellPos[1] == N[1]) break;
673
674 long posRow = input->tell();
675 unsigned long length = input->readULong(4);
676 if (length & 0xF0000000L) {
677 int nRow = length & 0x0FFFFFFFL;
678 if ((length >> 28) != 8 || std::numeric_limits<int>::max() - cellPos[1] < nRow) {
679 input->seek(posRow, librevenge::RVNG_SEEK_SET);
680 break;
681 }
682 f.str("");
683 f << "SSheetE:skipRow=" << std::hex << nRow;
684 cellPos[1]+=nRow;
685 ascFile.addPos(posRow);
686 ascFile.addNote(f.str().c_str());
687 continue;
688 }
689 long endRow = posRow+long(length)+4;
690
691 if (!input->checkPosition(endRow)) {
692 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part E(row)\n"));
693 input->seek(posRow, librevenge::RVNG_SEEK_SET);
694 return false;
695 }
696
697 f.str("");
698 cellPos[0]=0;
699 f << "SSheetE(Row" << std::dec << cellPos[1]+1 << "): ";
700 while (input->tell() < endRow-1) {
701 pos = input->tell();
702 auto sz = static_cast<int>(input->readULong(1));
703
704 if (sz == 0xFE) { // skip next cell
705 auto numC = static_cast<int>(input->readULong(1));
706 f2.str("");
707 f2 << "SSheetE:skipC=" << numC;
708 cellPos[0]+=numC;
709 ascFile.addPos(pos);
710 ascFile.addNote(f2.str().c_str());
711 continue;
712 }
713
714 if (sz == 0) {
715 ascFile.addPos(pos);
716 ascFile.addNote("SSheetE:empty");
717 ++cellPos[0];
718 continue;
719 }
720 MsWksSSParserInternal::Cell cell;
721 if (!readCell(sz, cellPos, cell)) {
722 input->seek(pos, librevenge::RVNG_SEEK_SET);
723 break;
724 }
725 if (!cell.isEmpty())
726 sheet.m_cells.push_back(cell);
727 ++cellPos[0];
728 }
729
730 ++cellPos[1];
731 if (input->tell() != endRow-1) {
732 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part E(cells)\n"));
733 input->seek(posRow, librevenge::RVNG_SEEK_SET);
734 return false;
735 }
736 ascFile.addDelimiter(endRow-1,'|');
737 val = static_cast<int>(input->readULong(1));
738 if (val == 0) f << "*";
739 else if (val != 0xFF)
740 f << "##end=" << std::hex << val << std::dec;
741
742 ascFile.addPos(posRow);
743 ascFile.addNote(f.str().c_str());
744 if (val == 0)
745 break;
746 }
747
748 pos = input->tell();
749 if (!input->checkPosition(pos+zoneSize[0])) {
750 input->seek(pos, librevenge::RVNG_SEEK_SET);
751 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Can not read part F\n"));
752 return false;
753 }
754
755 f.str("");
756 f << "SSheetF[A]:";
757 ascFile.addPos(pos);
758 ascFile.addNote(f.str().c_str());
759 input->seek(pos+zoneSize[0]-10, librevenge::RVNG_SEEK_SET);
760
761 pos = input->tell();
762 f.str("");
763 f << "SSheetF[B]:" << std::dec;
764 for (int i = 0; i < 4; i++) {
765 val = static_cast<int>(input->readLong(2));
766 if (val) f << "f" << i << "=" << val << ",";
767 }
768 val = static_cast<int>(input->readULong(2));
769 if (val) f << std::hex << "fl=" << val << "," << std::dec;
770 ascFile.addPos(pos);
771 ascFile.addNote(f.str().c_str());
772
773 if (numPageBreak || numColBreak) {
774 pos=input->tell();
775 f.str("");
776 f << "SSheetG:";
777 if (numPageBreak > 0) {
778 sheet.m_listPageBreaks.resize(size_t(numPageBreak));
779 f << "pgBreak=[";
780 for (auto &pgBreak : sheet.m_listPageBreaks) {
781 pgBreak = static_cast<int>(input->readULong(2));
782 f << pgBreak << ",";
783 }
784 f << "],";
785 }
786 // columns/notes break?
787 if (numColBreak) {
788 f << "colBreak=[";
789 for (int i = 0; i < numColBreak; i++)
790 f << input->readULong(2) << ",";
791 f << "],";
792 }
793 ascFile.addPos(pos);
794 ascFile.addNote(f.str().c_str());
795 }
796
797 if (zoneSize[1]>0) {
798 // only version<=2 seems to contains the print data with size 0x15e
799 pos = input->tell();
800 MWAWEntry zone;
801 if (!m_document->readDocumentInfo(zoneSize[1])) {
802 input->seek(pos+zoneSize[1], librevenge::RVNG_SEEK_SET);
803 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:can not read print info\n"));
804 ascii().addPos(pos);
805 ascii().addNote("SSheet[printInfo]:###");
806 }
807 }
808
809 if (vers==2) {
810 for (int i=0; i < numCharts; ++i) {
811 pos=input->tell();
812 if (!input->checkPosition(pos+256)) {
813 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:can not find chart %d data\n", i));
814 input->seek(pos, librevenge::RVNG_SEEK_SET);
815 return false;
816 }
817 f.str("");
818 f << "Entries(Chart)[" << i << "]:";
819 ascFile.addPos(pos);
820 ascFile.addNote(f.str().c_str());
821 input->seek(pos+256, librevenge::RVNG_SEEK_SET);
822 }
823 }
824
825 long HDebPos = input->tell();
826 f.str("");
827 f << "SSheetH:" << std::dec;
828 int numNote = 0;
829 while (1) {
830 pos = input->tell();
831 auto idNote = static_cast<int>(input->readLong(2));
832 if (idNote == 0) break;
833 if (idNote != ++numNote) {
834 input->seek(pos, librevenge::RVNG_SEEK_CUR);
835 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Pb when reading a note\n"));
836 return false;
837 }
838 // a pascal string
839 auto pSz = static_cast<int>(input->readLong(2));
840 MWAWEntry note;
841 note.setBegin(input->tell());
842 note.setLength(pSz);
843 std::string str="";
844 for (int s = 0; s < pSz; s++)
845 str += char(input->readLong(1));
846 if (input->tell() != pos+4+pSz) {
847 input->seek(pos, librevenge::RVNG_SEEK_CUR);
848 MWAW_DEBUG_MSG(("MsWksSSParser::readSSheetZone:Pb when reading a note\n"));
849 return false;
850 }
851 if (pSz) {
852 sheet.m_idNoteMap[idNote] = note;
853 f << "Note" << idNote << "=\"" << str << "\",";
854 }
855 }
856
857 ascFile.addPos(HDebPos);
858 ascFile.addNote(f.str().c_str());
859 return true;
860 }
861
862 bool MsWksSSParser::readCell(int sz, MWAWVec2i const &cellPos, MsWksSSParserInternal::Cell &cell)
863 {
864 int const vers=version();
865 cell = MsWksSSParserInternal::Cell();
866 cell.setPosition(cellPos);
867 if (sz == 0xFF || sz < 5) return false;
868
869 MWAWInputStreamPtr input=m_document->getInput();
870 long debPos = input->tell();
871
872 libmwaw::DebugFile &ascFile=m_document->ascii();
873 libmwaw::DebugStream f;
874 long endPos = debPos+sz-5;
875 input->seek(endPos+5, librevenge::RVNG_SEEK_SET);
876 if (input->tell() !=endPos+5) return false;
877
878 // read the flag
879 input->seek(endPos, librevenge::RVNG_SEEK_SET);
880 int fl[5];
881 for (auto &flag : fl) flag = static_cast<int>(input->readULong(1));
882 MWAWCell::Format format;
883 MWAWCellContent &content=cell.m_content;
884 int style = 0, align = 0, subformat = 0;
885 if (vers >= 3) {
886 style = (fl[4]>>1) & 0x1f;
887 align = (fl[4]>>6);
888 fl[4] &= 1;
889 subformat = fl[2] >> 4;
890 cell.setBorders(fl[2] & 0xF, MWAWBorder()); // checkme
891 fl[2] = 0;
892 }
893 else {
894 style = fl[4] & 0x18;
895 align = (fl[4]>>5)&3;
896 subformat= (fl[4]&7);
897 fl[4] &= 0x80;
898 }
899 switch (align) {
900 case 0:
901 cell.setHAlignment(MWAWCell::HALIGN_LEFT);
902 break;
903 case 1:
904 cell.setHAlignment(MWAWCell::HALIGN_CENTER);
905 break;
906 case 2:
907 cell.setHAlignment(MWAWCell::HALIGN_RIGHT);
908 break;
909 default:
910 case 3:
911 break; // default
912 }
913 cell.m_noteId = fl[1] & 0xf;
914 fl[1] >>= 4;
915 int type = fl[3] >> 4;
916 format.m_digits=(fl[3] & 0xf);
917 fl[3] &= 1;
918
919 MWAWFont font=m_state->m_spreadsheet.m_font;
920 MWAWColor col;
921 if (vers>=3&&m_document->getColor(fl[0],col,3)) {
922 font.setColor(col);
923 fl[0]=0;
924 }
925 uint32_t fflags = 0;
926 if (style) {
927 if (style & 1) fflags |= MWAWFont::shadowBit;
928 if (style & 2) fflags |= MWAWFont::embossBit;
929 if (style & 4) fflags |= MWAWFont::italicBit;
930 if (style & 8) font.setUnderlineStyle(MWAWFont::Line::Simple);
931 if (style & 16) fflags |= MWAWFont::boldBit;
932 }
933 font.setFlags(fflags);
934 cell.setFont(font);
935
936 content.m_contentType=MWAWCellContent::C_NONE;
937 if (type & 2) { // checkme: is this also ok for v2?
938 cell.setProtected(true);
939 type &= 0xFD;
940 }
941 switch (type>>2) {
942 case 0:
943 content.m_contentType=MWAWCellContent::C_TEXT;
944 format.m_format=MWAWCell::F_TEXT;
945 break;
946 case 1:
947 format.m_format=MWAWCell::F_NUMBER;
948 content.m_contentType=MWAWCellContent::C_NUMBER;
949 break;
950 case 3:
951 f << "type" << type << ",";
952 MWAW_FALLTHROUGH;
953 case 2: //number general
954 format.m_format=MWAWCell::F_NUMBER;
955 content.m_contentType=MWAWCellContent::C_FORMULA;
956 break;
957 default:
958 break;
959 }
960 if (vers <= 2 && format.m_format==MWAWCell::F_NUMBER) {
961 switch (subformat) {
962 case 0:
963 format.m_numberFormat=MWAWCell::F_NUMBER_DECIMAL;
964 break;
965 case 1:
966 format.m_numberFormat=MWAWCell::F_NUMBER_CURRENCY;
967 break;
968 case 2:
969 format.m_numberFormat=MWAWCell::F_NUMBER_PERCENT;
970 break;
971 case 4:
972 format.m_numberFormat=MWAWCell::F_NUMBER_SCIENTIFIC;
973 break;
974 case 5:
975 case 6:
976 format.m_format=MWAWCell::F_DATE;
977 break;
978 case 7:
979 format.m_format=MWAWCell::F_TIME;
980 break;
981 case 3: // generic
982 default:
983 format.m_numberFormat=MWAWCell::F_NUMBER_GENERIC;
984 break;
985 }
986 }
987 else if (vers>2) {
988 if (type&1) {
989 format.m_format= (subformat < 4) ? MWAWCell::F_TIME : MWAWCell::F_DATE;
990 fl[3] = 0;
991 }
992 switch (format.m_format) {
993 case MWAWCell::F_NUMBER:
994 format.m_numberFormat=MWAWCell::F_NUMBER_GENERIC;
995 switch (subformat) {
996 case 0:
997 break;
998 case 1:
999 format.m_numberFormat=MWAWCell::F_NUMBER_DECIMAL;
1000 break;
1001 case 2:
1002 format.m_numberFormat=MWAWCell::F_NUMBER_CURRENCY;
1003 break;
1004 case 3:
1005 format.m_thousandHasSeparator=true;
1006 break;
1007 case 4:
1008 format.m_numberFormat=MWAWCell::F_NUMBER_CURRENCY;
1009 format.m_thousandHasSeparator=true;
1010 break;
1011 case 5:
1012 format.m_numberFormat=MWAWCell::F_NUMBER_SCIENTIFIC;
1013 break;
1014 case 6:
1015 format.m_numberFormat=MWAWCell::F_NUMBER_PERCENT;
1016 break;
1017 case 7:
1018 format.m_numberFormat=MWAWCell::F_NUMBER_PERCENT;
1019 format.m_thousandHasSeparator=true;
1020 break;
1021 default:
1022 f << ",subform==##unkn" << subformat;
1023 break;
1024 }
1025 break;
1026 case MWAWCell::F_TIME:
1027 if (subformat >= 0 && subformat < 4) {
1028 static char const *wh[]= {"%I:%M:%S %p", "%I:%M %p", "%H:%M:%S", "%H:%M"};
1029 format.m_DTFormat=wh[subformat];
1030 }
1031 else
1032 f << ",subform==##unkn" << subformat;
1033 break;
1034 case MWAWCell::F_DATE:
1035 switch (subformat) {
1036 case 4:
1037 case 5:
1038 case 6:
1039 case 7:
1040 case 8: {
1041 static char const *wh[]= {"%m/%d/%y", "%b %d, %Y", "%b, %d", "%b, %Y", "%a, %d %b, %Y" };
1042 format.m_DTFormat=wh[subformat-4];
1043 break;
1044 }
1045 case 10:
1046 case 11:
1047 format.m_DTFormat="%B %d %Y";
1048 break;
1049 case 12:
1050 case 13:
1051 format.m_DTFormat="%A, %B %d, %Y";
1052 break;
1053 default:
1054 f << ",subform==##unkn" << subformat;
1055 break;
1056 }
1057 break;
1058 case MWAWCell::F_TEXT:
1059 break;
1060 case MWAWCell::F_BOOLEAN:
1061 case MWAWCell::F_UNKNOWN:
1062 MWAW_DEBUG_MSG(("MsWksSSParser::readCell: unexpected format\n"));
1063 break;
1064 #if !defined(__clang__)
1065 default:
1066 f << ",subform==##unkn" << subformat;
1067 break;
1068 #endif
1069 }
1070 }
1071 long pos = debPos;
1072 input->seek(pos, librevenge::RVNG_SEEK_SET);
1073
1074 if (pos != endPos) {
1075 bool ok = true;
1076 switch (content.m_contentType) {
1077 case MWAWCellContent::C_TEXT: {
1078 content.m_textEntry.setBegin(pos);
1079 content.m_textEntry.setEnd(endPos);
1080 if (content.m_textEntry.length()>=0) {
1081 std::string text("");
1082 for (long i=0; i <content.m_textEntry.length(); ++i)
1083 text += char(input->readULong(1));
1084 f << text << ",";
1085 }
1086 else
1087 f << "###text,";
1088 break;
1089 }
1090 case MWAWCellContent::C_NUMBER: {
1091 double val;
1092 bool isNan;
1093 std::string str;
1094 if (!m_document->readDBNumber(endPos, val, isNan, str)) {
1095 ok=false;
1096 f << "###number";
1097 }
1098 else
1099 content.setValue(val);
1100 f << val;
1101 if (!str.empty()) f << "[" << str << "],";
1102 break;
1103 }
1104 case MWAWCellContent::C_FORMULA: {
1105 std::string extra("");
1106 if (!m_document->readFormula(endPos, content, extra)) {
1107 ok=false;
1108 f << "###";
1109 }
1110 f << extra;
1111 break;
1112 }
1113 case MWAWCellContent::C_NONE:
1114 break;
1115 case MWAWCellContent::C_UNKNOWN:
1116 #if !defined(__clang__)
1117 default:
1118 #endif
1119 ok = false;
1120 }
1121 if (!ok)
1122 f << ",###pb";
1123 }
1124 cell.setFormat(format);
1125 // change the reference date from 1/1/1904 to 1/1/1900
1126 if (format.m_format==MWAWCell::F_DATE && content.isValueSet())
1127 content.setValue(content.m_value+1460.);
1128
1129 std::string extra = f.str();
1130 f.str("");
1131 f << "SSheetE:" << cell << ",unk=[" << std::hex;
1132 for (auto flag : fl) {
1133 if (!flag) f << "_,";
1134 else f << flag << ",";
1135 }
1136 f << "]" << std::dec;
1137 if (extra.size()) f << ", extra=" << extra;
1138
1139
1140 pos = input->tell();
1141 if (pos != endPos) {
1142 ascFile.addDelimiter(pos,'[');
1143 ascFile.addDelimiter(endPos,']');
1144 }
1145
1146 ascFile.addPos(debPos-1);
1147 ascFile.addNote(f.str().c_str());
1148 input->seek(endPos+5, librevenge::RVNG_SEEK_SET);
1149 return true;
1150 }
1151
1152 ////////////////////////////////////////////////////////////
1153 ////////////////////////////////////////////////////////////
1154 bool MsWksSSParser::sendSpreadsheet()
1155 {
1156 MWAWSpreadsheetListenerPtr listener=getSpreadsheetListener();
1157 MWAWInputStreamPtr &input= m_document->getInput();
1158 if (!listener) {
1159 MWAW_DEBUG_MSG(("MsWksSSParser::sendSpreadsheet: I can not find the listener\n"));
1160 return false;
1161 }
1162 auto &sheet = m_state->m_spreadsheet;
1163
1164 int prevRow = -1;
1165 listener->openSheet(sheet.convertInPoint(sheet.m_widthCols,76), librevenge::RVNG_POINT, std::vector<int>(), sheet.m_name);
1166 // fixme: this sends the pictures present in the main page, but not the picture present in header/footer
1167 auto zone=m_document->getZone(MsWksDocument::Z_MAIN);
1168 m_document->getGraphParser()->sendAll(zone.m_zoneId, true);
1169
1170 for (auto const &cell : sheet.m_cells) {
1171 // FIXME: find the row height...
1172 if (cell.position()[1]>prevRow+1) {
1173 if (prevRow != -1) listener->closeSheetRow();
1174 int numRepeat=cell.position()[1]-1-prevRow;
1175 listener->openSheetRow(16, librevenge::RVNG_POINT, numRepeat);
1176 prevRow+=numRepeat;
1177 }
1178 if (cell.position()[1] > prevRow) {
1179 if (prevRow != -1) listener->closeSheetRow();
1180 ++prevRow;
1181 listener->openSheetRow(16, librevenge::RVNG_POINT);
1182 }
1183 listener->openSheetCell(cell, cell.m_content);
1184 if (cell.m_content.m_textEntry.valid()) {
1185 listener->setFont(cell.isFontSet() ? cell.getFont() : sheet.m_font);
1186 input->seek(cell.m_content.m_textEntry.begin(), librevenge::RVNG_SEEK_SET);
1187 while (!input->isEnd() && input->tell()<cell.m_content.m_textEntry.end()) {
1188 auto c=static_cast<unsigned char>(input->readULong(1));
1189 if (c==0xd)
1190 listener->insertEOL();
1191 else
1192 listener->insertCharacter(c);
1193 }
1194 }
1195 if (cell.m_noteId>0) {
1196 MWAWSubDocumentPtr subDoc(new MsWksSSParserInternal::SubDocument(*this, input, cell.m_noteId));
1197 listener->insertComment(subDoc);
1198 }
1199 listener->closeSheetCell();
1200 }
1201 if (prevRow!=-1) listener->closeSheetRow();
1202 listener->closeSheet();
1203 return true;
1204 }
1205
1206 ////////////////////////////////////////////////////////////
1207 //
1208 // Low level
1209 //
1210 ////////////////////////////////////////////////////////////
1211
1212 ////////////////////////////////////////////////////////////
1213 // read the header
1214 ////////////////////////////////////////////////////////////
1215 bool MsWksSSParser::checkHeader(MWAWHeader *header, bool strict)
1216 {
1217 *m_state = MsWksSSParserInternal::State();
1218 if (!m_document || !m_document->checkHeader3(header, strict)) return false;
1219 if (m_document->getKind() != MWAWDocument::MWAW_K_SPREADSHEET)
1220 return false;
1221 #ifndef DEBUG
1222 if (version() == 1)
1223 return false;
1224 #endif
1225 return true;
1226 }
1227
1228 // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab: