summaryrefslogtreecommitdiff
path: root/src/lib/VSDXContentCollector.cpp
blob: 8f40c45cb84068531bde50371c3969e9835503b0 (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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
/* libvisio
 * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>
 * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02111-1301 USA
 */

#include "VSDXContentCollector.h"
#include "VSDXParser.h"
#include "VSDInternalStream.h"

#define DUMP_BITMAP 0

#if DUMP_BITMAP
static unsigned bitmapId = 0;
#include <sstream>
#endif

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

libvisio::VSDXContentCollector::VSDXContentCollector(
  libwpg::WPGPaintInterface *painter,
  std::vector<std::map<unsigned, XForm> > &groupXFormsSequence,
  std::vector<std::map<unsigned, unsigned> > &groupMembershipsSequence,
  std::vector<std::list<unsigned> > &documentPageShapeOrders,
  VSDXStyles &styles, VSDXStencils &stencils
  ) :
    m_painter(painter), m_isPageStarted(false), m_pageWidth(0.0), m_pageHeight(0.0),
    m_shadowOffsetX(0.0), m_shadowOffsetY(0.0),
    m_scale(1.0), m_x(0.0), m_y(0.0), m_originalX(0.0), m_originalY(0.0), m_xform(),
    m_txtxform(), m_currentGeometry(), m_groupXForms(groupXFormsSequence[0]),
    m_currentForeignData(), m_currentForeignProps(),
    m_currentShapeId(0), m_foreignType(0), m_foreignFormat(0), m_styleProps(),
    m_lineColour("black"), m_fillType("none"), m_linePattern(1),
    m_fillPattern(1), m_fillFGTransparency(0), m_fillBGTransparency(0),
    m_noLine(false), m_noFill(false), m_noShow(false), m_currentLevel(0),
    m_isShapeStarted(false), m_groupMemberships(groupMembershipsSequence[0]),
    m_groupXFormsSequence(groupXFormsSequence),
    m_groupMembershipsSequence(groupMembershipsSequence), m_currentPageNumber(0),
    m_shapeList(), m_shapeOutput(0), m_documentPageShapeOrders(documentPageShapeOrders),
    m_pageShapeOrder(documentPageShapeOrders[0]), m_isFirstGeometry(true), m_textFormat(VSD_TEXT_ANSI), m_outputTextStart(false), m_styles(styles), m_isTextUnstyled(false), m_stencils(stencils), m_isStencilStarted(false)
{
}

void libvisio::VSDXContentCollector::_flushCurrentPath()
{
  WPXPropertyListVector path;
  double startX = 0; double startY = 0;
  double x = 0; double y = 0;
  bool firstPoint = true;

  for (unsigned i = 0; i < m_currentGeometry.size(); i++)
  {
    if (firstPoint)
    {
       x = m_currentGeometry[i]["svg:x"]->getDouble();
       y = m_currentGeometry[i]["svg:y"]->getDouble();
       startX = x;
       startY = y;
       firstPoint = false;
    }
    else if (m_currentGeometry[i]["libwpg:path-action"]->getStr() == "M")
    {
      if (((startX == x && startY == y) || (m_styleProps["draw:fill"] && m_styleProps["draw:fill"]->getStr() != "none")) && path.count())
      {
         WPXPropertyList closedPath;
         closedPath.insert("libwpg:path-action", "Z");
         path.append(closedPath);
      }
      x = m_currentGeometry[i]["svg:x"]->getDouble();
      y = m_currentGeometry[i]["svg:y"]->getDouble();
      startX = x;
      startY = y;
    }
    else
    {
      x = m_currentGeometry[i]["svg:x"]->getDouble();
      y = m_currentGeometry[i]["svg:y"]->getDouble();
    }
    path.append(m_currentGeometry[i]);
  }
  if (((startX == x && startY == y) || (m_styleProps["draw:fill"] && m_styleProps["draw:fill"]->getStr() != "none")) && path.count())
  {
     WPXPropertyList closedPath;
     closedPath.insert("libwpg:path-action", "Z");
     path.append(closedPath);
  }
  if (path.count() && !m_noShow)
  {
    m_shapeOutput->addStyle(m_styleProps, WPXPropertyListVector());
    m_shapeOutput->addPath(path);
  }
  m_currentGeometry.clear();
}

void libvisio::VSDXContentCollector::_flushCurrentForeignData()
{
  if (m_currentForeignData.size() && m_currentForeignProps["libwpg:mime-type"] && !m_noShow)
  {
    m_shapeOutput->addStyle(m_styleProps, WPXPropertyListVector());
    m_shapeOutput->addGraphicObject(m_currentForeignProps, m_currentForeignData);
  }
  m_currentForeignData.clear();
  m_currentForeignProps.clear();
}

void libvisio::VSDXContentCollector::_flushCurrentPage()
{
  std::map<unsigned, VSDXOutputElementList>::iterator iter;
  if (m_pageShapeOrder.size())
  {
    for (std::list<unsigned>::iterator iterList = m_pageShapeOrder.begin(); iterList != m_pageShapeOrder.end(); iterList++)
    {
      iter = m_pageOutput.find(*iterList);
      if (iter != m_pageOutput.end())
        iter->second.draw(m_painter);
    }
  }
  m_pageOutput.clear();
}

void libvisio::VSDXContentCollector::collectEllipticalArcTo(unsigned /* id */, unsigned level, double x3, double y3, double x2, double y2, double angle, double ecc)
{
  _handleLevelChange(level);

  transformPoint(x2, y2);
  transformPoint(x3, y3);
  transformAngle(angle);

  double x1 = m_x*cos(angle) + m_y*sin(angle);
  double y1 = ecc*(m_y*cos(angle) - m_x*sin(angle));
  double x2n = x2*cos(angle) + y2*sin(angle);
  double y2n = ecc*(y2*cos(angle) -x2*sin(angle));
  double x3n = x3*cos(angle) + y3*sin(angle);
  double y3n = ecc*(y3*cos(angle) - x3*sin(angle));
  double x0 = ((x1-x2n)*(x1+x2n)*(y2n-y3n) - (x2n-x3n)*(x2n+x3n)*(y1-y2n) +
               (y1-y2n)*(y2n-y3n)*(y1-y3n)) /
               (2*((x1-x2n)*(y2n-y3n) - (x2n-x3n)*(y1-y2n)));
  double y0 = ((x1-x2n)*(x2n-x3n)*(x1-x3n) + (x2n-x3n)*(y1-y2n)*(y1+y2n) -
               (x1-x2n)*(y2n-y3n)*(y2n+y3n)) /
               (2*((x2n-x3n)*(y1-y2n) - (x1-x2n)*(y2n-y3n)));

  VSD_DEBUG_MSG(("Centre: (%f,%f), angle %f\n", x0, y0, angle));
  double rx = sqrt(pow(x1-x0, 2) + pow(y1-y0, 2));
  double ry = rx / ecc;
  m_x = x3; m_y = y3;
  m_originalX = m_x; m_originalY = m_y;
  WPXPropertyList arc;
  int largeArc = 0;
  int sweep = 1;

  // Calculate side of chord that ellipse centre and control point fall on
  double centreSide = (x3n-x1)*(y0-y1) - (y3n-y1)*(x0-x1);
  double midSide = (x3n-x1)*(y2n-y1) - (y3n-y1)*(x2n-x1);
  // Large arc if centre and control point are on the same side
  if ((centreSide > 0 && midSide > 0) || (centreSide < 0 && midSide < 0))
    largeArc = 1;
  // Change direction depending of side of control point
  if (midSide > 0)
    sweep = 0;

  arc.insert("svg:rx", m_scale*rx);
  arc.insert("svg:ry", m_scale*ry);
  arc.insert("libwpg:rotate", angle * 180 / M_PI);
  arc.insert("libwpg:large-arc", largeArc);
  arc.insert("libwpg:sweep", sweep);
  arc.insert("svg:x", m_scale*m_x);
  arc.insert("svg:y", m_scale*m_y);
  arc.insert("libwpg:path-action", "A");
  m_currentGeometry.push_back(arc);
}

void libvisio::VSDXContentCollector::collectEllipse(unsigned /* id */, unsigned level, double cx, double cy, double xleft, double yleft, double xtop, double ytop)
{
  _handleLevelChange(level);
  WPXPropertyList ellipse;
  double angle = fmod(2.0*M_PI + (cy > yleft ? 1.0 : -1.0)*acos((cx-xleft) / sqrt((xleft - cx)*(xleft - cx) + (yleft - cy)*(yleft - cy))), 2.0*M_PI);
  transformPoint(cx, cy);
  transformPoint(xleft, yleft);
  transformPoint(xtop, ytop);
  transformAngle(angle);

  double rx = sqrt((xleft - cx)*(xleft - cx) + (yleft - cy)*(yleft - cy));
  double ry = sqrt((xtop - cx)*(xtop - cx) + (ytop - cy)*(ytop - cy));

  int largeArc = 0;
  double centreSide = (xleft-xtop)*(cy-ytop) - (yleft-ytop)*(cx-xtop);
  if (centreSide > 0)
  {
    largeArc = 1;
  }
  ellipse.insert("svg:x",m_scale*xleft);
  ellipse.insert("svg:y",m_scale*yleft);
  ellipse.insert("libwpg:path-action", "M");
  m_currentGeometry.push_back(ellipse);
  ellipse.insert("svg:rx",m_scale*rx);
  ellipse.insert("svg:ry",m_scale*ry);
  ellipse.insert("svg:x",m_scale*xtop);
  ellipse.insert("svg:y",m_scale*ytop);
  ellipse.insert("libwpg:large-arc", largeArc?1:0);
  ellipse.insert("libwpg:path-action", "A");
  ellipse.insert("libwpg:rotate", angle * 180/M_PI);
  m_currentGeometry.push_back(ellipse);
  ellipse.insert("svg:x",m_scale*xleft);
  ellipse.insert("svg:y",m_scale*yleft);
  ellipse.insert("libwpg:large-arc", largeArc?0:1);
  m_currentGeometry.push_back(ellipse);

}

void libvisio::VSDXContentCollector::collectLine(unsigned /* id */, unsigned level, double strokeWidth, Colour c, unsigned linePattern, unsigned lineCap)
{
  _handleLevelChange(level);
  m_hasLocalLineStyle = true;
  m_linePattern = linePattern;
  m_styleProps.insert("svg:stroke-width", m_scale*strokeWidth);
  m_lineColour = getColourString(c);
  m_styleProps.insert("svg:stroke-color", m_lineColour);
  if (c.a)
    m_styleProps.insert("svg:stroke-opacity", (1 - c.a/255.0), WPX_PERCENT);
  else
    m_styleProps.insert("svg:stroke-opacity", 1.0, WPX_PERCENT);
  switch (lineCap)
  {
    case 0:
      m_styleProps.insert("svg:stroke-linecap", "round");
      m_styleProps.insert("svg:stroke-linejoin", "round");
      break;
    case 2:
      m_styleProps.insert("svg:stroke-linecap", "square");
      m_styleProps.insert("svg:stroke-linejoin", "miter");
      break;
    default:
      m_styleProps.insert("svg:stroke-linecap", "butt");
      m_styleProps.insert("svg:stroke-linejoin", "miter");
      break;
  }

  const char* patterns[] = {
    /*  0 */  "none",
    /*  1 */  "solid",
    /*  2 */  "6, 3",
    /*  3 */  "1, 3",
    /*  4 */  "6, 3, 1, 3",
    /*  5 */  "6, 3, 1, 3, 1, 3",
    /*  6 */  "6, 3, 6, 3, 1, 3",
    /*  7 */  "14, 2, 6, 2",
    /*  8 */  "14, 2, 6, 2, 6, 2",
    /*  9 */  "3, 1",
    /* 10 */  "1, 1",
    /* 11 */  "3, 1, 1, 1",
    /* 12 */  "3, 1, 1, 1, 1, 1",
    /* 13 */  "3, 1, 3, 1, 1, 1",
    /* 14 */  "7, 1, 3, 1",
    /* 15 */  "7, 1, 3, 1, 3, 1",
    /* 16 */  "11, 5",
    /* 17 */  "1, 5",
    /* 18 */  "11, 5, 1, 5",
    /* 19 */  "11, 5, 1, 5, 1, 5",
    /* 20 */  "11, 5, 11, 5, 1, 5",
    /* 21 */  "27, 5, 11, 5",
    /* 22 */  "27, 5, 11, 5, 11, 5",
    /* 23 */  "2, 1"
  };
  if (m_linePattern > 0 && m_linePattern < sizeof(patterns)/sizeof(patterns[0]))
    m_styleProps.insert("svg:stroke-dasharray", patterns[m_linePattern]);
  // FIXME: later it will require special treatment for custom line patterns
  // patt ID is 0xfe, link to stencil name is in 'Line' blocks
}

void libvisio::VSDXContentCollector::collectFillAndShadow(unsigned /* id */, unsigned level, unsigned colourIndexFG, unsigned colourIndexBG, unsigned fillPattern, unsigned fillFGTransparency, unsigned fillBGTransparency, unsigned shadowPattern, Colour shfgc, double shadowOffsetX, double shadowOffsetY)
{
  _handleLevelChange(level);
  m_hasLocalFillStyle = true;
  m_fillPattern = fillPattern;
  m_fillFGTransparency = fillFGTransparency;
  m_fillBGTransparency = fillBGTransparency;

  if (m_fillPattern == 0)
    m_fillType = "none";
  else if (m_fillPattern == 1)
  {
    m_fillType = "solid";
    m_styleProps.insert("draw:fill-color", getColourString(m_colours[colourIndexFG]));
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("draw:opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.remove("draw:opacity");
  }
  else if (m_fillPattern == 26 || m_fillPattern == 29)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "axial");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[colourIndexFG]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[colourIndexBG]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    if (m_fillPattern == 26)
      m_styleProps.insert("draw:angle", 90);
    else
      m_styleProps.insert("draw:angle", 0);
  }
  else if (m_fillPattern >= 25 && m_fillPattern <= 34)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "linear");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[colourIndexBG]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[colourIndexFG]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    switch(m_fillPattern)
    {
    case 25:
      m_styleProps.insert("draw:angle", 270);
      break;
    case 27:
      m_styleProps.insert("draw:angle", 90);
      break;
    case 28:
      m_styleProps.insert("draw:angle", 180);
      break;
    case 30:
      m_styleProps.insert("draw:angle", 0);
      break;
    case 31:
      m_styleProps.insert("draw:angle", 225);
      break;
    case 32:
      m_styleProps.insert("draw:angle", 135);
      break;
    case 33:
      m_styleProps.insert("draw:angle", 315);
      break;
    case 34:
      m_styleProps.insert("draw:angle", 45);
      break;
    }
  }
  else if (m_fillPattern == 35)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "rectangular");
    m_styleProps.insert("svg:cx", 0.5, WPX_PERCENT);
    m_styleProps.insert("svg:cy", 0.5, WPX_PERCENT);
    m_styleProps.insert("draw:start-color", getColourString(m_colours[colourIndexBG]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[colourIndexFG]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:angle", 0);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);
  }
  else if (m_fillPattern >= 36 && m_fillPattern <= 40)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "radial");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[colourIndexBG]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[colourIndexFG]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    switch(m_fillPattern)
    {
    case 36:
      m_styleProps.insert("svg:cx", 0, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0, WPX_PERCENT);
      break;
    case 37:
      m_styleProps.insert("svg:cx", 1, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0, WPX_PERCENT);
      break;
    case 38:
      m_styleProps.insert("svg:cx", 0, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 1, WPX_PERCENT);
      break;
    case 39:
      m_styleProps.insert("svg:cx", 1, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 1, WPX_PERCENT);
      break;
    case 40:
      m_styleProps.insert("svg:cx", 0.5, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0.5, WPX_PERCENT);
      break;
    }
  }
  else
  // fill types we don't handle right, but let us approximate with solid fill
  {
    m_fillType = "solid";
    m_styleProps.insert("draw:fill-color", getColourString(m_colours[colourIndexBG]));
  }

  if (shadowPattern != 0)
  {
    m_styleProps.insert("draw:shadow","visible"); // for ODG
    m_styleProps.insert("draw:shadow-offset-x",shadowOffsetX);
    m_styleProps.insert("draw:shadow-offset-y",shadowOffsetY);
    m_styleProps.insert("draw:shadow-color",getColourString(shfgc));
    m_styleProps.insert("libwpg:shadow-color-r",(double)(shfgc.r/255.));
    m_styleProps.insert("libwpg:shadow-color-g",(double)(shfgc.g/255.));
    m_styleProps.insert("libwpg:shadow-color-b",(double)(shfgc.b/255.));
    m_styleProps.insert("draw:shadow-opacity",(double)(1 - shfgc.a/255.));
  }
  m_styleProps.insert("draw:fill", m_fillType);
}

void libvisio::VSDXContentCollector::collectFillAndShadow(unsigned id, unsigned level, unsigned colourIndexFG, unsigned colourIndexBG, unsigned fillPattern, unsigned fillFGTransparency, unsigned fillBGTransparency, unsigned shadowPattern, Colour shfgc)
{
  collectFillAndShadow(id, level, colourIndexFG, colourIndexBG, fillPattern, fillFGTransparency, fillBGTransparency, shadowPattern, shfgc, m_shadowOffsetX, m_shadowOffsetY);
}

void libvisio::VSDXContentCollector::collectForeignData(unsigned /* id */, unsigned level, const WPXBinaryData &binaryData)
{
  _handleLevelChange(level);
  if (m_foreignType == 1 || m_foreignType == 4) // Image
  {
    // If bmp data found, reconstruct header
    if (m_foreignType == 1 && m_foreignFormat == 0)
    {
      m_currentForeignData.append(0x42);
      m_currentForeignData.append(0x4d);

      m_currentForeignData.append((unsigned char)((binaryData.size() + 14) & 0x000000ff));
      m_currentForeignData.append((unsigned char)(((binaryData.size() + 14) & 0x0000ff00) >> 8));
      m_currentForeignData.append((unsigned char)(((binaryData.size() + 14) & 0x00ff0000) >> 16));
      m_currentForeignData.append((unsigned char)(((binaryData.size() + 14) & 0xff000000) >> 24));

      m_currentForeignData.append(0x00);
      m_currentForeignData.append(0x00);
      m_currentForeignData.append(0x00);
      m_currentForeignData.append(0x00);

      m_currentForeignData.append(0x36);
      m_currentForeignData.append(0x00);
      m_currentForeignData.append(0x00);
      m_currentForeignData.append(0x00);
    }
    m_currentForeignData.append(binaryData);

#if DUMP_BITMAP
    if (m_foreignType == 1 || m_foreignType == 4)
    {
      ::WPXString filename;
      switch(m_foreignFormat)
      {
      case 0:
        filename.sprintf("binarydump%i.bmp", bitmapId++); break;
      case 1:
        filename.sprintf("binarydump%i.jpeg", bitmapId++); break;
      case 2:
        filename.sprintf("binarydump%i.gif", bitmapId++); break;
      case 3:
        filename.sprintf("binarydump%i.tiff", bitmapId++); break;
      case 4:
        filename.sprintf("binarydump%i.png", bitmapId++); break;
      default:
        filename.sprintf("binarydump%i.bin", bitmapId++); break;
      }
      FILE *f = fopen(filename.cstr(), "wb");
      if (f)
      {
        const unsigned char *tmpBuffer = m_currentForeignData.getDataBuffer();
        for (unsigned long k = 0; k < m_currentForeignData.size(); k++)
          fprintf(f, "%c",tmpBuffer[k]);
        fclose(f);
      }
    }
#endif

    m_currentForeignProps.insert("svg:width", m_scale*m_xform.width);
    m_currentForeignProps.insert("svg:height", m_scale*m_xform.height);
    double x = 0.0; double y = 0.0;
    transformPoint(x,y);

    m_currentForeignProps.insert("svg:x", m_scale*x);
    // Y axis starts at the bottom not top
    m_currentForeignProps.insert("svg:y", m_scale*(y - m_xform.height));

    if (m_foreignType == 1)
    {
      switch(m_foreignFormat)
      {
      case 0:
        m_currentForeignProps.insert("libwpg:mime-type", "image/bmp"); break;
      case 1:
        m_currentForeignProps.insert("libwpg:mime-type", "image/jpeg"); break;
      case 2:
        m_currentForeignProps.insert("libwpg:mime-type", "image/gif"); break;
      case 3:
        m_currentForeignProps.insert("libwpg:mime-type", "image/tiff"); break;
      case 4:
        m_currentForeignProps.insert("libwpg:mime-type", "image/png"); break;
      }
    }
    else if (m_foreignType == 4)
    {
      const unsigned char *tmpBinData = m_currentForeignData.getDataBuffer();
      // Check for EMF signature
      if (tmpBinData[0x28] == 0x20 && tmpBinData[0x29] == 0x45 && tmpBinData[0x2A] == 0x4D && tmpBinData[0x2B] == 0x46)
      {
        m_currentForeignProps.insert("libwpg:mime-type", "image/emf");
      }
      else
      {
        m_currentForeignProps.insert("libwpg:mime-type", "image/wmf");
      }
    }
  }
}

void libvisio::VSDXContentCollector::collectGeomList(unsigned /* id */, unsigned level)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectCharList(unsigned /* id */, unsigned level)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectGeometry(unsigned /* id */, unsigned level, unsigned geomFlags)
{
  _handleLevelChange(level);
  m_x = 0.0; m_y = 0.0;
  m_originalX = 0.0; m_originalY = 0.0;
  bool noFill = ((geomFlags & 1) == 1);
  bool noLine = ((geomFlags & 2) == 2);
  bool noShow = ((geomFlags & 4) == 4);
  
  if ((m_noFill != noFill) || (m_noLine != noLine) || (m_noShow != noShow) || m_isFirstGeometry)
  {
    if (!m_hasLocalLineStyle && m_stencilShape)
    {
      if (m_stencilShape->m_lineStyle != 0 && !m_noLine)
        lineStyleFromStyleSheet(*(m_stencilShape->m_lineStyle));
      else if (m_stencilShape->m_lineStyleID != 0xffffffff)
        lineStyleFromStyleSheet(m_stencilShape->m_lineStyleID);
    }

    if (!m_hasLocalFillStyle && m_stencilShape && !m_noFill)
    {
      if (m_stencilShape->m_fillStyle != 0)
        fillStyleFromStyleSheet(*(m_stencilShape->m_fillStyle));
      else if (m_stencilShape->m_fillStyleID != 0xffffffff)
        fillStyleFromStyleSheet(m_stencilShape->m_fillStyleID);
    }
    _flushCurrentPath();
  }
  m_isFirstGeometry = false;
  m_noFill = noFill;
  m_noLine = noLine;
  m_noShow = noShow;
  if (m_noLine || m_linePattern == 0)
    m_styleProps.insert("svg:stroke-color", "none");
  else
    m_styleProps.insert("svg:stroke-color", m_lineColour);
  if (m_noFill || m_fillPattern == 0)
    m_styleProps.insert("draw:fill", "none");
  else
  {
    m_styleProps.insert("draw:fill", m_fillType);
    m_styleProps.insert("svg:fill-rule", "evenodd");
  }
  VSD_DEBUG_MSG(("Flag: %d NoFill: %d NoLine: %d NoShow: %d\n", geomFlags, m_noFill, m_noLine, m_noShow));
}

void libvisio::VSDXContentCollector::collectMoveTo(unsigned /* id */, unsigned level, double x, double y)
{
  _handleLevelChange(level);
  m_originalX = x; m_originalY = y;
  transformPoint(x, y);
  m_x = x;
  m_y = y;
  WPXPropertyList end;
  end.insert("svg:x", m_scale*m_x);
  end.insert("svg:y", m_scale*m_y);
  end.insert("libwpg:path-action", "M");
  m_currentGeometry.push_back(end);
}

void libvisio::VSDXContentCollector::collectLineTo(unsigned /* id */, unsigned level, double x, double y)
{
  _handleLevelChange(level);
  m_originalX = x; m_originalY = y;
  transformPoint(x, y);
  m_x = x;
  m_y = y;
  WPXPropertyList end;
  end.insert("svg:x", m_scale*m_x);
  end.insert("svg:y", m_scale*m_y);
  end.insert("libwpg:path-action", "L");
  m_currentGeometry.push_back(end);
}

void libvisio::VSDXContentCollector::collectArcTo(unsigned /* id */, unsigned level, double x2, double y2, double bow)
{
  _handleLevelChange(level);
  m_originalX = x2; m_originalY = y2;
  transformPoint(x2, y2);
  double angle = 0.0;
  transformAngle(angle);

  if (bow == 0)
  {
    m_x = x2; m_y = y2;
    WPXPropertyList end;
    end.insert("svg:x", m_scale*m_x);
    end.insert("svg:y", m_scale*m_y);
    end.insert("libwpg:path-action", "L");
    m_currentGeometry.push_back(end);
  }
  else
  {
    WPXPropertyList arc;
    double chord = sqrt(pow((y2 - m_y),2) + pow((x2 - m_x),2));
    double radius = (4 * bow * bow + chord * chord) / (8 * fabs(bow));
    int largeArc = fabs(bow) > radius ? 1 : 0;
    int sweep = bow < 0 ? 1 : 0;
    m_x = x2; m_y = y2;
    arc.insert("svg:rx", m_scale*radius);
    arc.insert("svg:ry", m_scale*radius);
    arc.insert("libwpg:rotate", angle*180/M_PI);
    arc.insert("libwpg:large-arc", largeArc);
    arc.insert("libwpg:sweep", sweep);
    arc.insert("svg:x", m_scale*m_x);
    arc.insert("svg:y", m_scale*m_y);
    arc.insert("libwpg:path-action", "A");
    m_currentGeometry.push_back(arc);
  }
}

#define VSD_NUM_POLYLINES_PER_NURBS 1000

void libvisio::VSDXContentCollector::collectNURBSTo(unsigned /* id */, unsigned level, double x2, double y2, unsigned xType, unsigned yType, unsigned degree, std::vector<std::pair<double, double> > controlPoints, std::vector<double> knotVector, std::vector<double> weights)
{
  _handleLevelChange(level);

  if (!knotVector.size() || !controlPoints.size() || !weights.size())
  // Here, maybe we should just draw line to (x2,y2)
    return;

  // Fill in end knots
  while (knotVector.size() < (controlPoints.size() + degree + 2))
    knotVector.push_back(knotVector.back());

  // Convert control points to static co-ordinates
  for (std::vector<std::pair<double, double> >::iterator it = controlPoints.begin();
       it != controlPoints.end(); it++)
  {
    if (xType == 0) // Percentage
      (*it).first *= m_xform.width;

    if (yType == 0) // Percentage
      (*it).second *= m_xform.height;
  }

  controlPoints.push_back(std::pair<double,double>(x2, y2));
  controlPoints.insert(controlPoints.begin(), std::pair<double, double>(m_originalX, m_originalY));

  // Generate NURBS using VSD_NUM_POLYLINES_PER_NURBS polylines
  WPXPropertyList NURBS;
  double step = (knotVector.back() - knotVector[0]) / VSD_NUM_POLYLINES_PER_NURBS;

  for (unsigned i = 0; i < VSD_NUM_POLYLINES_PER_NURBS; i++)
  {
    NURBS.clear();
    NURBS.insert("libwpg:path-action", "L");
    double nextX = 0; double nextY = 0; double denominator = 0.0000001;

    for (unsigned p = 0; p < controlPoints.size() && p < weights.size(); p++)
    {
      double basis = _NURBSBasis(p, degree, i * step, knotVector);
      nextX += basis * controlPoints[p].first * weights[p];
      nextY += basis * controlPoints[p].second * weights[p];
      denominator += weights[p] * basis;
    }
    nextX = (nextX/denominator);
    nextY = (nextY/denominator);
    transformPoint(nextX, nextY);
    NURBS.insert("svg:x", m_scale*nextX);
    NURBS.insert("svg:y", m_scale*nextY);
    m_currentGeometry.push_back(NURBS);
  }

  m_originalX = x2; m_originalY = y2;
  m_x = x2;
  m_y = y2;
  transformPoint(m_x, m_y);
}

double libvisio::VSDXContentCollector::_NURBSBasis(unsigned knot, unsigned degree, double point, const std::vector<double> &knotVector)
{
  double basis = 0;
  if (!knotVector.size())
    return basis;
  if (degree == 0)
  {
    if (knotVector[knot] <= point && point < knotVector[knot+1])
      return 1;
    else
      return 0;
  }
  if (knotVector.size() > knot+degree && knotVector[knot+degree]-knotVector[knot] > 0)
    basis = (point-knotVector[knot])/(knotVector[knot+degree]-knotVector[knot]) * _NURBSBasis(knot, degree-1, point, knotVector);

  if (knotVector.size() > knot+degree+1 && knotVector[knot+degree+1] - knotVector[knot+1] > 0)
    basis += (knotVector[knot+degree+1]-point)/(knotVector[knot+degree+1]-knotVector[knot+1]) * _NURBSBasis(knot+1, degree-1, point, knotVector);

  return basis;
}

/* NURBS with incomplete data */
void libvisio::VSDXContentCollector::collectNURBSTo(unsigned id, unsigned level, double x2, double y2, double knot, double knotPrev, double weight, double weightPrev, unsigned dataID)
{
  std::map<unsigned, NURBSData>::iterator iter = m_NURBSData.find(dataID);
  if (iter != m_NURBSData.end())
  {
    NURBSData data = iter->second;
    data.knots.push_back(knot);
    data.knots.push_back(data.lastKnot);
    data.knots.insert(data.knots.begin(), knotPrev);
    data.weights.push_back(weight);
    data.weights.insert(data.weights.begin(), weightPrev);

    collectNURBSTo(id, level, x2, y2, data.xType, data.yType, data.degree, data.points, data.knots, data.weights);
  }
  else
    _handleLevelChange(level);

}

void libvisio::VSDXContentCollector::collectPolylineTo(unsigned /* id */ , unsigned level, double x, double y, unsigned xType, unsigned yType, std::vector<std::pair<double, double> > &points)
{
  _handleLevelChange(level);

  WPXPropertyList polyline;
  for (unsigned i = 0; i< points.size(); i++)
  {
    polyline.clear();
    if (xType == 0)
      points[i].first *= m_xform.width;
    if (yType == 0)
      points[i].second *= m_xform.height;

    transformPoint(points[i].first, points[i].second);
    polyline.insert("libwpg:path-action", "L");
    polyline.insert("svg:x", points[i].first);
    polyline.insert("svg:y", points[i].second);
    m_currentGeometry.push_back(polyline);
  }

  m_originalX = x; m_originalY = y;
  m_x = x; m_y = y;
  transformPoint(m_x, m_y);
  polyline.insert("libwpg:path-action", "L");
  polyline.insert("svg:x", m_x);
  polyline.insert("svg:y", m_y);
  m_currentGeometry.push_back(polyline);
}

/* Polyline with incomplete data */
void libvisio::VSDXContentCollector::collectPolylineTo(unsigned id, unsigned level, double x, double y, unsigned dataID)
{
  std::map<unsigned, PolylineData>::iterator iter = m_polylineData.find(dataID);
  if (iter != m_polylineData.end())
  {
    PolylineData data = iter->second;
    collectPolylineTo(id, level, x, y, data.xType, data.yType, data.points);
  }
  else
    _handleLevelChange(level);
}

/* NURBS shape data */
void libvisio::VSDXContentCollector::collectShapeData(unsigned id, unsigned level, unsigned xType, unsigned yType, unsigned degree, double lastKnot, std::vector<std::pair<double, double> > controlPoints, std::vector<double> knotVector, std::vector<double> weights)
{
  _handleLevelChange(level);
  NURBSData data;
  data.xType = xType;
  data.yType = yType;
  data.degree = degree;
  data.lastKnot = lastKnot;
  data.points = controlPoints;
  data.knots = knotVector;
  data.weights = weights;
  m_NURBSData[id] = data;
}

/* Polyline shape data */
void libvisio::VSDXContentCollector::collectShapeData(unsigned id, unsigned level, unsigned xType, unsigned yType, std::vector<std::pair<double, double> > points)
{
  _handleLevelChange(level);
  PolylineData data;
  data.xType = xType;
  data.yType = yType;
  data.points = points;
  m_polylineData[id] = data;
}

void libvisio::VSDXContentCollector::collectXFormData(unsigned /* id */, unsigned level, const XForm &xform)
{
  _handleLevelChange(level);
  m_xform = xform;
}

void libvisio::VSDXContentCollector::collectTxtXForm(unsigned /* id */, unsigned level, const XForm &txtxform)
{
  _handleLevelChange(level);
  m_txtxform = txtxform;
}

void libvisio::VSDXContentCollector::transformPoint(double &x, double &y)
{
  // We are interested for the while in shapes xforms only
  if (!m_isShapeStarted)
    return;

  if (!m_currentShapeId)
    return;

  unsigned shapeId = m_currentShapeId;

  while (true)
  {
    std::map<unsigned, XForm>::iterator iterX = m_groupXForms.find(shapeId);
    if (iterX != m_groupXForms.end())
    {
      XForm xform = iterX->second;
      x -= xform.pinLocX;
      y -= xform.pinLocY;
      if (xform.flipX)
        x = xform.width - x - 2.0*xform.pinLocX;
      if (xform.flipY)
        y = xform.height -y - 2.0*xform.pinLocY;
      if (xform.angle != 0.0)
      {
        double tmpX = x*cos(xform.angle) - y*sin(xform.angle);
        double tmpY = y*cos(xform.angle) + x*sin(xform.angle);
        x = tmpX;
        y = tmpY;
      }
      x += xform.pinX;
      y += xform.pinY;
    }
    else
      break;
    std::map<unsigned, unsigned>::iterator iter = m_groupMemberships.find(shapeId);
    if (iter != m_groupMemberships.end())
      shapeId = iter->second;
    else
      break;
  }
  y = m_pageHeight - y;
}

void libvisio::VSDXContentCollector::transformAngle(double &angle)
{
  // We are interested for the while in shape xforms only
  if (!m_isShapeStarted)
    return;

  if (!m_currentShapeId)
    return;

  double x0 = m_xform.pinLocX;
  double y0 = m_xform.pinLocY;
  double x1 = m_xform.pinLocX + cos(angle);
  double y1 =m_xform.pinLocY + sin(angle);
  transformPoint(x0, y0);
  transformPoint(x1, y1);
  angle = fmod(2.0*M_PI + (y1 > y0 ? 1.0 : -1.0)*acos((x1-x0) / sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0))), 2.0*M_PI);
}

void libvisio::VSDXContentCollector::collectShapeId(unsigned /* id */, unsigned level, unsigned /* shapeId */)
{
  _handleLevelChange(level);
}


void libvisio::VSDXContentCollector::collectShapeList(unsigned /* id */, unsigned level)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectForeignDataType(unsigned /* id */, unsigned level, unsigned foreignType, unsigned foreignFormat)
{
  _handleLevelChange(level);
  m_foreignType = foreignType;
  m_foreignFormat = foreignFormat;
}

void libvisio::VSDXContentCollector::collectPageProps(unsigned /* id */, unsigned level, double pageWidth, double pageHeight, double shadowOffsetX, double shadowOffsetY)
{
  _handleLevelChange(level);
  m_pageWidth = pageWidth;
  m_pageHeight = pageHeight;
  m_shadowOffsetX = shadowOffsetX;
  m_shadowOffsetY = shadowOffsetY;
  WPXPropertyList pageProps;
  pageProps.insert("svg:width", m_scale*m_pageWidth);
  pageProps.insert("svg:height", m_scale*m_pageHeight);

  if (m_isPageStarted)
    m_painter->endGraphics();
  m_painter->startGraphics(pageProps);
  m_isPageStarted = true;
}

void libvisio::VSDXContentCollector::collectShape(unsigned id, unsigned level, unsigned masterPage, unsigned masterShape, unsigned lineStyleId, unsigned fillStyleId, unsigned /*textStyleId*/)
{
  _handleLevelChange(level);

  m_foreignType = 0; // Tracks current foreign data type
  m_foreignFormat = 0; // Tracks foreign data format

  m_originalX = 0.0; m_originalY = 0.0;
  m_x = 0; m_y = 0;

  // Geometry flags
  m_noLine = false;
  m_noFill = false;
  m_noShow = false;

  // Save line colour and pattern, fill type and pattern
  m_fillType = "none";
  m_fillPattern = 1; // same as "solid"
  m_fillFGTransparency = 0;
  m_fillBGTransparency = 0;

  // Reset style
  m_styleProps.clear();
  m_styleProps.insert("draw:fill", m_fillType);
  m_styleProps.insert("svg:stroke-dasharray", "solid");

  m_currentShapeId = id;
  m_pageOutput[m_currentShapeId] = VSDXOutputElementList();
  m_shapeOutput = &m_pageOutput[m_currentShapeId];
  m_isShapeStarted = true;
  m_isFirstGeometry = true;

  // Get stencil shape
  m_stencilShape = 0;
  if (masterPage != 0xffffffff && masterShape != 0xffffffff)
  {
    const VSDXStencil * stencil = m_stencils.getStencil(masterPage);
    if (stencil != 0) m_stencilShape = stencil->getStencilShape(masterShape);
  }
  
  m_hasLocalLineStyle = false;
  m_hasLocalFillStyle = false;
  if (lineStyleId != 0xffffffff)
  {
    lineStyleFromStyleSheet(lineStyleId);
    m_hasLocalLineStyle = true;
  }
  if (fillStyleId != 0xffffffff)
  {
    fillStyleFromStyleSheet(fillStyleId);
    m_hasLocalFillStyle = true;
  }
}

void libvisio::VSDXContentCollector::collectUnhandledChunk(unsigned /* id */, unsigned level)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectColours(const std::vector<Colour> &colours)
{
  m_colours.clear();
  m_colours.reserve(colours.size());
  for (unsigned i = 0; i < colours.size(); i++)
    m_colours.push_back(colours[i]);
}

void libvisio::VSDXContentCollector::collectFont(unsigned short fontID, const std::vector<unsigned char> &textStream, TextFormat format)
{
  WPXString fontname;
  if (format == VSD_TEXT_ANSI)
  {
    for (unsigned i = 0; i < textStream.size(); i++)
    {
      if (textStream[i] <= 0x20)
        _appendUCS4(fontname, (unsigned int) 0x20);
      else
        _appendUCS4(fontname, (unsigned int) textStream[i]);
    }
  }
  else if (format == VSD_TEXT_UTF16)
  {
    VSDInternalStream tmpStream(textStream, textStream.size());
    _appendUTF16LE(fontname, &tmpStream);
  }

  m_fonts[fontID] = fontname;
}


void libvisio::VSDXContentCollector::collectText(unsigned /*id*/, unsigned level, const std::vector<unsigned char> &textStream, TextFormat format)
{
  _handleLevelChange(level);

  m_textStream = textStream;
  m_textFormat = format;
  m_outputTextStart = true;
}

void libvisio::VSDXContentCollector::collectCharFormat(unsigned /*id*/ , unsigned level, unsigned charCount, unsigned short fontID, Colour fontColour, unsigned /*langId*/, double fontSize, bool bold, bool italic, bool /*underline*/, WPXString fontFace)
{
  _handleLevelChange(level);

  if (m_textStream.size() == 0) return;
  WPXString text;
  text.clear();
  if (m_outputTextStart)
  {  
    double angle = 0.0;
    transformAngle(angle);

    WPXPropertyList textCoords;
    textCoords.insert("svg:x", m_scale * m_x);
    textCoords.insert("svg:y", m_scale * m_y);
    textCoords.insert("svg:cx", m_scale * m_x);
    textCoords.insert("svg:cy", m_scale * m_y);
    textCoords.insert("libwpg:rotate", -angle*180/M_PI);

    m_shapeOutput->addStartTextObject(textCoords, WPXPropertyListVector());
    m_outputTextStart = false;
  }

  if (m_textFormat == VSD_TEXT_ANSI)
  {
    unsigned long max = charCount <= m_textStream.size() ? charCount : m_textStream.size();
    max = (charCount == 0 && m_textStream.size()) ? m_textStream.size() : max;
    for (unsigned i = 0; i < max; i++)
    {
      if (m_textStream[i] <= 0x20)
        _appendUCS4(text, (unsigned int) 0x20);
      else
        _appendUCS4(text, (unsigned int) m_textStream[i]);
    }

    m_textStream.erase(m_textStream.begin(), m_textStream.begin() + max);
  }
  else if (m_textFormat == VSD_TEXT_UTF16)
  {
    unsigned long max = charCount <= (m_textStream.size()/2) ? charCount : (m_textStream.size()/2);
    VSD_DEBUG_MSG(("Charcount: %d, max: %lu, stream size: %lu\n", charCount, max, (unsigned long)m_textStream.size()));
    max = (charCount == 0 && m_textStream.size()) ? m_textStream.size()/2 : max;
    VSD_DEBUG_MSG(("Charcount: %d, max: %lu, stream size: %lu\n", charCount, max, (unsigned long)m_textStream.size()));
    VSDInternalStream tmpStream(m_textStream, max*2);
    _appendUTF16LE(text, &tmpStream);
    
    m_textStream.erase(m_textStream.begin(), m_textStream.begin() + (max*2));
  }
  WPXPropertyList textProps;
  if (m_fonts[fontID] == "")
    textProps.insert("style:font-name", fontFace);
  else
    textProps.insert("style:font-name", m_fonts[fontID]);

  if (bold) textProps.insert("fo:font-weight", "bold");
  if (italic) textProps.insert("fo:font-style", "italic");
  textProps.insert("fo:font-size", fontSize*72.0, WPX_POINT);
  textProps.insert("fo:color",getColourString(fontColour));
  double opacity = 1.0;
  if (fontColour.a)
    opacity -= fontColour.a/255.0;
  textProps.insert("svg:stroke-opacity", opacity, WPX_PERCENT);
  textProps.insert("svg:fill-opacity", opacity, WPX_PERCENT);

  VSD_DEBUG_MSG(("Text: %s\n", text.cstr()));
  m_shapeOutput->addStartTextSpan(textProps);
  m_shapeOutput->addInsertText(text);
  m_shapeOutput->addEndTextSpan();

  if (m_textStream.size() == 0)
    m_shapeOutput->addEndTextObject();
}

void libvisio::VSDXContentCollector::collectStyleSheet(unsigned id, unsigned level, unsigned parentLineStyle, unsigned parentFillStyle, unsigned parentTextStyle)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectLineStyle(unsigned /* id */, unsigned level, double strokeWidth, Colour c, unsigned linePattern, unsigned lineCap)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectFillStyle(unsigned /*id*/, unsigned level, unsigned /*colourIndexFG*/, unsigned /*colourIndexBG*/, unsigned /*fillPattern*/, unsigned /*fillFGTransparency*/, unsigned /*fillBGTransparency*/, unsigned /*shadowPattern*/, Colour /*shfgc*/, double /*shadowOffsetX*/, double /*shadowOffsetY*/)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::collectFillStyle(unsigned /*id*/, unsigned level, unsigned /*colourIndexFG*/, unsigned /*colourIndexBG*/, unsigned /*fillPattern*/, unsigned /*fillFGTransparency*/, unsigned /*fillBGTransparency*/, unsigned /*shadowPattern*/, Colour /*shfgc*/)
{
  _handleLevelChange(level);
}

void libvisio::VSDXContentCollector::lineStyleFromStyleSheet(unsigned styleId)
{
  lineStyleFromStyleSheet(m_styles.getLineStyle(styleId));
}

void libvisio::VSDXContentCollector::lineStyleFromStyleSheet(const VSDXLineStyle &lineStyle)
{
  m_lineColour = getColourString(lineStyle.colour);
  m_linePattern = lineStyle.pattern;

  m_styleProps.insert("svg:stroke-width", m_scale*lineStyle.width);
  m_styleProps.insert("svg:stroke-color", m_lineColour);
  if (lineStyle.colour.a)
    m_styleProps.insert("svg:stroke-opacity", (1 - lineStyle.colour.a/255.0), WPX_PERCENT);
  else
    m_styleProps.insert("svg:stroke-opacity", 1.0, WPX_PERCENT);

  if (m_linePattern > 0)
  {  
    const char* patterns[] = {
      /*  0 */  "none",
      /*  1 */  "solid",
      /*  2 */  "6, 3",
      /*  3 */  "1, 3",
      /*  4 */  "6, 3, 1, 3",
      /*  5 */  "6, 3, 1, 3, 1, 3",
      /*  6 */  "6, 3, 6, 3, 1, 3",
      /*  7 */  "14, 2, 6, 2",
      /*  8 */  "14, 2, 6, 2, 6, 2",
      /*  9 */  "3, 1",
      /* 10 */  "1, 1",
      /* 11 */  "3, 1, 1, 1",
      /* 12 */  "3, 1, 1, 1, 1, 1",
      /* 13 */  "3, 1, 3, 1, 1, 1",
      /* 14 */  "7, 1, 3, 1",
      /* 15 */  "7, 1, 3, 1, 3, 1",
      /* 16 */  "11, 5",
      /* 17 */  "1, 5",
      /* 18 */  "11, 5, 1, 5",
      /* 19 */  "11, 5, 1, 5, 1, 5",
      /* 20 */  "11, 5, 11, 5, 1, 5",
      /* 21 */  "27, 5, 11, 5",
      /* 22 */  "27, 5, 11, 5, 11, 5",
      /* 23 */  "2, 1"
    };
    if (m_linePattern > 0 && m_linePattern < sizeof(patterns)/sizeof(patterns[0]))
      m_styleProps.insert("svg:stroke-dasharray", patterns[m_linePattern]);
  }

  switch (lineStyle.cap)
  {
    case 0:
      m_styleProps.insert("svg:stroke-linecap", "round");
      m_styleProps.insert("svg:stroke-linejoin", "round");
      break;
    case 2:
      m_styleProps.insert("svg:stroke-linecap", "square");
      m_styleProps.insert("svg:stroke-linejoin", "miter");
      break;
    default:
      m_styleProps.insert("svg:stroke-linecap", "butt");
      m_styleProps.insert("svg:stroke-linejoin", "miter");
      break;
  }
}

void libvisio::VSDXContentCollector::fillStyleFromStyleSheet(unsigned styleId)
{
  fillStyleFromStyleSheet(m_styles.getFillStyle(styleId));
}

void libvisio::VSDXContentCollector::fillStyleFromStyleSheet(const VSDXFillStyle &fillStyle)
{
  m_fillPattern = fillStyle.pattern;
  m_fillFGTransparency = fillStyle.fgTransparency;
  m_fillBGTransparency = fillStyle.bgTransparency;

  if (m_fillPattern == 0)
    m_fillType = "none";
  else if (m_fillPattern == 1)
  {
    m_fillType = "solid";
    m_styleProps.insert("draw:fill-color", getColourString(m_colours[fillStyle.fgColourId]));
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("draw:opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.remove("draw:opacity");
  }
  else if (m_fillPattern == 26 || m_fillPattern == 29)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "axial");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[fillStyle.fgColourId]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[fillStyle.bgColourId]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    if (m_fillPattern == 26)
      m_styleProps.insert("draw:angle", 90);
    else
      m_styleProps.insert("draw:angle", 0);
  }
  else if (m_fillPattern >= 25 && m_fillPattern <= 34)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "linear");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[fillStyle.bgColourId]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[fillStyle.fgColourId]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    switch(m_fillPattern)
    {
    case 25:
      m_styleProps.insert("draw:angle", 270);
      break;
    case 27:
      m_styleProps.insert("draw:angle", 90);
      break;
    case 28:
      m_styleProps.insert("draw:angle", 180);
      break;
    case 30:
      m_styleProps.insert("draw:angle", 0);
      break;
    case 31:
      m_styleProps.insert("draw:angle", 225);
      break;
    case 32:
      m_styleProps.insert("draw:angle", 135);
      break;
    case 33:
      m_styleProps.insert("draw:angle", 315);
      break;
    case 34:
      m_styleProps.insert("draw:angle", 45);
      break;
    }
  }
  else if (m_fillPattern == 35)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "rectangular");
    m_styleProps.insert("svg:cx", 0.5, WPX_PERCENT);
    m_styleProps.insert("svg:cy", 0.5, WPX_PERCENT);
    m_styleProps.insert("draw:start-color", getColourString(m_colours[fillStyle.fgColourId]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[fillStyle.bgColourId]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:angle", 0);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);
  }
  else if (m_fillPattern >= 36 && m_fillPattern <= 40)
  {
    m_fillType = "gradient";
    m_styleProps.insert("draw:style", "radial");
    m_styleProps.insert("draw:start-color", getColourString(m_colours[fillStyle.bgColourId]));
    m_styleProps.insert("draw:end-color", getColourString(m_colours[fillStyle.fgColourId]));
    m_styleProps.remove("draw:opacity");
    if (m_fillBGTransparency > 0)
      m_styleProps.insert("libwpg:start-opacity", (double)(1 - m_fillBGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:start-opacity", 1, WPX_PERCENT);
    if (m_fillFGTransparency > 0)
      m_styleProps.insert("libwpg:end-opacity", (double)(1 - m_fillFGTransparency/255.0), WPX_PERCENT);
    else
      m_styleProps.insert("libwpg:end-opacity", 1, WPX_PERCENT);
    m_styleProps.insert("draw:border", 0, WPX_PERCENT);

    switch(m_fillPattern)
    {
    case 36:
      m_styleProps.insert("svg:cx", 0, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0, WPX_PERCENT);
      break;
    case 37:
      m_styleProps.insert("svg:cx", 1, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0, WPX_PERCENT);
      break;
    case 38:
      m_styleProps.insert("svg:cx", 0, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 1, WPX_PERCENT);
      break;
    case 39:
      m_styleProps.insert("svg:cx", 1, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 1, WPX_PERCENT);
      break;
    case 40:
      m_styleProps.insert("svg:cx", 0.5, WPX_PERCENT);
      m_styleProps.insert("svg:cy", 0.5, WPX_PERCENT);
      break;
    }
  }
  else
  // fill types we don't handle right, but let us approximate with solid fill
  {
    m_fillType = "solid";
    m_styleProps.insert("draw:fill-color", getColourString(m_colours[fillStyle.bgColourId]));
  }

  if (fillStyle.shadowPattern != 0)
  {
    m_styleProps.insert("draw:shadow","visible"); // for ODG
    m_styleProps.insert("draw:shadow-offset-x", fillStyle.shadowOffsetX);
    m_styleProps.insert("draw:shadow-offset-y", fillStyle.shadowOffsetY);
    m_styleProps.insert("draw:shadow-color",getColourString(fillStyle.shadowFgColour));
    m_styleProps.insert("libwpg:shadow-color-r",(double)(fillStyle.shadowFgColour.r/255.));
    m_styleProps.insert("libwpg:shadow-color-g",(double)(fillStyle.shadowFgColour.g/255.));
    m_styleProps.insert("libwpg:shadow-color-b",(double)(fillStyle.shadowFgColour.b/255.));
    m_styleProps.insert("draw:shadow-opacity",(double)(1 - fillStyle.shadowFgColour.a/255.));
  }
  m_styleProps.insert("draw:fill", m_fillType);  
}

void libvisio::VSDXContentCollector::_handleLevelChange(unsigned level)
{
  if (m_currentLevel == level)
    return;
  if (level < 2)
  {
    if (m_isShapeStarted)
    {
      if (m_stencilShape != 0 && !m_isStencilStarted)
      {
        m_isStencilStarted = true;
        m_NURBSData = m_stencilShape->m_nurbsData;
        m_polylineData = m_stencilShape->m_polylineData;

        if (m_stencilShape->m_foreign != 0)
        {
          collectForeignDataType(m_stencilShape->m_foreign->typeId, m_stencilShape->m_foreign->typeLevel, m_stencilShape->m_foreign->type, m_stencilShape->m_foreign->format);
          
          // Messy - this is set to false in _handleLevelChange() called
          // by collectForeignDataType() so make sure it's true
          m_isShapeStarted = true;
          collectForeignData(m_stencilShape->m_foreign->dataId, m_stencilShape->m_foreign->dataLevel, m_stencilShape->m_foreign->data);
        }

        if (!m_hasLocalLineStyle && !m_noLine)
        {
          if (m_stencilShape->m_lineStyle != 0)
            lineStyleFromStyleSheet(*(m_stencilShape->m_lineStyle));
          else if (m_stencilShape->m_lineStyleID != 0xffffffff)
            lineStyleFromStyleSheet(m_stencilShape->m_lineStyleID);
        }

        if (!m_hasLocalFillStyle && !m_noFill)
        {
          if (m_stencilShape->m_fillStyle != 0)
            fillStyleFromStyleSheet(*(m_stencilShape->m_fillStyle));
          else if (m_stencilShape->m_fillStyleID != 0xffffffff)
            fillStyleFromStyleSheet(m_stencilShape->m_fillStyleID);
        }

        if (m_currentGeometry.size() == 0)
        {
          for (unsigned i = 0; i < m_stencilShape->m_geometries.size(); i++)
          {
            m_x = 0.0; m_y = 0.0;
            m_stencilShape->m_geometries[i].handle(this);
          }
        }
        m_isStencilStarted = false;
      }

      _flushCurrentPath();
      _flushCurrentForeignData();
      m_isShapeStarted = false;
    }
    m_originalX = 0.0; m_originalY = 0.0;
    m_x = 0; m_y = 0;
    m_NURBSData.clear();
    m_polylineData.clear();
  }

  m_currentLevel = level;
}


void libvisio::VSDXContentCollector::startPage()
{
  if (m_isShapeStarted)
  {
    _flushCurrentPath();
    _flushCurrentForeignData();
    m_isShapeStarted = false;
  }
  m_originalX = 0.0; m_originalY = 0.0;
  m_x = 0; m_y = 0;
  m_currentPageNumber++;
  if (m_groupXFormsSequence.size() >= m_currentPageNumber)
    m_groupXForms = m_groupXFormsSequence[m_currentPageNumber-1];
  if (m_groupMembershipsSequence.size() >= m_currentPageNumber)
    m_groupMemberships = m_groupMembershipsSequence[m_currentPageNumber-1];
  if (m_documentPageShapeOrders.size() >= m_currentPageNumber)
    m_pageShapeOrder = m_documentPageShapeOrders[m_currentPageNumber-1];
}

void libvisio::VSDXContentCollector::endPage()
{
  // End page if one is started
  if (m_isPageStarted)
  {
    _handleLevelChange(0);
    _flushCurrentPage();

    m_painter->endGraphics();
    m_isPageStarted = false;
  }
}

#define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)

void libvisio::VSDXContentCollector::_appendUTF16LE(WPXString &text, WPXInputStream *input)
{
  while (!input->atEOS())
  {
    uint16_t high_surrogate = 0;
    bool fail = false;
    uint32_t ucs4Character;
    while (true)
    {
      if (input->atEOS())
      {
        fail = true;
        break;
      }
      uint16_t character = readU16(input);
      if (character >= 0xdc00 && character < 0xe000) /* low surrogate */
      {
        if (high_surrogate)
        {
          ucs4Character = SURROGATE_VALUE(high_surrogate, character);
          high_surrogate = 0;
          break;
        }
        else
        {
          fail = true;
          break;
        }
      }
      else
      {
        if (high_surrogate)
        {
          fail = true;
          break;
        }
        if (character >= 0xd800 && character < 0xdc00) /* high surrogate */
          high_surrogate = character;
        else
        {
          ucs4Character = character;
          break;
        }
      }
    }
    if (fail)
      throw GenericException();

    _appendUCS4(text, ucs4Character);
  }
}

void libvisio::VSDXContentCollector::_appendUCS4(WPXString &text, unsigned int ucs4Character)
{
  unsigned char first;
  int len;
  if (ucs4Character < 0x80)
  {
    first = 0;
    len = 1;
  }
  else if (ucs4Character < 0x800)
  {
    first = 0xc0;
    len = 2;
  }
  else if (ucs4Character < 0x10000)
  {
    first = 0xe0;
    len = 3;
  }
  else if (ucs4Character < 0x200000)
  {
    first = 0xf0;
    len = 4;
  }
  else if (ucs4Character < 0x4000000)
  {
    first = 0xf8;
    len = 5;
  }
  else
  {
    first = 0xfc;
    len = 6;
  }

  unsigned char outbuf[6] = { 0, 0, 0, 0, 0, 0 };
  int i;
  for (i = len - 1; i > 0; --i)
  {
    outbuf[i] = (ucs4Character & 0x3f) | 0x80;
    ucs4Character >>= 6;
  }
  outbuf[0] = ucs4Character | first;

  for (i = 0; i < len; i++)
    text.append(outbuf[i]);
}