summaryrefslogtreecommitdiff
path: root/src/lib/SW602Cell.cpp
blob: 10ef0b2da1d24c12d404afe54df8496b2eb6ea13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libsw602 project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/** \file SW602Cell.cxx
 * Implements SW602Cell (cell content and format)
 */

#include "SW602Cell.h"

#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>

#include <time.h>

#include <librevenge/librevenge.h>

#include "SW602CharsetConverter.h"
#include "SW602Listener.h"

namespace libsw602
{

////////////////////////////////////////////////////////////
// SW602Cell::Format
////////////////////////////////////////////////////////////
std::string SW602Cell::Format::getValueType() const
{
  switch (m_format)
  {
  case F_NUMBER:
    if (m_numberFormat==F_NUMBER_CURRENCY) return "currency";
    if (m_numberFormat==F_NUMBER_PERCENT) return "percent";
    if (m_numberFormat==F_NUMBER_SCIENTIFIC) return "scientific";
    return "float";
  case F_BOOLEAN:
    return "boolean";
  case F_DATE:
    return "date";
  case F_TIME:
    return "time";
  case F_TEXT:
  case F_UNKNOWN:
  default:
    break;
  }
  return "float";
}

bool SW602Cell::Format::getNumberingProperties(librevenge::RVNGPropertyList &propList) const
{
  librevenge::RVNGPropertyListVector pVect;
  switch (m_format)
  {
  case F_BOOLEAN:
    propList.insert("librevenge:value-type", "boolean");
    break;
  case F_NUMBER:
    if (m_digits>0)
      propList.insert("number:decimal-places", m_digits);
    if (m_thousandHasSeparator)
      propList.insert("number:grouping", true);
    switch (m_numberFormat)
    {
    case F_NUMBER_GENERIC:
      propList.insert("librevenge:value-type", "number");
      propList.remove("number:decimal-places");
      break;
    case F_NUMBER_SCIENTIFIC:
      propList.insert("librevenge:value-type", "scientific");
      break;
    case F_NUMBER_PERCENT:
      propList.insert("librevenge:value-type", "percentage");
      break;
    case F_NUMBER_DECIMAL:
      propList.insert("librevenge:value-type", "number");
      if (m_integerDigits>=0)
      {
        propList.insert("number:min-integer-digits", m_integerDigits+1);
        propList.insert("number:decimal-places", 0);
      }
      break;
    case F_NUMBER_FRACTION:
      propList.insert("librevenge:value-type", "fraction");
      propList.insert("number:min-integer-digits", 0);
      propList.insert("number:min-numerator-digits", m_numeratorDigits>0 ? m_numeratorDigits : 1);
      propList.insert("number:min-denominator-digits", m_denominatorDigits>0 ? m_denominatorDigits : 1);
      propList.remove("number:decimal-places");
      break;
    case F_NUMBER_CURRENCY:
    {
      propList.clear();
      propList.insert("librevenge:value-type", "currency");
      librevenge::RVNGPropertyList list;
      list.insert("librevenge:value-type", "currency-symbol");
      list.insert("number:language","en");
      list.insert("number:country","US");
      list.insert("librevenge:currency",m_currencySymbol.c_str());
      pVect.append(list);

      list.clear();
      list.insert("librevenge:value-type", "number");
      if (m_digits>-1000)
        list.insert("number:decimal-places", m_digits);
      pVect.append(list);
      break;
    }
    case F_NUMBER_UNKNOWN:
    default:
      return false;
    }
    break;
  case F_DATE:
    propList.insert("librevenge:value-type", "date");
    propList.insert("number:automatic-order", "true");
    if (!convertDTFormat(m_DTFormat.empty() ? "%m/%d/%Y" : m_DTFormat, pVect))
      return false;
    break;
  case F_TIME:
    propList.insert("librevenge:value-type", "time");
    propList.insert("number:automatic-order", "true");
    if (!convertDTFormat(m_DTFormat.empty() ? "%H:%M:%S" : m_DTFormat, pVect))
      return false;
    break;
  case F_TEXT:
  case F_UNKNOWN:
  default:
    return false;
  }
  if (pVect.count())
    propList.insert("librevenge:format", pVect);
  return true;
}

bool SW602Cell::Format::convertDTFormat(std::string const &dtFormat, librevenge::RVNGPropertyListVector &propVect)
{
  propVect.clear();
  size_t len=dtFormat.size();
  std::string text("");
  librevenge::RVNGPropertyList list;
  for (size_t c=0; c < len; ++c)
  {
    if (dtFormat[c]!='%' || c+1==len)
    {
      text+=dtFormat[c];
      continue;
    }
    char ch=dtFormat[++c];
    if (ch=='%')
    {
      text += '%';
      continue;
    }
    if (!text.empty())
    {
      list.clear();
      list.insert("librevenge:value-type", "text");
      list.insert("librevenge:text", text.c_str());
      propVect.append(list);
      text.clear();
    }
    list.clear();
    switch (ch)
    {
    case 'Y':
      list.insert("number:style", "long");
    case 'y':
      list.insert("librevenge:value-type", "year");
      propVect.append(list);
      break;
    case 'B':
      list.insert("number:style", "long");
    case 'b':
    case 'h':
      list.insert("librevenge:value-type", "month");
      list.insert("number:textual", true);
      propVect.append(list);
      break;
    case 'm':
      list.insert("librevenge:value-type", "month");
      propVect.append(list);
      break;
    case 'e':
      list.insert("number:style", "long");
    // fall-through intended
    case 'd':
      list.insert("librevenge:value-type", "day");
      propVect.append(list);
      break;
    case 'A':
      list.insert("number:style", "long");
    case 'a':
      list.insert("librevenge:value-type", "day-of-week");
      propVect.append(list);
      break;

    case 'H':
      list.insert("number:style", "long");
    // fall-through intended
    case 'I':
      list.insert("librevenge:value-type", "hours");
      propVect.append(list);
      break;
    case 'M':
      list.insert("librevenge:value-type", "minutes");
      list.insert("number:style", "long");
      propVect.append(list);
      break;
    case 'S':
      list.insert("librevenge:value-type", "seconds");
      list.insert("number:style", "long");
      propVect.append(list);
      break;
    case 'p':
      list.insert("librevenge:value-type", "text");
      list.insert("librevenge:text", " ");
      propVect.append(list);
      list.clear();
      list.insert("librevenge:value-type", "am-pm");
      propVect.append(list);
      break;
    default:
      SW602_DEBUG_MSG(("SW602Cell::Format::convertDTFormat: find unimplement command %c(ignored)\n", ch));
    }
  }
  if (!text.empty())
  {
    list.clear();
    list.insert("librevenge:value-type", "text");
    list.insert("librevenge:text", text.c_str());
    propVect.append(list);
  }
  return propVect.count()!=0;
}

std::ostream &operator<<(std::ostream &o, SW602Cell::Format const &format)
{
  switch (format.m_format)
  {
  case SW602Cell::F_BOOLEAN:
    o << "boolean";
    break;
  case SW602Cell::F_TEXT:
    o << "text";
    break;
  case SW602Cell::F_NUMBER:
    o << "number";
    switch (format.m_numberFormat)
    {
    case SW602Cell::F_NUMBER_GENERIC:
      break;
    case SW602Cell::F_NUMBER_DECIMAL:
      o << "[decimal]";
      break;
    case SW602Cell::F_NUMBER_SCIENTIFIC:
      o << "[exp]";
      break;
    case SW602Cell::F_NUMBER_PERCENT:
      o << "[percent]";
      break;
    case SW602Cell::F_NUMBER_CURRENCY:
      o << "[money=" << format.m_currencySymbol << "]";
      break;
    case SW602Cell::F_NUMBER_FRACTION:
      o << "[fraction]";
      break;
    case SW602Cell::F_NUMBER_UNKNOWN:
    default:
      SW602_DEBUG_MSG(("SW602Cell::operator<<(Format): find unexpected type\n"));
      o << "###format,";
      break;
    }
    if (format.m_thousandHasSeparator)
      o << "[thousandSep]";
    if (format.m_parenthesesForNegative)
      o << "[parenthesis<0]";
    break;
  case SW602Cell::F_DATE:
    o << "date[" << format.m_DTFormat << "]";
    break;
  case SW602Cell::F_TIME:
    o << "time[" << format.m_DTFormat << "]";
    break;
  case SW602Cell::F_UNKNOWN:
  default:
    break; // default
  }
  o << ",";

  if (format.m_digits != -1) o << "digits=" << format.m_digits << ",";
  if (format.m_integerDigits != -1) o << "digits[min]=" << format.m_integerDigits << ",";
  if (format.m_numeratorDigits != -1) o << "digits[num]=" << format.m_numeratorDigits << ",";
  if (format.m_denominatorDigits != -1) o << "digits[den]=" << format.m_denominatorDigits << ",";
  return o;
}

int SW602Cell::Format::compare(SW602Cell::Format const &cell) const
{
  if (m_format<cell.m_format) return 1;
  if (m_format>cell.m_format) return -1;
  if (m_numberFormat<cell.m_numberFormat) return 1;
  if (m_numberFormat>cell.m_numberFormat) return -1;
  if (m_digits<cell.m_digits) return 1;
  if (m_digits>cell.m_digits) return -1;
  if (m_integerDigits<cell.m_integerDigits) return 1;
  if (m_integerDigits>cell.m_integerDigits) return -1;
  if (m_numeratorDigits<cell.m_numeratorDigits) return 1;
  if (m_numeratorDigits>cell.m_numeratorDigits) return -1;
  if (m_denominatorDigits<cell.m_denominatorDigits) return 1;
  if (m_denominatorDigits>cell.m_denominatorDigits) return -1;
  if (m_thousandHasSeparator!=cell.m_thousandHasSeparator) return m_thousandHasSeparator ? -1:1;
  if (m_parenthesesForNegative!=cell.m_parenthesesForNegative) return m_parenthesesForNegative ? -1:1;
  if (m_DTFormat<cell.m_DTFormat) return 1;
  if (m_DTFormat>cell.m_DTFormat) return -1;
  if (m_currencySymbol<cell.m_currencySymbol) return 1;
  if (m_currencySymbol>cell.m_currencySymbol) return -1;
  return 0;
}
////////////////////////////////////////////////////////////
// SW602Cell
////////////////////////////////////////////////////////////
void SW602Cell::addTo(librevenge::RVNGPropertyList &propList) const
{
  propList.insert("librevenge:column", position()[0]);
  propList.insert("librevenge:row", position()[1]);

  propList.insert("table:number-columns-spanned", numSpannedCells()[0]);
  propList.insert("table:number-rows-spanned", numSpannedCells()[1]);

  if (m_fontSet)
    m_font.addTo(propList);
  for (size_t c = 0; c < m_bordersList.size(); c++)
  {
    switch (c)
    {
    case libsw602::Left:
      m_bordersList[c].addTo(propList, "left");
      break;
    case libsw602::Right:
      m_bordersList[c].addTo(propList, "right");
      break;
    case libsw602::Top:
      m_bordersList[c].addTo(propList, "top");
      break;
    case libsw602::Bottom:
      m_bordersList[c].addTo(propList, "bottom");
      break;
    default:
      SW602_DEBUG_MSG(("SW602Cell::addTo: can not send %d border\n",int(c)));
      break;
    }
  }
  if (!backgroundColor().isWhite())
    propList.insert("fo:background-color", backgroundColor().str().c_str());
  if (isProtected())
    propList.insert("style:cell-protect","protected");
  // alignment
  switch (hAlignment())
  {
  case HALIGN_LEFT:
    propList.insert("fo:text-align", "first");
    propList.insert("style:text-align-source", "fix");
    break;
  case HALIGN_CENTER:
    propList.insert("fo:text-align", "center");
    propList.insert("style:text-align-source", "fix");
    break;
  case HALIGN_RIGHT:
    propList.insert("fo:text-align", "end");
    propList.insert("style:text-align-source", "fix");
    break;
  case HALIGN_DEFAULT:
    break; // default
  case HALIGN_FULL:
  default:
    SW602_DEBUG_MSG(("SW602Cell::addTo: called with unknown halign=%d\n", hAlignment()));
  }
  // no padding
  propList.insert("fo:padding", 0, librevenge::RVNG_POINT);
  // alignment
  switch (vAlignment())
  {
  case VALIGN_TOP:
    propList.insert("style:vertical-align", "top");
    break;
  case VALIGN_CENTER:
    propList.insert("style:vertical-align", "middle");
    break;
  case VALIGN_BOTTOM:
    propList.insert("style:vertical-align", "bottom");
    break;
  case VALIGN_DEFAULT:
    break; // default
  default:
    SW602_DEBUG_MSG(("SW602Cell::addTo: called with unknown valign=%d\n", vAlignment()));
  }
}

std::string SW602Cell::getColumnName(int col)
{
  std::stringstream f;
  f << "[.";
  if (col > 26) f << char('A'+col/26);
  f << char('A'+(col%26));
  f << "]";
  return f.str();
}

std::string SW602Cell::getBasicCellName(SW602Vec2i const &pos)
{
  std::stringstream f;
  int col = pos[0];
  if (col > 26*26)
  {
    f << char('A'+col/(26*26));
    col *= 26*26;
  }
  if (col > 26)
  {
    f << char('A'+col/26);
    col %= 26;
  }
  f << char('A'+col);
  f << pos[1]+1;
  return f.str();
}

std::string SW602Cell::getCellName(SW602Vec2i const &pos, SW602Vec2b const &absolute)
{
  std::stringstream f;
  f << "[.";
  if (absolute[1]) f << "$";
  int col = pos[0];
  if (col > 26*26)
  {
    f << char('A'+col/(26*26));
    col *= 26*26;
  }
  if (col > 26)
  {
    f << char('A'+col/26);
    col %= 26;
  }
  f << char('A'+col);
  if (absolute[0]) f << "$";
  f << pos[1]+1 << ']';
  return f.str();
}

void SW602Cell::setBorders(int wh, SW602Border const &border)
{
  int const allBits = libsw602::LeftBit|libsw602::RightBit|libsw602::TopBit|libsw602::BottomBit|libsw602::HMiddleBit|libsw602::VMiddleBit;
  if (wh & (~allBits))
  {
    SW602_DEBUG_MSG(("SW602Cell::setBorders: unknown borders\n"));
    return;
  }
  size_t numData = 4;
  if (wh & (libsw602::HMiddleBit|libsw602::VMiddleBit))
    numData=6;
  if (m_bordersList.size() < numData)
  {
    SW602Border emptyBorder;
    emptyBorder.m_style = SW602Border::None;
    m_bordersList.resize(numData, emptyBorder);
  }
  if (wh & libsw602::LeftBit) m_bordersList[libsw602::Left] = border;
  if (wh & libsw602::RightBit) m_bordersList[libsw602::Right] = border;
  if (wh & libsw602::TopBit) m_bordersList[libsw602::Top] = border;
  if (wh & libsw602::BottomBit) m_bordersList[libsw602::Bottom] = border;
  if (wh & libsw602::HMiddleBit) m_bordersList[libsw602::HMiddle] = border;
  if (wh & libsw602::VMiddleBit) m_bordersList[libsw602::VMiddle] = border;
}

std::ostream &operator<<(std::ostream &o, SW602Cell const &cell)
{
  o << SW602Cell::getCellName(cell.m_position, SW602Vec2b(false,false)) << ":";
  if (cell.numSpannedCells()[0] != 1 || cell.numSpannedCells()[1] != 1)
    o << "span=[" << cell.numSpannedCells()[0] << "," << cell.numSpannedCells()[1] << "],";

  if (cell.m_protected) o << "protected,";
  if (cell.m_bdBox.size()[0]>0 || cell.m_bdBox.size()[1]>0)
    o << "bdBox=" << cell.m_bdBox << ",";
  if (cell.m_bdSize[0]>0 || cell.m_bdSize[1]>0)
    o << "bdSize=" << cell.m_bdSize << ",";
  o << cell.m_format;
  if (cell.m_fontSet) o << "hasFont,";
  switch (cell.m_hAlign)
  {
  case SW602Cell::HALIGN_LEFT:
    o << "left,";
    break;
  case SW602Cell::HALIGN_CENTER:
    o << "centered,";
    break;
  case SW602Cell::HALIGN_RIGHT:
    o << "right,";
    break;
  case SW602Cell::HALIGN_FULL:
    o << "full,";
    break;
  case SW602Cell::HALIGN_DEFAULT:
  default:
    break; // default
  }
  switch (cell.m_vAlign)
  {
  case SW602Cell::VALIGN_TOP:
    o << "top,";
    break;
  case SW602Cell::VALIGN_CENTER:
    o << "centered[y],";
    break;
  case SW602Cell::VALIGN_BOTTOM:
    o << "bottom,";
    break;
  case SW602Cell::VALIGN_DEFAULT:
  default:
    break; // default
  }

  if (!cell.m_backgroundColor.isWhite())
    o << "backColor=" << cell.m_backgroundColor << ",";
  for (size_t i = 0; i < cell.m_bordersList.size(); i++)
  {
    if (cell.m_bordersList[i].m_style == SW602Border::None)
      continue;
    o << "bord";
    if (i < 6)
    {
      static char const *wh[] = { "L", "R", "T", "B", "MiddleH", "MiddleV" };
      o << wh[i];
    }
    else o << "[#wh=" << i << "]";
    o << "=" << cell.m_bordersList[i] << ",";
  }
  switch (cell.m_extraLine)
  {
  case SW602Cell::E_None:
    break;
  case SW602Cell::E_Line1:
    o << "line[TL->RB],";
    break;
  case SW602Cell::E_Line2:
    o << "line[BL->RT],";
    break;
  case SW602Cell::E_Cross:
    o << "line[cross],";
    break;
  default:
    break;
  }
  if (cell.m_extraLine!=SW602Cell::E_None)
    o << cell.m_extraLineType << ",";
  return o;
}

// send data to listener
bool SW602Cell::send(SW602ListenerPtr listener, SW602Table &table)
{
  if (!listener) return true;
  listener->openTableCell(*this);
  bool ok=sendContent(listener, table);
  listener->closeTableCell();
  return ok;
}

bool SW602Cell::sendContent(SW602ListenerPtr, SW602Table &)
{
  SW602_DEBUG_MSG(("SW602Cell::sendContent: must not be called!!!\n"));
  return false;
}

////////////////////////////////////////////////////////////
// SW602CellContent
////////////////////////////////////////////////////////////
bool SW602CellContent::double2Date(double val, int &Y, int &M, int &D)
{
  /* first convert the date in long*/
  long numDaysSinceOrigin=long(val+0.4);
  // checkme: do we need to check before for isNan(val) ?
  if (numDaysSinceOrigin<-10000*365 || numDaysSinceOrigin>10000*365)
  {
    /* normally, we can expect documents to contain date between 1904
       and 2004. So even if such a date can make sense, storing it as
       a number of days is clearly abnormal */
    SW602_DEBUG_MSG(("SW602CellContent::double2Date: using a double to represent the date %ld seems odd\n", numDaysSinceOrigin));
    Y=1904;
    M=D=1;
    return false;
  }
  // find the century
  int century=19;
  while (numDaysSinceOrigin>=36500+24)
  {
    long numDaysInCentury=36500+24+((century%4)?0:1);
    if (numDaysSinceOrigin<numDaysInCentury) break;
    numDaysSinceOrigin-=numDaysInCentury;
    ++century;
  }
  while (numDaysSinceOrigin<0)
  {
    --century;
    numDaysSinceOrigin+=36500+24+((century%4)?0:1);
  }
  // now compute the year
  Y=int(numDaysSinceOrigin/365);
  long numDaysToEndY1=Y*365+(Y>0 ? (Y-1)/4+((century%4)?0:1) : 0);
  if (numDaysToEndY1>numDaysSinceOrigin)
  {
    --Y;
    numDaysToEndY1=Y*365+(Y>0 ? (Y-1)/4+((century%4)?0:1) : 0);
  }
  // finish to compute the date
  int numDaysFrom1Jan=int(numDaysSinceOrigin-numDaysToEndY1);
  Y+=century*100;
  bool isLeap=(Y%4)==0 && ((Y%400)==0 || (Y%100)!=0);

  for (M=0; M<12; ++M)
  {
    static const int days[2][12] =
    {
      { 0,31,59,90,120,151,181,212,243,273,304,334},
      { 0,31,60,91,121,152,182,213,244,274,305,335}
    };
    if (M<11 && days[isLeap ? 1 : 0][M+1]<=numDaysFrom1Jan) continue;
    D=(numDaysFrom1Jan-days[isLeap ? 1 : 0][M++])+1;
    break;
  }
  return true;
}

bool SW602CellContent::date2Double(int Y, int M, int D, double &val)
{
  --M;
  --D;
  if (M>11)
  {
    Y += M/12;
    M %= 12;
  }
  else if (M<0)
  {
    int yDiff = (-M + 11)/12;
    Y -= yDiff;
    M+=12*yDiff;
  }
  // sanity check
  if (M<0||M>11)
  {
    SW602_DEBUG_MSG(("SW602CellContent::date2Double: something is bad\n"));
    return false;
  }
  bool isLeap=(Y%4)==0 && ((Y%400)==0 || (Y%100)!=0);
  int32_t const daysFrom0=365*Y+(Y/400)-(Y/100)+(Y/4);
  int32_t const daysFrom1900=365*1900+(1900/400)-(1900/100)+(1900/4);
  static const int32_t days[2][12] =
  {
    { 0,31,59,90,120,151,181,212,243,273,304,334},
    { 0,31,60,91,121,152,182,213,244,274,305,335}
  };
  int32_t daysFrom1Jan=days[isLeap ? 1 : 0][M] + D;
  val=double(daysFrom0-daysFrom1900+daysFrom1Jan);
  return true;
}

bool SW602CellContent::double2Time(double val, int &H, int &M, int &S)
{
  if (val < 0.0 || val > 1.0) return false;
  double time = 24.*3600.*val+0.5;
  H=int(time/3600.);
  time -= H*3600.;
  M=int(time/60.);
  time -= M*60.;
  S=int(time);
  return true;
}

bool SW602CellContent::double2String(double val, SW602Cell::Format const &format, std::string &str)
{
  std::stringstream s;
  switch (format.m_format)
  {
  case SW602Cell::F_BOOLEAN:
    if (val<0 || val >0) s << "true";
    else s << "false";
    break;
  case SW602Cell::F_NUMBER:
    if (format.m_digits>=0 && format.m_numberFormat!=SW602Cell::F_NUMBER_GENERIC)
      s << std::setprecision(format.m_digits);
    switch (format.m_numberFormat)
    {
    case SW602Cell::F_NUMBER_CURRENCY:
      s << std::fixed << val << "$";
      break;
    case SW602Cell::F_NUMBER_DECIMAL:
      s << val;
      break;
    case SW602Cell::F_NUMBER_SCIENTIFIC:
      s << std::scientific << val;
      break;
    case SW602Cell::F_NUMBER_PERCENT:
      s << std::fixed << 100*val << "%";
      break;
    case SW602Cell::F_NUMBER_FRACTION:
    case SW602Cell::F_NUMBER_GENERIC:
    case SW602Cell::F_NUMBER_UNKNOWN:
    default:
      s << val;
      break;
    }
    break;
  case SW602Cell::F_DATE:
  {
    int Y, M, D;
    if (!double2Date(val, Y, M, D)) return false;
    struct tm time;
    time.tm_sec=time.tm_min=time.tm_hour=0;
    time.tm_mday=D;
    time.tm_mon=M;
    time.tm_year=Y;
    time.tm_wday=time.tm_yday=time.tm_isdst=-1;
#if HAVE_STRUCT_TM_TM_ZONE
    time.tm_zone=0;
#endif
    char buf[256];
    if (mktime(&time)==-1 ||
        !strftime(buf, 256, format.m_DTFormat.empty() ? "%m/%d/%y" : format.m_DTFormat.c_str(), &time))
      return false;
    s << buf;
    break;
  }
  case SW602Cell::F_TIME:
  {
    if (val<0 || val>=1)
      val=std::fmod(val,1.);
    int H, M, S;
    if (!double2Time(val, H, M, S)) return false;
    struct tm time;
    time.tm_sec=S;
    time.tm_min=M;
    time.tm_hour=H;
    time.tm_mday=time.tm_mon=1;
    time.tm_year=100;
    time.tm_wday=time.tm_yday=time.tm_isdst=-1;
#if HAVE_STRUCT_TM_TM_ZONE
    time.tm_zone=0;
#endif
    char buf[256];
    if (mktime(&time)==-1 ||
        !strftime(buf, 256, format.m_DTFormat.empty() ? "%H:%M:%S" : format.m_DTFormat.c_str(), &time))
      return false;
    s << buf;
    break;
  }
  case SW602Cell::F_TEXT:
  case SW602Cell::F_UNKNOWN:
  default:
    SW602_DEBUG_MSG(("SW602CellContent::double2String: called with bad format\n"));
    return false;
  }
  str=s.str();
  return true;
}

std::ostream &operator<<(std::ostream &o, SW602CellContent const &content)
{
  switch (content.m_contentType)
  {
  case SW602CellContent::C_NONE:
    break;
  case SW602CellContent::C_TEXT:
    o << ",text=\"" << content.m_textEntry << "\"";
    break;
  case SW602CellContent::C_NUMBER:
  {
    o << ",val=";
    bool textAndVal = false;
    if (content.hasText())
    {
      o << "entry=" << content.m_textEntry;
      textAndVal = content.isValueSet();
    }
    if (textAndVal) o << "[";
    if (content.isValueSet()) o << content.m_value;
    if (textAndVal) o << "]";
  }
  break;
  case SW602CellContent::C_FORMULA:
    o << ",formula=";
    for (size_t l=0; l < content.m_formula.size(); ++l)
      o << content.m_formula[l];
    if (content.isValueSet()) o << "[" << content.m_value << "]";
    break;
  case SW602CellContent::C_UNKNOWN:
    break;
  default:
    o << "###unknown type,";
    break;
  }
  return o;
}

// ---------- WKSContentListener::FormulaInstruction ------------------
librevenge::RVNGPropertyList SW602CellContent::FormulaInstruction::getPropertyList(const SW602CharsetConverter &converter) const
{
  librevenge::RVNGPropertyList pList;
  switch (m_type)
  {
  case F_Operator:
    pList.insert("librevenge:type","librevenge-operator");
    pList.insert("librevenge:operator",m_content.c_str());
    break;
  case F_Function:
    pList.insert("librevenge:type","librevenge-function");
    pList.insert("librevenge:function",m_content.c_str());
    break;
  case F_Text:
  {
    // we must use the font converter here to get the final string
    pList.insert("librevenge:type","librevenge-text");
    librevenge::RVNGString finalStr("");
    for (size_t i=0; i<m_content.size(); ++i)
    {
      char c=m_content[i];
      const int unicode = converter.unicode(c);
      if (unicode==-1)
      {
        if (c < 0x20 && c!=9)
        {
          SW602_DEBUG_MSG(("SW602CellContent::FormulaInstruction: Find odd char %x\n", (unsigned int)c));
        }
        else
          finalStr.append(char(c));
      }
      else if (unicode != 0xfffd)
        libsw602::appendUnicode((uint32_t) unicode, finalStr);
    }
    pList.insert("librevenge:text",finalStr);
    break;
  }
  case F_Double:
    pList.insert("librevenge:type","librevenge-number");
    pList.insert("librevenge:number",m_doubleValue, librevenge::RVNG_GENERIC);
    break;
  case F_Long:
    pList.insert("librevenge:type","librevenge-number");
    pList.insert("librevenge:number",m_longValue, librevenge::RVNG_GENERIC);
    break;
  case F_Cell:
    pList.insert("librevenge:type","librevenge-cell");
    pList.insert("librevenge:column",m_position[0][0], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:row",m_position[0][1], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:column-absolute",!m_positionRelative[0][0]);
    pList.insert("librevenge:row-absolute",!m_positionRelative[0][1]);
    if (!m_sheet.empty())
      pList.insert("librevenge:sheet-name",m_sheet.c_str());
    break;
  case F_CellList:
    pList.insert("librevenge:type","librevenge-cells");
    pList.insert("librevenge:start-column",m_position[0][0], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:start-row",m_position[0][1], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:start-column-absolute",!m_positionRelative[0][0]);
    pList.insert("librevenge:start-row-absolute",!m_positionRelative[0][1]);
    pList.insert("librevenge:end-column",m_position[1][0], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:end-row",m_position[1][1], librevenge::RVNG_GENERIC);
    pList.insert("librevenge:end-column-absolute",!m_positionRelative[1][0]);
    pList.insert("librevenge:end-row-absolute",!m_positionRelative[1][1]);
    if (!m_sheet.empty())
      pList.insert("librevenge:sheet-name",m_sheet.c_str());
    break;
  default:
    SW602_DEBUG_MSG(("SW602CellContent::FormulaInstruction::getPropertyList: unexpected type\n"));
  }
  return pList;
}

std::ostream &operator<<(std::ostream &o, SW602CellContent::FormulaInstruction const &inst)
{
  if (inst.m_type==SW602CellContent::FormulaInstruction::F_Double)
    o << inst.m_doubleValue;
  else if (inst.m_type==SW602CellContent::FormulaInstruction::F_Long)
    o << inst.m_longValue;
  else if (inst.m_type==SW602CellContent::FormulaInstruction::F_Cell)
  {
    if (!inst.m_sheet.empty()) o << inst.m_sheet;
    if (!inst.m_positionRelative[0][0]) o << "$";
    if (inst.m_position[0][0]<0) o << "C" << inst.m_position[0][0];
    else
    {
      if (inst.m_position[0][0]>=26) o << (char)(inst.m_position[0][0]/26-1 + 'A');
      o << (char)(inst.m_position[0][0]%26+'A');
    }
    if (!inst.m_positionRelative[0][1]) o << "$";
    if (inst.m_position[0][1]<0) o << "R" << inst.m_position[0][1];
    else o << inst.m_position[0][1];
  }
  else if (inst.m_type==SW602CellContent::FormulaInstruction::F_CellList)
  {
    if (!inst.m_sheet.empty()) o << inst.m_sheet;
    for (int l=0; l<2; ++l)
    {
      if (!inst.m_positionRelative[l][0]) o << "$";
      if (inst.m_position[l][0]<0) o << "C" << inst.m_position[l][0];
      else
      {
        if (inst.m_position[l][0]>=26) o << (char)(inst.m_position[l][0]/26-1 + 'A');
        o << (char)(inst.m_position[l][0]%26+'A');
      }
      if (!inst.m_positionRelative[l][1]) o << "$";
      if (inst.m_position[l][1]<0) o << "R" << inst.m_position[l][1];
      else o << inst.m_position[l][1];
      if (l==0) o << ":";
    }
  }
  else if (inst.m_type==SW602CellContent::FormulaInstruction::F_Text)
    o << "\"" << inst.m_content << "\"";
  else
    o << inst.m_content;
  return o;
}

}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */