Debian Codegraph @

src/lib/QuattroSpreadsheet.cpp

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* libwps
3 * Version: MPL 2.0 / LGPLv2.1+
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * Major Contributor(s):
10 * Copyright (C) 2006, 2007 Andrew Ziem
11 * Copyright (C) 2004 Marc Maurer ([email protected])
12 * Copyright (C) 2004-2006 Fridrich Strba ([email protected])
13 *
14 * For minor contributions see the git repository.
15 *
16 * Alternatively, the contents of this file may be used under the terms
17 * of the GNU Lesser General Public License Version 2.1 or later
18 * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
19 * applicable instead of those above.
20 */
21
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include <algorithm>
26 #include <cctype>
27 #include <cmath>
28 #include <limits>
29 #include <set>
30 #include <string>
31 #include <sstream>
32 #include <stack>
33
34 #include <librevenge-stream/librevenge-stream.h>
35
36 #include "libwps_internal.h"
37 #include "libwps_tools_win.h"
38
39 #include "WPSCell.h"
40 #include "WKSContentListener.h"
41 #include "WPSEntry.h"
42 #include "WPSFont.h"
43 #include "WPSStream.h"
44 #include "WPSTable.h"
45
46 #include "Quattro.h"
47 #include "QuattroFormula.h"
48
49 #include "QuattroSpreadsheet.h"
50
51 namespace QuattroSpreadsheetInternal
52 {
53 //! a class used to store a style of a cell in QuattroSpreadsheet
54 struct Style final : public WPSCellFormat
55 {
56 //! construtor
57 explicit Style(libwps_tools_win::Font::Type type)
58 : WPSCellFormat()
59 , m_fontType(type)
60 , m_fileFormat(0xFF)
61 , m_alignAcrossColumn(false)
62 , m_extra("")
63 {
64 }
65 Style(Style const &)=default;
66 //! destructor
67 ~Style() final;
68 //! operator<<
69 friend std::ostream &operator<<(std::ostream &o, Style const &style);
70 //! operator==
71 bool operator==(Style const &st) const;
72 //! operator!=
73 bool operator!=(Style const &st) const
74 {
75 return !(*this==st);
76 }
77 //! font encoding type
78 libwps_tools_win::Font::Type m_fontType;
79 //! the file format
80 int m_fileFormat;
81 //! flag to know if we must align across column
82 bool m_alignAcrossColumn;
83 /** extra data */
84 std::string m_extra;
85 };
86
87 Style::~Style()
88 {
89 }
90
91 //! operator<<
92 std::ostream &operator<<(std::ostream &o, Style const &style)
93 {
94 o << static_cast<WPSCellFormat const &>(style) << ",";
95 if (style.m_fileFormat!=0xFF)
96 o << "format=" << std::hex << style.m_fileFormat << std::dec << ",";
97 if (style.m_extra.length())
98 o << "extra=[" << style.m_extra << "],";
99
100 return o;
101 }
102
103 bool Style::operator==(Style const &st) const
104 {
105 if (m_fontType!=st.m_fontType || m_fileFormat!=st.m_fileFormat) return false;
106 int diff = WPSCellFormat::compare(st);
107 if (diff) return false;
108 return m_alignAcrossColumn==st.m_alignAcrossColumn && m_extra==st.m_extra;
109 }
110
111 //! a cellule of a Quattro spreadsheet
112 class Cell final : public WPSCell
113 {
114 public:
115 /// constructor
116 explicit Cell(libwps_tools_win::Font::Type type)
117 : m_fontType(type)
118 , m_fileFormat(0xFF)
119 , m_styleId(-1)
120 , m_alignAcrossColumn(false)
121 , m_content()
122 , m_hasGraphic(false)
123 , m_stream() { }
124
125 //! operator<<
126 friend std::ostream &operator<<(std::ostream &o, Cell const &cell);
127
128 //! call when a cell must be send
129 bool send(WPSListenerPtr &/*listener*/) final;
130
131 //! call when the content of a cell must be send
132 bool sendContent(WPSListenerPtr &/*listener*/) final
133 {
134 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Cell::sendContent: must not be called\n"));
135 return false;
136 }
137 //! update the cell format using file format
138 void updateFormat()
139 {
140 if (m_fileFormat==0xFF)
141 return;
142 switch ((m_fileFormat>>4)&7)
143 {
144 case 0:
145 case 6: // checkme: date format set by system
146 switch (m_fileFormat&0xF)
147 {
148 case 1: // +/- : kind of bool
149 setFormat(F_BOOLEAN);
150 break;
151 case 2: // default
152 break;
153 case 3:
154 setFormat(F_TEXT);
155 break;
156 case 4:
157 setFormat(F_TEXT);
158 m_font.m_attributes |= WPS_HIDDEN_BIT;
159 break;
160 case 5:
161 setDTFormat(F_DATE, "%d %b %y");
162 break;
163 case 6:
164 setDTFormat(F_DATE, "%d %b");
165 break;
166 case 7:
167 setDTFormat(F_DATE, "%b-%d");
168 break;
169 case 8:
170 setDTFormat(F_DATE, "%m/%d/%y");
171 break;
172 case 9:
173 setDTFormat(F_DATE, "%m/%d");
174 break;
175 case 0xa:
176 setDTFormat(F_TIME, "%I:%M:%S%p");
177 break;
178 case 0xb:
179 setDTFormat(F_TIME, "%I:%M%p");
180 break;
181 case 0xc:
182 setDTFormat(F_TIME, "%H:%M:%S");
183 break;
184 case 0xd:
185 setDTFormat(F_TIME, "%H:%M");
186 break;
187 case 0xe:
188 setDTFormat(F_TIME, "%y");
189 break;
190 case 0xf:
191 setDTFormat(F_TIME, "%b");
192 break;
193 default:
194 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Cell::updateFormat: unknown format %x\n", unsigned(m_fileFormat)));
195 break;
196 }
197 break;
198 case 1: // fixed
199 setFormat(F_NUMBER, 1);
200 setDigits(m_fileFormat&0xF);
201 break;
202 case 2: // scientific
203 setFormat(F_NUMBER, 2);
204 setDigits(m_fileFormat&0xF);
205 break;
206 case 3: // currency
207 setFormat(F_NUMBER, 4);
208 setDigits(m_fileFormat&0xF);
209 break;
210 case 4: // percent
211 setFormat(F_NUMBER, 3);
212 setDigits(m_fileFormat&0xF);
213 break;
214 case 5: // decimal
215 setFormat(F_NUMBER, 1);
216 setDigits(m_fileFormat&0xF);
217 break;
218 case 7: // fixme use UserFormat (m_fileFormat&0xF) in Quattro.cpp at least to decode date...
219 {
220 static bool first=true;
221 if (first)
222 {
223 first=false;
224 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Cell::updateFormat: user defined format is not supported\n"));
225 }
226 break;
227 }
228 default:
229 break;
230 }
231 }
232 //! font encoding type
233 libwps_tools_win::Font::Type m_fontType;
234 //! the file format
235 int m_fileFormat;
236 //! the style id
237 int m_styleId;
238 //! flag to know if we must align across column
239 bool m_alignAcrossColumn;
240 //! the content
241 WKSContentListener::CellContent m_content;
242 //! a flag to know a cell has some graphic
243 bool m_hasGraphic;
244 //! the text stream(used to send text's zone)
245 std::shared_ptr<WPSStream> m_stream;
246 };
247 bool Cell::send(WPSListenerPtr &/*listener*/)
248 {
249 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Cell::send: must not be called\n"));
250 return false;
251 }
252
253 //! operator<<
254 std::ostream &operator<<(std::ostream &o, Cell const &cell)
255 {
256 o << reinterpret_cast<WPSCell const &>(cell) << cell.m_content << ",";
257 if (cell.m_fileFormat!=0xFF)
258 o << "format=" << std::hex << cell.m_fileFormat << std::dec << ",";
259 return o;
260 }
261
262 //! the spreadsheet of a Quattro Spreadsheet
263 class Spreadsheet
264 {
265 public:
266 //! a constructor
267 Spreadsheet(int id, libwps_tools_win::Font::Type fontType)
268 : m_id(id)
269 , m_numCols(0)
270 , m_rowHeightMap()
271 , m_heightDefault(13) // fixme: use zone d2
272 , m_widthCols()
273 , m_widthDefault(54) // fixme: use zone d4
274 , m_positionToCellMap()
275 , m_dummyCell(fontType)
276 {
277 }
278 //! return a cell corresponding to a spreadsheet, create one if needed
279 Cell &getCell(Vec2i const &pos, libwps_tools_win::Font::Type type)
280 {
281 if (m_positionToCellMap.find(pos)==m_positionToCellMap.end())
282 {
283 Cell cell(type);
284 cell.setPosition(pos);
285 if (pos[0]<0 || pos[0]>255)
286 {
287 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Spreadsheet::getCell: find unexpected col=%d\n", pos[0]));
288 return m_dummyCell;
289 }
290 m_positionToCellMap.insert(std::map<Vec2i, Cell>::value_type(pos,cell));
291 }
292 return m_positionToCellMap.find(pos)->second;
293 }
294 //! returns true if the spreedsheet is empty
295 bool empty() const
296 {
297 return m_positionToCellMap.empty();
298 }
299 //! set the columns size
300 void setColumnWidth(int col, int w=-1)
301 {
302 if (col < 0) return;
303 if (col >= int(m_widthCols.size())) m_widthCols.resize(size_t(col)+1, -1);
304 m_widthCols[size_t(col)] = w;
305 if (col >= m_numCols) m_numCols=col+1;
306 }
307
308 //! return the columns format
309 std::vector<WPSColumnFormat> getWidths() const
310 {
311 std::vector<WPSColumnFormat> widths;
312 WPSColumnFormat defWidth(m_widthDefault), actWidth;
313 defWidth.m_useOptimalWidth=true;
314 int repeat=0;
315 for (auto const &w : m_widthCols)
316 {
317 WPSColumnFormat newWidth;
318 if (w < 0)
319 newWidth=defWidth;
320 else
321 newWidth=WPSColumnFormat(float(w)/20.f);
322 if (repeat && newWidth!=actWidth)
323 {
324 actWidth.m_numRepeat=repeat;
325 widths.push_back(actWidth);
326 repeat=0;
327 }
328 if (repeat==0)
329 actWidth=newWidth;
330 ++repeat;
331 }
332 if (repeat)
333 {
334 actWidth.m_numRepeat=repeat;
335 widths.push_back(actWidth);
336 }
337 return widths;
338 }
339 //! set the rows size in TWIP
340 void setRowHeight(int row, int h)
341 {
342 auto rIt=m_rowHeightMap.lower_bound(Vec2i(-1,row));
343 if (rIt!=m_rowHeightMap.end() && rIt->first[0]<=row && rIt->first[1]>=row)
344 {
345 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Spreadsheet::setRowHeight: oops, row %d is already set\n", row));
346 return;
347 }
348 if (h>=0)
349 m_rowHeightMap[Vec2i(row,row)]=h;
350 }
351 //! set the rows size in TWIP
352 void setRowHeights(int minRow, int maxRow, int h)
353 {
354 auto rIt=m_rowHeightMap.lower_bound(Vec2i(-1,minRow));
355 while (rIt!=m_rowHeightMap.end())
356 {
357 auto const &cells=rIt->first;
358 if (cells[0]>maxRow) break;
359 if (cells[1]>=minRow)
360 {
361 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::Spreadsheet::setRowHeight: oops, some rows are already set in %dx%d\n", minRow, maxRow));
362 return;
363 }
364 ++rIt;
365 }
366 if (h>=0)
367 m_rowHeightMap[Vec2i(minRow,maxRow)]=h;
368 }
369 //! returns the row size in point
370 float getRowHeight(int row) const
371 {
372 auto rIt=m_rowHeightMap.lower_bound(Vec2i(-1,row));
373 if (rIt!=m_rowHeightMap.end() && rIt->first[0]<=row && rIt->first[1]>=row)
374 return float(rIt->second)/20.f;
375 return m_heightDefault;
376 }
377 //! returns the height of a row in point and updated repeated row
378 float getRowHeight(int row, int &numRepeated) const
379 {
380 auto rIt=m_rowHeightMap.lower_bound(Vec2i(-1,row));
381 if (rIt!=m_rowHeightMap.end() && rIt->first[0]<=row && rIt->first[1]>=row)
382 {
383 numRepeated=rIt->first[1]-row+1;
384 return float(rIt->second)/20.f;
385 }
386 numRepeated=10000;
387 return m_heightDefault;
388 }
389 //! try to compress the list of row height
390 void compressRowHeights()
391 {
392 auto oldMap=m_rowHeightMap;
393 m_rowHeightMap.clear();
394 int actHeight=-1;
395 Vec2i actPos(0,-1);
396 for (auto const &rIt : oldMap)
397 {
398 // first check for not filled row
399 if (rIt.first[0]!=actPos[1]+1)
400 {
401 if (actHeight==int(m_heightDefault)*20)
402 actPos[1]=rIt.first[0]-1;
403 else
404 {
405 if (actPos[1]>=actPos[0])
406 m_rowHeightMap[actPos]=actHeight;
407 actHeight=int(m_heightDefault)*20;
408 actPos=Vec2i(actPos[1]+1, rIt.first[0]-1);
409 }
410 }
411 if (rIt.second!=actHeight)
412 {
413 if (actPos[1]>=actPos[0])
414 m_rowHeightMap[actPos]=actHeight;
415 actPos[0]=rIt.first[0];
416 actHeight=rIt.second;
417 }
418 actPos[1]=rIt.first[1];
419 }
420 if (actPos[1]>=actPos[0])
421 m_rowHeightMap[actPos]=actHeight;
422 }
423 //! returns the cell position
424 Vec2f getPosition(Vec2i const &cell) const
425 {
426 float c=0;
427 int numWidth=int(m_widthCols.size());
428 for (int i=0; i<cell[0]; ++i)
429 {
430 if (i>=numWidth)
431 {
432 c+=float(i+1-numWidth)*m_widthDefault;
433 break;
434 }
435 int w=m_widthCols[size_t(i)];
436 if (w < 0)
437 c+=m_widthDefault;
438 else
439 c+=float(w)/20.f;
440 }
441 int r=0, prevR=0;
442 for (auto const &it : m_rowHeightMap)
443 {
444 int maxR=std::min(it.first[1],cell[1]-1);
445 if (prevR<it.first[0])
446 {
447 r+=(maxR-prevR)*int(m_heightDefault)*20;
448 prevR=maxR;
449 }
450 if (maxR<it.first[0])
451 break;
452 r+=(maxR+1-it.first[0])*it.second;
453 prevR=maxR;
454 }
455 if (prevR<cell[1]) r+=(cell[1]-prevR)*int(m_heightDefault)*20;
456 return Vec2f(c,float(r/20));
457 }
458 //! the spreadsheet id
459 int m_id;
460 /** the number of columns */
461 int m_numCols;
462
463 /** the map Vec2i(min row, max row) to size in TWIP */
464 std::map<Vec2i,int> m_rowHeightMap;
465 /** the default row size in point */
466 float m_heightDefault;
467 /** the column size in TWIP */
468 std::vector<int> m_widthCols;
469 /** the default width size in point */
470 float m_widthDefault;
471 /** a map cell to not empty cells */
472 std::map<Vec2i, Cell> m_positionToCellMap;
473 /** a dummy cell */
474 mutable Cell m_dummyCell;
475 };
476
477 //! the state of QuattroSpreadsheet
478 struct State
479 {
480 //! constructor
481 explicit State(QuattroFormulaManager::CellReferenceFunction const &readCellReference)
482 : m_version(-1)
483 , m_maxDimension(0,0,0)
484 , m_actSheet(-1)
485 , m_stylesList()
486 , m_formulaManager(readCellReference, 1)
487 , m_spreadsheetMap()
488 , m_idToSheetNameMap()
489 , m_sheetNameSet()
490 , m_idToUserFormatMap()
491 {
492 }
493 //! returns the ith real spreadsheet
494 std::shared_ptr<Spreadsheet> getSheet(int id, libwps_tools_win::Font::Type fontType)
495 {
496 auto it=m_spreadsheetMap.find(id);
497 if (it!=m_spreadsheetMap.end())
498 return it->second;
499 std::shared_ptr<Spreadsheet> sheet(new Spreadsheet(id, fontType));
500 sheet->setColumnWidth(m_maxDimension[0]);
501 if (id<0 || id>m_maxDimension[2])
502 {
503 WPS_DEBUG_MSG(("QuattroSpreadsheetInternal::State::getSheet: find unexpected id=%d\n", id));
504 if (id<0 || id>255) // too small or too big, return dummy spreadsheet
505 return sheet;
506 }
507 m_spreadsheetMap[id]=sheet;
508 return sheet;
509 }
510 //! returns the ith spreadsheet
511 librevenge::RVNGString getSheetName(int id)
512 {
513 auto it = m_idToSheetNameMap.find(id);
514 if (it!=m_idToSheetNameMap.end() && !it->second.empty())
515 return it->second;
516 librevenge::RVNGString name;
517 name.sprintf("Sheet%d", id+1);
518 name=getUniqueSheetName(name);
519 m_idToSheetNameMap[id]=name;
520 return name;
521 }
522 //! returns a unique sheet name build using the current name
523 librevenge::RVNGString getUniqueSheetName(librevenge::RVNGString const &name)
524 {
525 if (m_sheetNameSet.find(name)==m_sheetNameSet.end())
526 {
527 m_sheetNameSet.insert(name);
528 return name;
529 }
530 int i=0;
531 while (i<1000)
532 {
533 librevenge::RVNGString uniqueName(name);
534 uniqueName.append((std::string("_")+std::to_string(i++)).c_str());
535 if (m_sheetNameSet.find(uniqueName)==m_sheetNameSet.end())
536 {
537 m_sheetNameSet.insert(uniqueName);
538 return uniqueName;
539 }
540 }
541 return name;
542 }
543 //! the file version
544 int m_version;
545 //! the maximum col, row, sheet
546 WPSVec3i m_maxDimension;
547 //! the actual sheet
548 int m_actSheet;
549 //! the list of styles
550 std::vector<Style> m_stylesList;
551 //! the formula manager
552 QuattroFormulaManager m_formulaManager;
553
554 //! the map of spreadsheet
555 std::map<int, std::shared_ptr<Spreadsheet> > m_spreadsheetMap;
556 //! the map id to sheet's name
557 std::map<int, librevenge::RVNGString> m_idToSheetNameMap;
558 //! the set of used sheet name
559 std::set<librevenge::RVNGString> m_sheetNameSet;
560 //! map id to user format string
561 std::map<int, librevenge::RVNGString> m_idToUserFormatMap;
562 };
563
564 }
565
566 // constructor, destructor
567 QuattroSpreadsheet::QuattroSpreadsheet(QuattroParser &parser)
568 : m_listener()
569 , m_mainParser(parser)
570 , m_state()
571 {
572 m_state.reset(new QuattroSpreadsheetInternal::State(getReadCellReferenceFunction()));
573 }
574
575 QuattroSpreadsheet::~QuattroSpreadsheet()
576 {
577 }
578
579 void QuattroSpreadsheet::cleanState()
580 {
581 m_state.reset(new QuattroSpreadsheetInternal::State(getReadCellReferenceFunction()));
582 }
583
584 void QuattroSpreadsheet::updateState()
585 {
586 }
587
588 int QuattroSpreadsheet::version() const
589 {
590 if (m_state->m_version<0)
591 m_state->m_version=m_mainParser.version();
592 return m_state->m_version;
593 }
594
595 QuattroFormulaManager::CellReferenceFunction QuattroSpreadsheet::getReadCellReferenceFunction()
596 {
597 return [this](std::shared_ptr<WPSStream> const &stream, long endPos,
598 QuattroFormulaInternal::CellReference &ref,
599 Vec2i const &pos, int sheetId)
600 {
601 return this->readCellReference(stream, endPos, ref, pos, sheetId);
602 };
603 }
604
605 int QuattroSpreadsheet::getNumSpreadsheets() const
606 {
607 if (m_state->m_spreadsheetMap.empty())
608 return m_state->m_maxDimension[2]+1;
609 auto it=m_state->m_spreadsheetMap.end();
610 --it;
611 return std::max(it->first,m_state->m_maxDimension[2])+1;
612 }
613
614 librevenge::RVNGString QuattroSpreadsheet::getSheetName(int id) const
615 {
616 return m_state->getSheetName(id);
617 }
618
619 Vec2f QuattroSpreadsheet::getPosition(int sheetId, Vec2i const &cell) const
620 {
621 auto it=m_state->m_spreadsheetMap.find(sheetId);
622 if (it==m_state->m_spreadsheetMap.end() || !it->second)
623 {
624 WPS_DEBUG_MSG(("QuattroSpreadsheet::getPosition: can not find the sheet %d\n", sheetId));
625 return Vec2f(float(cell[0]*50), float(cell[1]*13));
626 }
627 return it->second->getPosition(cell);
628 }
629
630 void QuattroSpreadsheet::addDLLIdName(int id, librevenge::RVNGString const &name, bool func1)
631 {
632 m_state->m_formulaManager.addDLLIdName(id, name, func1);
633 }
634
635 void QuattroSpreadsheet::addUserFormat(int id, librevenge::RVNGString const &name)
636 {
637 if (name.empty())
638 {
639 WPS_DEBUG_MSG(("QuattroSpreadsheet::addUserFormat: called with empty name for id=%d\n", id));
640 return;
641 }
642 if (m_state->m_idToUserFormatMap.find(id)!=m_state->m_idToUserFormatMap.end())
643 {
644 WPS_DEBUG_MSG(("QuattroSpreadsheet::addUserFormat: called with dupplicated id=%d\n", id));
645 }
646 else
647 m_state->m_idToUserFormatMap[id]=name;
648 }
649
650 ////////////////////////////////////////////////////////////
651 // low level
652
653 ////////////////////////////////////////////////////////////
654 // parse sheet data
655 ////////////////////////////////////////////////////////////
656 bool QuattroSpreadsheet::readCell(std::shared_ptr<WPSStream> const &stream)
657 {
658 RVNGInputStreamPtr input = stream->m_input;
659 libwps::DebugFile &ascFile=stream->m_ascii;
660 libwps::DebugStream f;
661
662 long pos = input->tell();
663 auto type = long(libwps::readU16(input)&0x7fff);
664 if ((type < 0xc || type > 0x10) && (type!=0x33))
665 {
666 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: not a cell property\n"));
667 return false;
668 }
669 long sz = libwps::readU16(input);
670 long endPos = pos+4+sz;
671
672 if (sz < 5)
673 {
674 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: cell def is too short\n"));
675 return false;
676 }
677 int cellPos[2];
678 cellPos[0]=int(libwps::readU8(input));
679 auto sheetId=int(libwps::readU8(input));
680 cellPos[1]=int(libwps::read16(input));
681 if (cellPos[1] < 0)
682 {
683 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: cell pos is bad\n"));
684 return false;
685 }
686 if (sheetId)
687 f << "sheet[id]=" << sheetId << ",";
688
689 auto defFontType=m_mainParser.getDefaultFontType();
690 auto sheet = m_state->getSheet(sheetId, defFontType);
691 auto &cell=sheet->getCell(Vec2i(cellPos[0],cellPos[1]), defFontType);
692 auto format=int(libwps::readU16(input));
693 int id=format>>3;
694 // format&7: reserved
695 if (id<0 || id>int(m_state->m_stylesList.size()))
696 {
697 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: can not find cell format\n"));
698 f << "###Ce" << id << ",";
699 }
700 else if (id)
701 {
702 auto const &style=m_state->m_stylesList[size_t(id-1)];
703 if (type!=0x33)
704 {
705 cell.m_styleId=id-1;
706 cell.m_fileFormat=style.m_fileFormat;
707 cell.m_fontType=style.m_fontType;
708 static_cast<WPSCellFormat &>(cell)=style;
709 cell.m_alignAcrossColumn=style.m_alignAcrossColumn;
710 }
711 f << "Ce" << id-1 << ",";
712 }
713
714 long dataPos = input->tell();
715 auto dataSz = int(endPos-dataPos);
716
717 bool ok = true;
718 switch (type)
719 {
720 case 12:
721 {
722 if (dataSz == 0)
723 {
724 cell.m_content.m_contentType=WKSContentListener::CellContent::C_NONE;
725 break;
726 }
727 ok = false;
728 break;
729 }
730 case 13:
731 {
732 if (dataSz == 2)
733 {
734 cell.m_content.m_contentType=WKSContentListener::CellContent::C_NUMBER;
735 cell.m_content.setValue(libwps::read16(input));
736 break;
737 }
738 ok = false;
739 break;
740 }
741 case 14:
742 {
743 double val;
744 bool isNaN;
745 if (dataSz == 8 && libwps::readDouble8(input, val, isNaN))
746 {
747 cell.m_content.m_contentType=WKSContentListener::CellContent::C_NUMBER;
748 cell.m_content.setValue(val);
749 break;
750 }
751 ok = false;
752 break;
753 }
754 case 15:
755 cell.m_content.m_contentType=WKSContentListener::CellContent::C_TEXT;
756 WPS_FALLTHROUGH;
757 case 0x33: // formula res
758 {
759 long begText=input->tell()+1;
760 // align + c string
761 auto align=char(libwps::readU8(input));
762 if (align=='\'') cell.setHAlignment(WPSCellFormat::HALIGN_DEFAULT);
763 else if (align=='^') cell.setHAlignment(WPSCellFormat::HALIGN_CENTER);
764 else if (align=='\"') cell.setHAlignment(WPSCellFormat::HALIGN_RIGHT);
765 else if (align=='\\') f << "repeat,"; // USEME
766 else if (align==0x7c) f << "break,"; // FIXME remove "::" in text
767 else if (align) f << "#align=" << int(align) << ",";
768
769 librevenge::RVNGString text("");
770 if (!m_mainParser.readCString(stream,text,dataSz-1))
771 f << "##sSz,";
772 else
773 {
774 if (endPos!=input->tell() && endPos!=input->tell()+1)
775 {
776 f << "#extra,";
777 ascFile.addDelimiter(input->tell(), '|');
778 }
779 cell.m_stream=stream;
780 cell.m_content.m_textEntry.setBegin(begText);
781 cell.m_content.m_textEntry.setEnd(input->tell()-1);
782 if (!text.empty())
783 f << text.cstr() << ",";
784 }
785 break;
786 }
787 case 16:
788 {
789 double val;
790 bool isNaN;
791 if (dataSz >= 10 && libwps::readDouble8(input, val, isNaN))
792 {
793 cell.m_content.m_contentType=WKSContentListener::CellContent::C_FORMULA;
794 cell.m_content.setValue(val);
795 auto state=int(libwps::readU16(input));
796 if (state)
797 {
798 f << "state[";
799 if (state&0x8) f << "constant,";
800 if (state==0x10) f << "volatile,";
801 if (state==0x100) f << "inArray,";
802 if (state==0x200) f << "useDLL,";
803 if (state&0xfcf3) f << "#state=" << std::hex << (state&0xfcf3) << std::dec << ",";
804 f << "],";
805 }
806 std::string error;
807 if (!m_state->m_formulaManager.readFormula(stream, endPos, cell.position(), sheetId, cell.m_content.m_formula, error))
808 {
809 cell.m_content.m_contentType=WKSContentListener::CellContent::C_NUMBER;
810 ascFile.addDelimiter(input->tell()-1, '#');
811 }
812 if (error.length()) f << error;
813 break;
814 }
815 ok = false;
816 break;
817 }
818 default:
819 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: unknown type=%ld\n", type));
820 ok = false;
821 break;
822 }
823 if (!ok) ascFile.addDelimiter(dataPos, '#');
824
825 input->seek(pos+sz, librevenge::RVNG_SEEK_SET);
826
827 std::string extra=f.str();
828 f.str("");
829 f << cell << "," << extra;
830
831 ascFile.addPos(pos);
832 ascFile.addNote(f.str().c_str());
833
834 return true;
835 }
836
837 bool QuattroSpreadsheet::readCellStyle(std::shared_ptr<WPSStream> const &stream)
838 {
839 RVNGInputStreamPtr input = stream->m_input;
840 libwps::DebugFile &ascFile=stream->m_ascii;
841 libwps::DebugStream f;
842 long pos = input->tell();
843 auto type = long(libwps::readU16(input)&0x7fff);
844 if (type != 0xce)
845 {
846 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellStyle: not a style zone\n"));
847 return false;
848 }
849 long sz = libwps::readU16(input);
850 f << "[Ce" << m_state->m_stylesList.size() << "],";
851 QuattroSpreadsheetInternal::Style style(m_mainParser.getDefaultFontType());
852 if (sz<8)
853 {
854 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellStyle: size seems bad\n"));
855 f << "###";
856 ascFile.addPos(pos);
857 ascFile.addNote(f.str().c_str());
858 m_state->m_stylesList.push_back(style);
859 return true;
860 }
861 style.m_fileFormat=int(libwps::readU8(input));
862 if (style.m_fileFormat!=0xFF)
863 f << "form=" << std::hex << style.m_fileFormat << std::dec << ",";
864 auto flag=int(libwps::readU8(input));
865 switch (flag&7)
866 {
867 case 1:
868 style.setHAlignment(WPSCellFormat::HALIGN_LEFT);
869 f << "left,";
870 break;
871 case 2:
872 style.setHAlignment(WPSCellFormat::HALIGN_CENTER);
873 f << "center,";
874 break;
875 case 3:
876 style.setHAlignment(WPSCellFormat::HALIGN_RIGHT);
877 f << "right,";
878 break;
879 case 4:
880 style.setHAlignment(WPSCellFormat::HALIGN_FULL);
881 f << "block,";
882 break;
883 case 6:
884 {
885 style.setHAlignment(WPSCellFormat::HALIGN_CENTER);
886 style.m_alignAcrossColumn=true;
887 f << "center[across],";
888 break;
889 }
890 default:
891 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellStyle: find unexpected alignment\n"));
892 f << "###align=" << (flag&7) << ",";
893 break;
894 case 0: // standart
895 break;
896 }
897 if (sz>=12)
898 {
899 switch ((flag>>3)&3)
900 {
901 case 0: // default
902 style.setVAlignment(WPSCellFormat::VALIGN_BOTTOM);
903 break;
904 case 1:
905 style.setVAlignment(WPSCellFormat::VALIGN_CENTER);
906 f << "vAlign=center,";
907 break;
908 case 2:
909 style.setVAlignment(WPSCellFormat::VALIGN_TOP);
910 f << "vAlign=top,";
911 break;
912 default:
913 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellStyle: find unexpected alignment\n"));
914 f << "###valign=3,";
915 break;
916 }
917 if (flag&0x20)
918 {
919 style.setTextRotation(270);
920 f << "top[down],";
921 }
922 if (flag&0x80)
923 {
924 style.setWrapping(WPSCellFormat::WRAP_WRAP);
925 f << "wrap,";
926 }
927 flag &= 0x40;
928 }
929 else
930 {
931 switch ((flag>>6)&3) // checkme, maybe diferent in wb2, ie. I find difference with qprostyle.cpp
932 {
933 default:
934 case 0: // standart
935 break;
936 case 1:
937 f << "label[only],";
938 break;
939 case 2:
940 f << "date[only],";
941 break;
942 case 3:
943 f << "##input=3,";
944 break;
945 }
946 flag&=0x38;
947 }
948 if (flag)
949 f << "#fl=" << std::hex << flag << std::dec << ",";
950 auto val=int(libwps::readU8(input));
951 int color[3]= {val>>4, val&0xf, 0}; // col2: shade, col1: shade, textcolor
952 val=int(libwps::readU8(input));
953 color[2]=val>>4;
954 int blend=(val&0x7);
955 WPSColor colors[]= {WPSColor::white(), WPSColor::black(), WPSColor::black()};
956 for (int i=0; i<3; ++i)
957 {
958 int const expected[]= {0,3,3};
959 if (color[i]==expected[i]) continue;
960 if (m_mainParser.getColor(color[i], colors[i]))
961 f << "color" << i << "=" << colors[i] << ",";
962 else
963 f << "##color" << i << "=" << color[i] << ",";
964 }
965 if (blend==7)
966 f << "###blend=7,";
967 else
968 {
969 int const percent[]= {0,6,3,1,2,5,4};
970 float fPercent=float(percent[blend])/6.f;
971 if (blend)
972 f << "blend=" << 100.f *fPercent << "%,";
973 style.setBackgroundColor(WPSColor::barycenter(fPercent,colors[1],1.f-fPercent,colors[0]));
974 // percent col2 + (1-percent) col1
975 }
976 if (val&8) f << "fl[8],";
977 auto fId=int(libwps::readU8(input));
978 WPSFont font;
979 if (fId)
980 {
981 if (!m_mainParser.getFont(fId-1, font, style.m_fontType))
982 f << "###";
983 f << "F" << fId-1 << ",";
984 }
985 font.m_color=colors[2];
986 style.setFont(font);
987 auto bFlags=int(libwps::readU8(input));
988 // 80:has[textColor], 40:has[protect], 20:has[borders], 10:has[fonts], 8:has[color], 4:[hasAlign], 2:[hasForm], 1:[hasProtect+0x40?]...
989 val=int(libwps::readU8(input));
990 val &= 0x41;
991 if (val==0x41)
992 f << "protect=no,";
993 else if (val) f << "fl2=" << std::hex << val << std::dec << ",";
994 val=int(libwps::readU8(input)); // USEME
995 if (val) f << "style[id]=" << val << ",";
996 WPSColor borderColors[4];
997 for (auto &c : borderColors) c=WPSColor::black();
998 if (sz>=12) // sz=12, pre-wb2, wb2?
999 {
1000 f << "borders[color]=[";
1001 for (int i=0; i<2; ++i)
1002 {
1003 val=int(libwps::readU8(input));
1004 for (int j=0; j<2; ++j)
1005 {
1006 int c=j==1 ? (val>>4) : (val&0xf);
1007 if (!m_mainParser.getColor(c, borderColors[2*i+j]))
1008 f << "##color=" << c << ",";
1009 else if (borderColors[2*i+j].isBlack())
1010 f << "_,";
1011 else
1012 f << borderColors[2*i+j] << ",";
1013 }
1014 }
1015 f << "],";
1016 val=int(libwps::readU16(input));
1017 switch (val&3)
1018 {
1019 default:
1020 case 0: // standart
1021 break;
1022 case 1:
1023 f << "label[only],";
1024 break;
1025 case 2:
1026 f << "date[only],";
1027 break;
1028 case 3:
1029 f << "##input=3,";
1030 break;
1031 }
1032 if (val&4) f << "use[lineColor],"; // or page color
1033 val&=0xfff8;
1034 if (val) f << "fl3=" << val << ",";
1035 }
1036 if (bFlags)
1037 {
1038 f << "borders=[";
1039 for (int i=0, depl=0; i<4; ++i, depl+=2) // BRTL
1040 {
1041 int bType=(bFlags>>depl)&3;
1042 if (!bType) continue;
1043 char const *wh[]= {"L","T","R","B"};
1044 WPSBorder border;
1045 switch (bType)
1046 {
1047 case 1: // normal
1048 f << wh[i] << ",";
1049 break;
1050 case 2: // double
1051 border.m_type=WPSBorder::Double;
1052 f << wh[i] << "=double,";
1053 break;
1054 case 3: // width*2
1055 border.m_width=2;
1056 f << wh[i] << "=w2,";
1057 break;
1058 default: // impossible
1059 break;
1060 }
1061 border.m_color=borderColors[i];
1062 int const which[]= {WPSBorder::LeftBit, WPSBorder::TopBit, WPSBorder::RightBit, WPSBorder::BottomBit};
1063 style.setBorders(which[i], border);
1064 }
1065 f << "],";
1066 }
1067 m_state->m_stylesList.push_back(style);
1068 ascFile.addPos(pos);
1069 ascFile.addNote(f.str().c_str());
1070 return true;
1071 }
1072
1073 bool QuattroSpreadsheet::readSheetSize(std::shared_ptr<WPSStream> const &stream)
1074 {
1075 RVNGInputStreamPtr input = stream->m_input;
1076 libwps::DebugFile &ascFile=stream->m_ascii;
1077 libwps::DebugStream f;
1078 long pos = input->tell();
1079 auto type = long(libwps::readU16(input)&0x7fff);
1080 if (type != 0x6)
1081 {
1082 WPS_DEBUG_MSG(("QuattroSpreadsheet::readSheetSize: not a sheet zone\n"));
1083 return false;
1084 }
1085 long sz = libwps::readU16(input);
1086 if (sz < 8)
1087 {
1088 WPS_DEBUG_MSG(("QuattroSpreadsheet::readSheetSize: block is too short\n"));
1089 return false;
1090 }
1091 bool ok=true;
1092 for (int i = 0; i < 2; i++) // min can be invalid if the file is an extract file
1093 {
1094 f << (i==0 ? "min": "max") << "=[";
1095 int nCol = int(libwps::readU8(input))+1;
1096 f << "col=" << nCol << ",";
1097 auto nSheet = int(libwps::readU8(input));
1098 int nRow = libwps::read16(input);
1099 f << "row=" << nRow << ",";
1100 if (nSheet)
1101 f << "sheet=" << nSheet << ",";
1102 f << "],";
1103 if (i==0)
1104 continue;
1105 m_state->m_maxDimension=WPSVec3i(nCol,nRow,nSheet);
1106 if (nRow<0)
1107 ok=(nRow==-1 && nCol==1); // empty spreadsheet
1108 }
1109 ascFile.addPos(pos);
1110 ascFile.addNote(f.str().c_str());
1111 return ok;
1112 }
1113
1114 bool QuattroSpreadsheet::readColumnRowDefaultSize(std::shared_ptr<WPSStream> const &stream)
1115 {
1116 RVNGInputStreamPtr input = stream->m_input;
1117 libwps::DebugFile &ascFile=stream->m_ascii;
1118 libwps::DebugStream f;
1119 long pos = input->tell();
1120 auto type = long(libwps::readU16(input)&0x7fff);
1121 if (type < 0xd2 || type > 0xd5)
1122 {
1123 WPS_DEBUG_MSG(("QuattroSpreadsheet::readColumnRowDefaultSize: not a column size zone\n"));
1124 return false;
1125 }
1126 long sz = libwps::readU16(input);
1127 if (sz != 2)
1128 {
1129 WPS_DEBUG_MSG(("QuattroSpreadsheet::readColumnRowDefaultSize: block is too short\n"));
1130 return false;
1131 }
1132 int val=int(libwps::readU16(input));
1133 if (val&0x8000)
1134 {
1135 f << "user,";
1136 val &= 0x7fff;
1137 }
1138 f << float(val)/20.f << ",";
1139 if (type==0xd2 || type==0xd4)
1140 {
1141 auto defFontType=m_mainParser.getDefaultFontType();
1142 auto sheet=m_state->getSheet(m_state->m_actSheet, defFontType);
1143 if (type==0xd2)
1144 sheet->m_heightDefault=float(val)/20.f;
1145 else
1146 sheet->m_widthDefault=float(val)/20.f;
1147 }
1148
1149 ascFile.addPos(pos);
1150 ascFile.addNote(f.str().c_str());
1151 return true;
1152 }
1153
1154 bool QuattroSpreadsheet::readColumnSize(std::shared_ptr<WPSStream> const &stream)
1155 {
1156 RVNGInputStreamPtr input = stream->m_input;
1157 libwps::DebugFile &ascFile=stream->m_ascii;
1158 libwps::DebugStream f;
1159 long pos = input->tell();
1160 auto type = long(libwps::readU16(input)&0x7fff);
1161 if (type != 0xd8 && type != 0xd9)
1162 {
1163 WPS_DEBUG_MSG(("QuattroSpreadsheet::readColumnSize: not a column size zone\n"));
1164 return false;
1165 }
1166 long sz = libwps::readU16(input);
1167 if (sz < 4)
1168 {
1169 WPS_DEBUG_MSG(("QuattroSpreadsheet::readColumnSize: block is too short\n"));
1170 return false;
1171 }
1172
1173 int col = libwps::read16(input);
1174 int width = libwps::readU16(input);
1175
1176 auto defFontType=m_mainParser.getDefaultFontType();
1177 auto sheet=m_state->getSheet(m_state->m_actSheet, defFontType);
1178 bool ok = col >= 0 && col < sheet->m_numCols+10;
1179 f << "Col" << col << ":";
1180 if (width&0x8000)
1181 {
1182 f << "user,";
1183 width &= 0x7fff;
1184 }
1185 f << "width=" << float(width)/72.f << ",";
1186 if (ok && type==0xd8)
1187 {
1188 if (col >= sheet->m_numCols)
1189 {
1190 static bool first = true;
1191 if (first)
1192 {
1193 first = false;
1194 WPS_DEBUG_MSG(("QuattroSpreadsheet::readColumnSize: I must increase the number of columns\n"));
1195 }
1196 f << "#col[inc],";
1197 }
1198 sheet->setColumnWidth(col, width);
1199 }
1200 else if (col>256 && type==0xd8)
1201 f << "###,";
1202 ascFile.addPos(pos);
1203 ascFile.addNote(f.str().c_str());
1204
1205 return true;
1206 }
1207
1208 bool QuattroSpreadsheet::readRowSize(std::shared_ptr<WPSStream> const &stream)
1209 {
1210 RVNGInputStreamPtr input = stream->m_input;
1211 libwps::DebugFile &ascFile=stream->m_ascii;
1212 libwps::DebugStream f;
1213 long pos = input->tell();
1214 auto type = long(libwps::readU16(input)&0x7fff);
1215 if (type != 0xd6 && type != 0xd7)
1216 {
1217 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowSize: not a row size zone\n"));
1218 return false;
1219 }
1220 long sz = libwps::readU16(input);
1221 if (sz != 4)
1222 {
1223 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowSize: block is too short\n"));
1224 return false;
1225 }
1226
1227 int row = libwps::read16(input);
1228 int height = libwps::readU16(input);
1229
1230 f << "Row" << row << ",";
1231 if (height&0x8000) // maybe set by hand?
1232 {
1233 f << "user,";
1234 height &= 0x7fff;
1235 }
1236 f << "h=" << float(height)/20.f << ",";
1237 if (type==0xd6)
1238 {
1239 if (row>=0 && m_state->m_actSheet>=0)
1240 {
1241 auto defFontType=m_mainParser.getDefaultFontType();
1242 m_state->getSheet(m_state->m_actSheet, defFontType)->setRowHeight(row, height);
1243 }
1244 else
1245 {
1246 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowSize: can not find the current sheet\n"));
1247 f << "###";
1248 }
1249 }
1250
1251 ascFile.addPos(pos);
1252 ascFile.addNote(f.str().c_str());
1253
1254 return true;
1255 }
1256
1257 bool QuattroSpreadsheet::readRowRangeSize(std::shared_ptr<WPSStream> const &stream)
1258 {
1259 RVNGInputStreamPtr input = stream->m_input;
1260 libwps::DebugFile &ascFile=stream->m_ascii;
1261 libwps::DebugStream f;
1262 long pos = input->tell();
1263 auto type = long(libwps::readU16(input)&0x7fff);
1264 if (type != 0x105 && type != 0x106)
1265 {
1266 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowRangeSize: not a row size zone\n"));
1267 return false;
1268 }
1269 long sz = libwps::readU16(input);
1270 if (sz != 6)
1271 {
1272 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowRangeSize: block is too short\n"));
1273 return false;
1274 }
1275
1276 int minRow = libwps::read16(input);
1277 int maxRow = libwps::read16(input);
1278 int height = libwps::readU16(input);
1279
1280 f << "Row" << minRow << "<->R" << maxRow << ",";
1281 if (height&0x8000) // maybe set by hand?
1282 {
1283 f << "user,";
1284 height &= 0x7fff;
1285 }
1286 f << "h=" << float(height)/20.f << ",";
1287 if (type==0x105)
1288 {
1289 if (minRow>=0 && minRow<=maxRow && m_state->m_actSheet>=0)
1290 {
1291 auto defFontType=m_mainParser.getDefaultFontType();
1292 m_state->getSheet(m_state->m_actSheet, defFontType)->setRowHeights(minRow, maxRow, height);
1293 }
1294 else
1295 {
1296 WPS_DEBUG_MSG(("QuattroSpreadsheet::readRowSize: can not find the current sheet\n"));
1297 f << "###";
1298 }
1299 }
1300
1301 ascFile.addPos(pos);
1302 ascFile.addNote(f.str().c_str());
1303
1304 return true;
1305 }
1306
1307 ////////////////////////////////////////////////////////////
1308 // general
1309 ////////////////////////////////////////////////////////////
1310 bool QuattroSpreadsheet::readBeginEndSheet(std::shared_ptr<WPSStream> const &stream, int &sheetId)
1311 {
1312 RVNGInputStreamPtr input = stream->m_input;
1313 libwps::DebugFile &ascFile=stream->m_ascii;
1314 libwps::DebugStream f;
1315
1316 long pos = input->tell();
1317 auto type = long(libwps::readU16(input)&0x7fff);
1318 if (type != 0xca && type != 0xcb)
1319 {
1320 WPS_DEBUG_MSG(("QuattroSpreadsheet::readBeginEndSheet: not a zoneB type\n"));
1321 return false;
1322 }
1323 auto sz = long(libwps::readU16(input));
1324 if (sz != 1)
1325 {
1326 WPS_DEBUG_MSG(("QuattroSpreadsheet::readBeginEndSheet: size seems bad\n"));
1327 f << "###";
1328 ascFile.addPos(pos);
1329 ascFile.addNote(f.str().c_str());
1330 return true;
1331 }
1332 auto sheet=int(libwps::readU8(input));
1333 f << "sheet=" << sheet << ",";
1334 if (type==0xca)
1335 {
1336 if (m_state->m_actSheet>=0)
1337 {
1338 WPS_DEBUG_MSG(("QuattroSpreadsheet::readBeginEndSheet: oops, does not find the previous end\n"));
1339 f << "###";
1340 }
1341 sheetId=m_state->m_actSheet=sheet;
1342 }
1343 else
1344 {
1345 if (m_state->m_actSheet!=sheet)
1346 {
1347 WPS_DEBUG_MSG(("QuattroSpreadsheet::readBeginEndSheet: oops, end sheet id does not match with begin sheet id\n"));
1348 f << "###";
1349 }
1350 sheetId=m_state->m_actSheet=-1;
1351 }
1352 ascFile.addPos(pos);
1353 ascFile.addNote(f.str().c_str());
1354 return true;
1355 }
1356
1357 bool QuattroSpreadsheet::readSheetName(std::shared_ptr<WPSStream> const &stream)
1358 {
1359 RVNGInputStreamPtr input = stream->m_input;
1360 libwps::DebugFile &ascFile=stream->m_ascii;
1361 libwps::DebugStream f;
1362
1363 long pos = input->tell();
1364 auto type = long(libwps::readU16(input)&0x7fff);
1365 if (type != 0xcc)
1366 {
1367 WPS_DEBUG_MSG(("QuattroSpreadsheet::readSheetName: not a zoneB type\n"));
1368 return false;
1369 }
1370 auto sz = long(libwps::readU16(input));
1371 if (sz < 1)
1372 {
1373 WPS_DEBUG_MSG(("QuattroSpreadsheet::readSheetName: size seems bad\n"));
1374 f << "###";
1375 ascFile.addPos(pos);
1376 ascFile.addNote(f.str().c_str());
1377 return true;
1378 }
1379 librevenge::RVNGString name;
1380 if (!m_mainParser.readCString(stream,name,sz) || name.empty())
1381 f << "###";
1382 else
1383 {
1384 f << name.cstr() << ",";
1385 if (m_state->m_idToSheetNameMap.find(m_state->m_actSheet)!=m_state->m_idToSheetNameMap.end())
1386 {
1387 WPS_DEBUG_MSG(("QuattroSpreadsheet::readSheetName: id dupplicated\n"));
1388 f << "###id";
1389 }
1390 else
1391 m_state->m_idToSheetNameMap[m_state->m_actSheet]=m_state->getUniqueSheetName(name);
1392 }
1393 ascFile.addPos(pos);
1394 ascFile.addNote(f.str().c_str());
1395 return true;
1396 }
1397
1398 bool QuattroSpreadsheet::readViewInfo(std::shared_ptr<WPSStream> const &stream)
1399 {
1400 RVNGInputStreamPtr input = stream->m_input;
1401 libwps::DebugFile &ascFile=stream->m_ascii;
1402 libwps::DebugStream f;
1403 long pos = input->tell();
1404 auto type = long(libwps::readU16(input)&0x7fff);
1405 if (type != 0x197 && type !=0x198)
1406 {
1407 WPS_DEBUG_MSG(("QuattroSpreadsheet::readViewInfo: not a sheet zone\n"));
1408 return false;
1409 }
1410 long sz = libwps::readU16(input);
1411 long endPos=pos+4+sz;
1412 if (sz < 21)
1413 {
1414 WPS_DEBUG_MSG(("QuattroSpreadsheet::readViewInfo: block is too short\n"));
1415 return false;
1416 }
1417 auto id=int(libwps::read8(input));
1418 f << "id=" << id << ",";
1419
1420 int val = libwps::readU16(input); // 0|1|3|f
1421 f << "show=[";
1422 if (val&1) f << "rowHeading,";
1423 if (val&2) f << "colHeading,";
1424 if (val&4) f << "horiGrid,";
1425 if (val&8) f << "vertGrid,";
1426 // val&0x10: reserved
1427 val &=0xfff0;
1428 if (val)
1429 f << "f0=" << std::hex << val << std::dec << ",";
1430 f << "],";
1431 f << "range=";
1432 for (int i=0; i<2; ++i)
1433 {
1434 f << "C" << int(libwps::readU8(input));
1435 f << "S" << int(libwps::readU8(input));
1436 f << "R" << int(libwps::readU16(input));
1437 f << (i==0 ? "<->" : ",");
1438 }
1439 val = libwps::readU16(input);
1440 switch (val)
1441 {
1442 case 0: // default
1443 break;
1444 case 1:
1445 f << "title[hori],";
1446 break;
1447 case 2:
1448 f << "title[verti],";
1449 break;
1450 case 3:
1451 f << "title[both],";
1452 break;
1453 default:
1454 f << "##title=" << val << ",";
1455 break;
1456 }
1457 f << "cell[TL]=C" << int(libwps::readU8(input));
1458 f << "S" << int(libwps::readU8(input));
1459 f << "R" << int(libwps::readU16(input)) << ",";
1460 f << "num[row]=" << int(libwps::readU16(input)) << ",";
1461 f << "num[col]=" << int(libwps::readU16(input)) << ",";
1462 if (input->tell()!=endPos)
1463 ascFile.addDelimiter(input->tell(),'|');
1464 ascFile.addPos(pos);
1465 ascFile.addNote(f.str().c_str());
1466 return true;
1467 }
1468
1469 ////////////////////////////////////////////////////////////
1470 // formula
1471 ////////////////////////////////////////////////////////////
1472 bool QuattroSpreadsheet::readCell
1473 (std::shared_ptr<WPSStream> const &stream, Vec2i actPos, WKSContentListener::FormulaInstruction &instr, int sheetId, librevenge::RVNGString const &fName)
1474 {
1475 RVNGInputStreamPtr input = stream->m_input;
1476 instr=WKSContentListener::FormulaInstruction();
1477 instr.m_type=WKSContentListener::FormulaInstruction::F_Cell;
1478 instr.m_fileName=fName;
1479 int pos[3]; // col, sheet, fl|row
1480 bool relative[3] = { false, false, false};
1481 for (int d=0; d<2; ++d) pos[d]=int(libwps::readU8(input));
1482 pos[2]=int(libwps::readU16(input));
1483 if (pos[2]&0x8000)
1484 {
1485 pos[1] = int8_t(pos[1])+sheetId;
1486 relative[1] = true;
1487 }
1488 if (pos[2]&0x4000)
1489 {
1490 pos[0] = int8_t(pos[0])+actPos[0];
1491 relative[0] = true;
1492 }
1493 if (pos[2]&0x2000)
1494 {
1495 pos[2] = actPos[1]+(int16_t((pos[2]&0x1fff)<<3)>>3);
1496 relative[2] = true;
1497 }
1498 else
1499 pos[2] &= 0x1fff;
1500 if (pos[0] < 0 || pos[0] > 255 || pos[2] < 0)
1501 {
1502 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCell: can not read cell position\n"));
1503 return false;
1504 }
1505 instr.m_position[0]=Vec2i(pos[0],pos[2]);
1506 instr.m_positionRelative[0]=Vec2b(relative[0],relative[2]);
1507 if (!fName.empty()) // external file, assume default name
1508 {
1509 librevenge::RVNGString name;
1510 name.sprintf("Sheet%d", pos[1]+1);
1511 instr.m_sheetName[0]=name;
1512 }
1513 else
1514 instr.m_sheetId[0]=pos[1];
1515 return true;
1516 }
1517
1518 bool QuattroSpreadsheet::readCellReference(std::shared_ptr<WPSStream> const &stream, long endPos,
1519 QuattroFormulaInternal::CellReference &ref,
1520 Vec2i const &cPos, int sheetId) const
1521 {
1522 ref.m_cells.clear();
1523 RVNGInputStreamPtr input = stream->m_input;
1524 long pos = input->tell();
1525 if (pos+4>endPos) return false;
1526 auto type=int(libwps::readU16(input));
1527 int cellType=type>>12;
1528 if (cellType>4) return false;
1529 if (cellType==4)
1530 {
1531 // type==4: +6 unused bit then a 233 data field (checkme)
1532 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellReference: find a cell collection 4\n"));
1533 return false;
1534 }
1535
1536 WKSContentListener::FormulaInstruction instr;
1537 if (cellType==3)
1538 {
1539 int dataSize=(type&0x3ff);
1540 if (pos+2+dataSize>endPos)
1541 {
1542 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellReference: can not read the cell collection data size\n"));
1543 return false;
1544 }
1545 if (type&0xc00) // check for deletion
1546 {
1547 input->seek(dataSize, librevenge::RVNG_SEEK_CUR);
1548 return true;
1549 }
1550 endPos=pos+2+dataSize;
1551 while (input->tell()<endPos)
1552 {
1553 QuattroFormulaInternal::CellReference cells;
1554 if (!readCellReference(stream, endPos, cells, cPos, sheetId))
1555 {
1556 WPS_DEBUG_MSG(("QuattroSpreadsheet::readCellReference: can not read a cell\n"));
1557 return false;
1558 }
1559 for (auto const &c : cells.m_cells) ref.addInstruction(c);
1560 }
1561 return true;
1562 }
1563 int const expectedSize[]= {4,8,2};
1564 if (pos+2+expectedSize[cellType]>endPos) return false;
1565 if (type&0xc00)
1566 {
1567 input->seek(expectedSize[cellType], librevenge::RVNG_SEEK_CUR);
1568 return true;
1569 }
1570 librevenge::RVNGString fileName;
1571 if ((type&0x3ff))
1572 {
1573 if (!m_mainParser.getExternalFileName((type&0x3ff), fileName))
1574 return false;
1575 }
1576 if (cellType==0 && pos+6<=endPos)
1577 {
1578 if (!readCell(stream, cPos, instr, sheetId, fileName))
1579 return false;
1580 ref.addInstruction(instr);
1581 return true;
1582 }
1583 else if (cellType==2)
1584 {
1585 auto fId=int(libwps::readU16(input));
1586 librevenge::RVNGString text;
1587 return m_mainParser.getField(fId, text, ref, fileName);
1588 }
1589 else if (cellType==1 && pos+10<=endPos)
1590 {
1591 WKSContentListener::FormulaInstruction cell2;
1592 if (!readCell(stream, cPos, instr, sheetId, fileName) ||
1593 !readCell(stream, cPos, cell2, sheetId, fileName))
1594 return false;
1595 instr.m_type=WKSContentListener::FormulaInstruction::F_CellList;
1596 instr.m_position[1]=cell2.m_position[0];
1597 instr.m_positionRelative[1]=cell2.m_positionRelative[0];
1598 instr.m_sheetId[1]=cell2.m_sheetId[0];
1599 instr.m_sheetName[1]=cell2.m_sheetName[0];
1600 ref.addInstruction(instr);
1601 return true;
1602 }
1603 return false;
1604 }
1605
1606 ////////////////////////////////////////////////////////////
1607 // send data
1608 ////////////////////////////////////////////////////////////
1609 void QuattroSpreadsheet::sendSpreadsheet(int sId, std::vector<Vec2i> const &listGraphicCells)
1610 {
1611 if (!m_listener)
1612 {
1613 WPS_DEBUG_MSG(("QuattroSpreadsheet::sendSpreadsheet: I can not find the listener\n"));
1614 return;
1615 }
1616 auto defFontType=m_mainParser.getDefaultFontType();
1617 auto sheet = m_state->getSheet(sId, defFontType);
1618 for (auto const &c: listGraphicCells)
1619 sheet->getCell(c, defFontType).m_hasGraphic=true;
1620 m_listener->openSheet(sheet->getWidths(), m_state->getSheetName(sId));
1621 m_mainParser.sendPageGraphics(sId);
1622 sheet->compressRowHeights();
1623 auto it = sheet->m_positionToCellMap.begin();
1624 int prevRow = -1;
1625 while (it != sheet->m_positionToCellMap.end())
1626 {
1627 int row=it->first[1];
1628 auto const &cell=(it++)->second;
1629 if (row>prevRow+1)
1630 {
1631 while (row > prevRow+1)
1632 {
1633 if (prevRow != -1) m_listener->closeSheetRow();
1634 int numRepeat;
1635 float h=sheet->getRowHeight(prevRow+1, numRepeat);
1636 if (row<prevRow+1+numRepeat)
1637 numRepeat=row-1-prevRow;
1638 m_listener->openSheetRow(WPSRowFormat(h), numRepeat);
1639 prevRow+=numRepeat;
1640 }
1641 }
1642 if (row!=prevRow)
1643 {
1644 if (prevRow != -1) m_listener->closeSheetRow();
1645 m_listener->openSheetRow(WPSRowFormat(sheet->getRowHeight(++prevRow)));
1646 }
1647 if (cell.m_alignAcrossColumn) // we must look for "merged" cell
1648 {
1649 auto firstCol=cell.position()[0], lastCol=firstCol+1;
1650 auto fIt=it;
1651 while (fIt!=sheet->m_positionToCellMap.end() && fIt->first==Vec2i(lastCol,row))
1652 {
1653 auto const &nextCell=fIt->second;
1654 if (nextCell.m_styleId!=cell.m_styleId)
1655 break;
1656 auto const &nextContent=nextCell.m_content;
1657 if ((nextContent.m_contentType== nextContent.C_NUMBER && !nextContent.isValueSet()) ||
1658 nextContent.empty())
1659 {
1660 ++fIt;
1661 ++lastCol;
1662 }
1663 else
1664 break;
1665 }
1666 if (lastCol!=firstCol+1)
1667 {
1668 const_cast<QuattroSpreadsheetInternal::Cell &>(cell).setNumSpannedCells(Vec2i(lastCol-firstCol,1));
1669 it=fIt;
1670 }
1671 }
1672 sendCellContent(cell, sId);
1673 }
1674 if (prevRow!=-1) m_listener->closeSheetRow();
1675 m_listener->closeSheet();
1676 }
1677
1678 namespace libwps
1679 {
1680 // basic function which probably does not exist on Windows, so rewrite it
1681 static int strncasecmp(char const *s1, char const *s2, size_t n)
1682 {
1683 if (n == 0)
1684 return 0;
1685
1686 while (n-- != 0 && std::tolower(*s1) == std::tolower(*s2))
1687 {
1688 if (n == 0 || *s1 == '\0' || *s2 == '\0')
1689 break;
1690 s1++;
1691 s2++;
1692 }
1693
1694 return std::tolower(*s1) - std::tolower(*s2);
1695 }
1696 }
1697
1698 void QuattroSpreadsheet::updateCellWithUserFormat(QuattroSpreadsheetInternal::Cell &cell, librevenge::RVNGString const &format)
1699 {
1700 if (format.empty())
1701 {
1702 WPS_DEBUG_MSG(("QuattroSpreadsheet::updateCellWithUserFormat: called with empty format\n"));
1703 return;
1704 }
1705 char const *ptr=format.cstr();
1706 auto c=char(std::toupper(*(ptr++)));
1707 // first N/n: numeric, T/t: date
1708 // all: *: fill with last data, 'string': strings, \x: x
1709 if (c=='N')
1710 {
1711 bool scientific=false;
1712 bool hasThousand=false;
1713 bool percent=false;
1714 int digits=-1;
1715 bool end=false;
1716 // numeric 0:always a digits, 9: potential digit, %: percent, ,:thousand, .:decimal, ;different format pos,equal,neg, [Ee][+-], other string
1717 while (*ptr)
1718 {
1719 c=char(std::toupper(*(ptr++)));
1720 bool ok=true;
1721 switch (c)
1722 {
1723 case '0':
1724 case '9':
1725 if (digits>=0 && !scientific) ++digits;
1726 break;
1727 case ',':
1728 if (digits<0 && !scientific)
1729 hasThousand=true;
1730 else
1731 ok=false;
1732 break;
1733 case 'E':
1734 if (digits<0)
1735 scientific=true;
1736 else
1737 ok=false;
1738 break;
1739 case '.':
1740 if (digits<0 && !scientific)
1741 digits=0;
1742 else
1743 ok=false;
1744 break;
1745 case '+':
1746 case '-':
1747 ok=scientific;
1748 break;
1749 case ';':
1750 end=true;
1751 break;
1752 case '%':
1753 percent=true;
1754 break;
1755 default:
1756 if (digits || scientific)
1757 end=true;
1758 else
1759 ok=false;
1760 break;
1761 }
1762 if (!ok)
1763 {
1764 WPS_DEBUG_MSG(("QuattroSpreadsheet::updateCellWithUserFormat: unsure how to format %s\n", format.cstr()));
1765 cell.setFormat(cell.F_NUMBER, 0);
1766 return;
1767 }
1768 if (end)
1769 break;
1770 }
1771 if (digits>0)
1772 cell.setDigits(digits);
1773 if (scientific)
1774 cell.setFormat(cell.F_NUMBER,4);
1775 else if (percent)
1776 cell.setFormat(cell.F_NUMBER,3);
1777 else
1778 cell.setFormat(cell.F_NUMBER, hasThousand ? 5 : 1);
1779 return;
1780 }
1781 if (c!='T')
1782 {
1783 WPS_DEBUG_MSG(("QuattroSpreadsheet::updateCellWithUserFormat: unsure how to format %s\n", format.cstr()));
1784 return;
1785 }
1786 // d: day(1-31), dd: day(01-31), wday(sun), weekday(sunday),
1787 // m: month(1-12) or minute if preceded by h or hh, mm: month(01-12) or..
1788 // mo: month(1-12), mmo: month(01-12), mon(jan), month(january)
1789 // yy: year(00-99), yyyy: year(0001-9999), h: hour(0-23) except if ampm, hh: hour(00-23) except if ampm
1790 // mi: minute, mmi, s: second, ss
1791 // ampm:
1792 std::string dtFormat;
1793 bool hasHour=false;
1794 bool hasDate=false;
1795 bool inString=false;
1796 while (*ptr)
1797 {
1798 c=*(ptr++);
1799 if (inString)
1800 {
1801 if (c=='\'')
1802 inString=false;
1803 else if (c=='\\')
1804 {
1805 if (*ptr)
1806 dtFormat+=*(ptr++);
1807 }
1808 else
1809 dtFormat+=c;
1810 continue;
1811 }
1812 c=char(std::toupper(c));
1813 switch (c)
1814 {
1815 case 'A':
1816 if (libwps::strncasecmp(ptr, "mpm",3)==0)
1817 {
1818 dtFormat+="%p";
1819 ptr+=3;
1820 hasHour=true;
1821 }
1822 else
1823 dtFormat+=c;
1824 break;
1825 case 'D':
1826 if (*ptr=='d' || *ptr=='D')
1827 ++ptr;
1828 dtFormat+="%d";
1829 hasDate=true;
1830 break;
1831 case 'H':
1832 if (*ptr=='h' || *ptr=='H')
1833 ++ptr;
1834 dtFormat+="%H";
1835 hasHour=true;
1836 break;
1837 case 'M':
1838 if (*ptr=='m' || *ptr=='M')
1839 ++ptr;
1840 if (*ptr=='o' || *ptr=='O')
1841 {
1842 if (libwps::strncasecmp(ptr, "onth",4)==0)
1843 {
1844 dtFormat+="%B";
1845 ptr+=4;
1846 }
1847 else if (libwps::strncasecmp(ptr, "on",2)==0)
1848 {
1849 dtFormat+="%b";
1850 ptr+=2;
1851 }
1852 else
1853 {
1854 dtFormat+="%m";
1855 ++ptr;
1856 }
1857 hasDate=true;
1858 }
1859 else if (*ptr=='i' || *ptr=='I')
1860 {
1861 hasHour=true;
1862 dtFormat+="%M";
1863 ++ptr;
1864 }
1865 else if (hasHour)
1866 dtFormat+="%M";
1867 else
1868 dtFormat+="%m";
1869 break;
1870 case 'S':
1871 if (*ptr=='s' || *ptr=='S')
1872 ++ptr;
1873 dtFormat+="%S";
1874 hasHour=true;
1875 break;
1876 case 'W':
1877 if (libwps::strncasecmp(ptr, "day",3)==0)
1878 {
1879 dtFormat+="%a";
1880 ptr+=3;
1881 hasDate=true;
1882 }
1883 else if (libwps::strncasecmp(ptr, "eekday",6)==0)
1884 {
1885 dtFormat+="%A";
1886 ptr+=6;
1887 hasDate=true;
1888 }
1889 else
1890 dtFormat+=c;
1891 break;
1892 case 'Y':
1893 if (libwps::strncasecmp(ptr, "yyy",3)==0)
1894 {
1895 dtFormat+="%Y";
1896 ptr+=3;
1897 hasDate=true;
1898 }
1899 else if (libwps::strncasecmp(ptr, "y",1)==0)
1900 {
1901 dtFormat+="%y";
1902 ptr+=1;
1903 hasDate=true;
1904 }
1905 else
1906 dtFormat+=c;
1907 break;
1908 case '\'':
1909 inString=true;
1910 break;
1911 case '\\':
1912 if (*ptr)
1913 dtFormat+=*(ptr++);
1914 break;
1915 default:
1916 dtFormat+=c;
1917 break;
1918 }
1919 }
1920 cell.setDTFormat((hasDate||!hasHour) ? cell.F_DATE : cell.F_TIME, dtFormat);
1921 }
1922
1923 void QuattroSpreadsheet::sendCellContent(QuattroSpreadsheetInternal::Cell const &cell, int sheetId)
1924 {
1925 if (m_listener.get() == nullptr)
1926 {
1927 WPS_DEBUG_MSG(("QuattroSpreadsheet::sendCellContent: I can not find the listener\n"));
1928 return;
1929 }
1930
1931 libwps_tools_win::Font::Type fontType = cell.m_fontType;
1932 m_listener->setFont(cell.getFont());
1933
1934 QuattroSpreadsheetInternal::Cell finalCell(cell);
1935 auto &content=finalCell.m_content;
1936 for (auto &f : content.m_formula)
1937 {
1938 if (f.m_type==WKSContentListener::FormulaInstruction::F_Cell ||
1939 f.m_type==WKSContentListener::FormulaInstruction::F_CellList)
1940 {
1941 int dim=f.m_type==WKSContentListener::FormulaInstruction::F_Cell ? 1 : 2;
1942 for (int i=0; i<dim; ++i)
1943 {
1944 if (f.m_sheetId[i]>=0 && f.m_sheetName[i].empty() && (f.m_sheetId[i]!=sheetId || !f.m_fileName.empty()))
1945 f.m_sheetName[i]=getSheetName(f.m_sheetId[i]);
1946 }
1947 continue;
1948 }
1949 if (f.m_type!=WKSContentListener::FormulaInstruction::F_Text)
1950 continue;
1951 std::string &text=f.m_content;
1952 librevenge::RVNGString finalString=libwps_tools_win::Font::unicodeString(text, fontType);
1953 if (finalString.empty())
1954 text.clear();
1955 else
1956 text=finalString.cstr();
1957 }
1958 if ((finalCell.m_fileFormat>>4)==7)
1959 {
1960 auto it=m_state->m_idToUserFormatMap.find(finalCell.m_fileFormat&0xf);
1961 if (it==m_state->m_idToUserFormatMap.end() || it->second.empty())
1962 {
1963 WPS_DEBUG_MSG(("QuattroSpreadsheet::sendCellContent: can not find an user format\n"));
1964 }
1965 else
1966 updateCellWithUserFormat(finalCell, it->second);
1967 }
1968 else
1969 finalCell.updateFormat();
1970 m_listener->openSheetCell(finalCell, content);
1971 if (cell.m_hasGraphic)
1972 m_mainParser.sendGraphics(sheetId, cell.position());
1973 if (cell.m_content.m_textEntry.valid())
1974 {
1975 if (!cell.m_stream || !cell.m_stream->m_input)
1976 {
1977 WPS_DEBUG_MSG(("QuattroSpreadsheet::sendCellContent: oops can not find the text's stream\n"));
1978 }
1979 else
1980 {
1981 auto input=cell.m_stream->m_input;
1982 input->seek(cell.m_content.m_textEntry.begin(), librevenge::RVNG_SEEK_SET);
1983 bool prevEOL=false;
1984 std::string text;
1985 while (input->tell()<=cell.m_content.m_textEntry.end())
1986 {
1987 bool last=input->isEnd() || input->tell()>=cell.m_content.m_textEntry.end();
1988 auto c=last ? '\0' : char(libwps::readU8(input));
1989 if ((c==0 || c==0xa || c==0xd) && !text.empty())
1990 {
1991 m_listener->insertUnicodeString(libwps_tools_win::Font::unicodeString(text, fontType));
1992 text.clear();
1993 }
1994 if (last) break;
1995 if (c==0xd)
1996 {
1997 m_listener->insertEOL();
1998 prevEOL=true;
1999 }
2000 else if (c==0xa)
2001 {
2002 if (!prevEOL)
2003 {
2004 WPS_DEBUG_MSG(("QuattroSpreadsheet::sendCellContent: find 0xa without 0xd\n"));
2005 }
2006 prevEOL=false;
2007 }
2008 else
2009 {
2010 if (c)
2011 text.push_back(c);
2012 prevEOL=false;
2013 }
2014 }
2015 }
2016 }
2017 m_listener->closeSheetCell();
2018 }
2019
2020 /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */