Debian Codegraph @

src/lib/Canvas5Structure.cxx

raw
1 /* -*- Mode: C++; c-default-style: "k&r"; indent-tabs-mode: nil; tab-width: 2; c-basic-offset: 2 -*- */
2
3 /* libmwaw
4 * Version: MPL 2.0 / LGPLv2+
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 2.0 (the "License"); you may not use this file except in compliance with
8 * the License or as specified alternatively below. You may obtain a copy of
9 * the License at http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * Major Contributor(s):
17 * Copyright (C) 2002 William Lachance ([email protected])
18 * Copyright (C) 2002,2004 Marc Maurer ([email protected])
19 * Copyright (C) 2004-2006 Fridrich Strba ([email protected])
20 * Copyright (C) 2006, 2007 Andrew Ziem
21 * Copyright (C) 2011, 2012 Alonso Laurent ([email protected])
22 *
23 *
24 * All Rights Reserved.
25 *
26 * For minor contributions see the git repository.
27 *
28 * Alternatively, the contents of this file may be used under the terms of
29 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
30 * in which case the provisions of the LGPLv2+ are applicable
31 * instead of those above.
32 */
33
34 #include <iomanip>
35 #include <iostream>
36 #include <set>
37 #include <vector>
38
39 #include "MWAWStringStream.hxx"
40 #include "MWAWPictBitmap.hxx"
41
42 #include "Canvas5Structure.hxx"
43
44 namespace Canvas5Structure
45 {
46
47 std::string getString(unsigned val)
48 {
49 if (val<20) return std::to_string(val);
50 std::string res;
51 for (int dec=24; dec>=0; dec-=8) {
52 char c=char((val>>dec)&0xff);
53 if (!std::isprint(c))
54 return std::to_string(val);
55 res+=c;
56 }
57 return res;
58 }
59
60 bool readBitmap(Stream &stream, int version, MWAWEmbeddedObject &object, MWAWColor *avgColor)
61 {
62 object=MWAWEmbeddedObject();
63 auto input=stream.input();
64 long pos=input->tell();
65 libmwaw::DebugStream f;
66 auto &ascFile=stream.ascii();
67 f << "Entries(Bitmap):";
68 int type0=int(input->readULong(4)); // found type0=5 in texture bw bitmap
69 if (type0!=6) f << "type0=" << type0 << ",";
70 if (!input->checkPosition(pos+64) || (type0!=5 && type0!=6)) {
71 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: the zone beginning seems bad\n"));
72 f << "###";
73 ascFile.addPos(pos);
74 ascFile.addNote(f.str().c_str());
75 return false;
76 }
77 int type=int(input->readLong(2)); // 1-3
78 switch (type) {
79 case 0:
80 f << "bw[indexed],"; // 1 bool by bytes
81 break;
82 case 1:
83 f << "bw[color],"; // 1 plane
84 break;
85 case 2:
86 f << "indexed,"; // 1 plane, color map
87 break;
88 case 3:
89 f << "color,"; // with 3 planes
90 break;
91 case 4:
92 f << "color4,"; // with 4 planes
93 break;
94 default:
95 f << "##type=" << type << ",";
96 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: unexpected type\n"));
97 ascFile.addPos(pos);
98 ascFile.addNote(f.str().c_str());
99 return false;
100 }
101 int numBytes=int(input->readLong(2)); // number of byte?
102 if (numBytes!=8) {
103 if (numBytes==1 && type==0)
104 f << "num[bytes]=1,";
105 else {
106 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: oops, find a number of bytes unexpected, unimplemented\n"));
107 f << "##num[bytes]=" << numBytes << ",";
108 }
109 }
110 int dim[2];
111 for (auto &d : dim) d=int(input->readULong(4));
112 MWAWVec2i dimension(dim[1], dim[0]);
113 f << "dim=" << dimension << ",";
114 int numPlanes=int(input->readLong(2)); // 1-4
115 int val=int(input->readLong(2)); // val
116 if (numPlanes!=val)
117 f << "num[planes]=" << numPlanes << "x" << val << ",";
118 else if (numPlanes!=1) f << "f2=" << val << ",";
119 float fDim[2];
120 for (auto &v : fDim) v=float(input->readULong(4))/65536.f;
121 if (MWAWVec2f(fDim[0],fDim[1])!=MWAWVec2f(72,72))
122 f << "fDim=" << MWAWVec2f(fDim[0],fDim[1]) << ",";
123 for (int i=0; i<4; ++i) { // 0
124 val=int(input->readLong(2));
125 if (val)
126 f << "f" << i+3 << "=" << val << ",";
127 }
128 for (auto &d : dim) d=int(input->readULong(4));
129 MWAWVec2i dim1(dim[1], dim[0]);
130 if (dimension!=dim1)
131 f << "dim1=" << dim1 << ",";
132 ascFile.addPos(pos);
133 ascFile.addNote(f.str().c_str());
134
135 // FIXME: find correctly the data, color positions
136 // but only reconstruct correctly small bitmaps :-~
137 std::shared_ptr<MWAWPictBitmapIndexed> bitmapIndexed;
138 std::shared_ptr<MWAWPictBitmapColor> bitmapColor;
139 switch (type) {
140 case 0:
141 case 2:
142 bitmapIndexed.reset(new MWAWPictBitmapIndexed(dimension));
143 break;
144 case 1:
145 case 3:
146 case 4:
147 default:
148 bitmapColor.reset(new MWAWPictBitmapColor(dimension));
149 break;
150 }
151
152 pos=input->tell();
153 int const width=type==0 ? (dimension[0]+7)/8 : dimension[0];
154 int const planeHeaderLength=(version<9 ? 20 : 40);
155 long dataLength=((type==3||type==4) ? numPlanes : 1)*(planeHeaderLength+width*dimension[1]);
156 if (width<=0 || dimension[1]<=0 || pos+dataLength<pos || !input->checkPosition(pos+dataLength)) {
157 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: can not find the bitmap data\n"));
158 f << "###";
159 ascFile.addPos(pos);
160 ascFile.addNote(f.str().c_str());
161 return false;
162 }
163
164 long dataPos=pos;
165 // first read the color map
166 input->seek(pos+dataLength, librevenge::RVNG_SEEK_SET);
167 pos=input->tell();
168 long len=input->readLong(4);
169 if (pos+4+(len?4:0)+len<pos+4 || !input->checkPosition(pos+4+(len?4:0)+len)) {
170 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: can not find the color block\n"));
171 ascFile.addPos(pos);
172 ascFile.addNote("Bitmap[color]:###");
173 return false;
174 }
175 if (len==0) {
176 ascFile.addPos(pos);
177 ascFile.addNote("_");
178 }
179 else {
180 input->seek(4, librevenge::RVNG_SEEK_CUR);
181 unsigned long numBytesRead;
182 auto *data=input->read(size_t(len), numBytesRead);
183 if (!data || long(numBytesRead)!=len) {
184 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmap: can not find the color block\n"));
185 ascFile.addPos(pos);
186 ascFile.addNote("Bitmap[color]:###");
187 return false;
188 }
189 size_t N=size_t(len/3);
190 std::vector<MWAWColor> colors(N);
191 for (size_t c=0; c<N; ++c) colors[c]=MWAWColor(data[c],data[c+N],data[c+2*N]);
192 if (type==2)
193 bitmapIndexed->setColors(colors);
194 ascFile.addPos(pos);
195 ascFile.addNote("Bitmap[color]:");
196 ascFile.skipZone(pos+8, pos+8+len-1);
197 }
198 long endPos=input->tell();
199 if (type==0)
200 bitmapIndexed->setColors({MWAWColor::black(), MWAWColor::white()});
201 // now read the bitmap data
202 input->seek(dataPos, librevenge::RVNG_SEEK_SET);
203 for (int plane=0; plane<((type==3||type==4) ? numPlanes : 1); ++plane) {
204 pos=input->tell();
205 f.str("");
206 f << "Bitmap-P" << plane << ":";
207 for (int i=0; i<3; ++i) {
208 val=int(input->readLong(4));
209 int const expected[]= {2 /* or 3*/,8,1};
210 if (val==expected[i]) continue;
211 if (i==1)
212 f << "num[bytes]=" << val << ",";
213 else
214 f << "g" << i << "=" << val << ",";
215 }
216 for (auto &d : dim) d=int(input->readULong(4));
217 dim1=MWAWVec2i(dim[1], dim[0]);
218 if (dimension!=dim1)
219 f << "dim2=" << dim1 << ",";
220 input->seek(pos+planeHeaderLength, librevenge::RVNG_SEEK_SET);
221 ascFile.addPos(pos);
222 ascFile.addNote(f.str().c_str());
223
224 if (type==0) {
225 // checkme: is the picture decomposed by block if dim[0]>128*8 or dim[1]>128 ?
226 for (int y=0; y<dimension[1]; ++y) {
227 int x=0;
228 for (int w=0; w<width; ++w) {
229 val=int(input->readULong(1));
230 for (int v=0, depl=0x80; v<8; ++v, depl>>=1) {
231 if (x>=dimension[0])
232 break;
233 bitmapIndexed->set(x++,y, (val&depl) ? 0 : 1);
234 }
235 }
236 }
237 }
238 else {
239 for (int nY=0; nY<(dimension[1]+127)/128; ++nY) {
240 for (int nW=0; nW<(dimension[0]+127)/128; ++nW) {
241 for (int y=128*nY; y<std::min(dimension[1], 128*(nY+1)); ++y) {
242 for (int w=128*nW; w<std::min(dimension[0], 128*(nW+1)); ++w) {
243 unsigned char c=(unsigned char)input->readULong(1);
244 if (type==1)
245 bitmapColor->set(w,y, MWAWColor(c,c,c));
246 else if (type==2)
247 bitmapIndexed->set(w,y,c);
248 else {
249 if (plane==0)
250 bitmapColor->set(w,y,MWAWColor(c,0,0));
251 else {
252 int const decal=plane==3 ? 24 : (16-(8*plane));
253 uint32_t finalValue=bitmapColor->get(w,y).value()|(uint32_t(c)<<decal);
254 bitmapColor->set(w,y,MWAWColor(finalValue));
255 }
256 }
257 }
258 }
259 }
260 }
261 }
262 ascFile.skipZone(dataPos+20, dataPos+dataLength-1);
263 }
264 input->seek(endPos, librevenge::RVNG_SEEK_SET);
265
266 bool ok=false;
267 if (type==0 || type==2) {
268 ok=bitmapIndexed->getBinary(object);
269 if (ok && avgColor) *avgColor=bitmapIndexed->getAverageColor();
270 }
271 else if (type==1 || type==3 || type==4) {
272 ok=bitmapColor->getBinary(object);
273 if (ok && avgColor) *avgColor=bitmapColor->getAverageColor();
274 }
275 #ifdef DEBUG_WITH_FILES
276 if (ok && !object.m_dataList.empty()) {
277 std::stringstream s;
278 static int index=0;
279 s << "file" << ++index << ".png";
280 libmwaw::Debug::dumpFile(object.m_dataList[0], s.str().c_str());
281 }
282 #endif
283 return ok && !object.m_dataList.empty();
284 }
285
286 bool readBitmapDAD58Bim(Stream &stream, int version, MWAWEmbeddedObject &object)
287 {
288 if (!readBitmap(stream, version, object))
289 return false;
290
291 auto input=stream.input();
292 long pos=input->tell();
293 auto &ascFile=stream.ascii();
294
295 // DAD5 block
296 libmwaw::DebugStream f;
297 f << "Bitmap[DAD5]:";
298 if (!input->checkPosition(pos+12)) {
299 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: can not find the DAD5 block\n"));
300 f << "###";
301 ascFile.addPos(pos);
302 ascFile.addNote(f.str().c_str());
303 return false;
304 }
305 int val=int(input->readLong(4));
306 if (val!=1) // checkme: val=0 means probably no data
307 f << "f0=" << val << ",";
308 f << "len?=" << std::hex << input->readULong(4) << std::dec << ",";
309 int N=int(input->readULong(4)); // 1-3
310 f << "N=" << N << ",";
311 if (N<0 || (input->size()-pos-12)/16<N || pos+12+16*N<pos+12 || !input->checkPosition(pos+12+16*N)) {
312 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5]: can not find the number of subblock\n"));
313 f << "###";
314 ascFile.addPos(pos);
315 ascFile.addNote(f.str().c_str());
316 return false;
317 }
318 ascFile.addPos(pos);
319 ascFile.addNote(f.str().c_str());
320
321 for (int j=0; j<N; ++j) {
322 pos=input->tell();
323 f.str("");
324 f << "Bitmap[DAD5-A" << j << "]:";
325 if (!input->checkPosition(pos+16)) {
326 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5]: can not read subblock %d\n", j));
327 f << "###";
328 ascFile.addPos(pos);
329 ascFile.addNote(f.str().c_str());
330 return false;
331 }
332 unsigned types[2];
333 for (auto &t : types) t=unsigned(input->readULong(4));
334 f << getString(types[0]) << ":" << getString(types[1]) << ",";
335 val=int(input->readLong(4));
336 if (val!=1) f << "f0=" << val << ",";
337 long len=input->readLong(4);
338 if (len<0 || pos+16+len<pos+16 || !input->checkPosition(pos+16+len)) {
339 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5]: can not read subblock %d length\n", j));
340 f << "###len=" << len << ",";
341 ascFile.addPos(pos);
342 ascFile.addNote(f.str().c_str());
343 return false;
344 }
345 // DAD5::VISM (size 8), DAD5::hack (size 8c) or DAD5::1 (size variable, ie end with a string)
346 if (types[0]==0x44414435) {
347 switch (types[1]) {
348 case 1: {
349 std::string name;
350 for (int k=0; k<len; ++k) {
351 char c=char(input->readULong(1));
352 if (c==0)
353 break;
354 name+=c;
355 }
356 f << "path=" << name << ",";
357 break;
358 }
359 case 0x6861636b: {
360 if (len!=0x8c) {
361 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5,hack]: unexpected length\n"));
362 f << "###";
363 break;
364 }
365 for (int k=0; k<2; ++k) { // 0
366 val=int(input->readLong(4));
367 if (val)
368 f << "f" << k+1 << "=" << val << ",";
369 }
370 int maxN=int(input->readLong(4));
371 f << "maxN=" << maxN << ",";
372 f << "unkn=[";
373 for (int k=0; k<32; ++k) { // unsure where to stop
374 val=int(input->readLong(4));
375 if (val<=0 || val>maxN) break;
376 f << val << ",";
377 }
378 f << "],";
379 ascFile.addDelimiter(input->tell(),'|');
380 break;
381 }
382 case 0x5649534d: // VISM
383 if (len!=8) {
384 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5,VISM]: unexpected length\n"));
385 f << "###";
386 break;
387 }
388 val=int(input->readLong(4)); // 0-1
389 if (val)
390 f << "f1=" << val << ",";
391 val=int(input->readLong(4));
392 if (val!=-1)
393 f << "f2=" << val << ",";
394 break;
395 default:
396 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5]: unexpected type for sub zone\n"));
397 f << "###";
398 break;
399 }
400 }
401 else {
402 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[DAD5]: find unknown type0 for subblock %d\n", j));
403 f << "###";
404 }
405 ascFile.addPos(pos);
406 ascFile.addNote(f.str().c_str());
407 input->seek(pos+16+len, librevenge::RVNG_SEEK_SET);
408 }
409
410 // last block: 8BIM
411 pos=input->tell();
412 long len=input->readLong(4);
413 f.str("");
414 f << "Bitmap[8bim]:";
415 long endBimBlock=pos+4+len;
416 if (len<0 || endBimBlock<pos+4 || !input->checkPosition(endBimBlock)) {
417 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: can not read 8bim block\n"));
418 f << "###";
419 ascFile.addPos(pos);
420 ascFile.addNote(f.str().c_str());
421 return false;
422 }
423 ascFile.addPos(pos);
424 ascFile.addNote(f.str().c_str());
425 while (input->tell()<endBimBlock) {
426 pos=input->tell();
427 f.str("");
428 f << "Bitmap[8bim]:";
429 if (pos+12>endBimBlock) {
430 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: a 8bim block seems bad\n"));
431 f << "###";
432 ascFile.addPos(pos);
433 ascFile.addNote(f.str().c_str());
434 break;
435 }
436 unsigned type=unsigned(input->readULong(4));
437 f << getString(type) << ","; // 8BIM
438 int id=int(input->readLong(2));
439 f << "id=" << id << ",";
440 val=int(input->readLong(2));
441 if (val)
442 f << "f0=" << val << ",";
443 len=input->readLong(4);
444 if (len<0 || pos+12+len>endBimBlock) {
445 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: a 8bim block len seems bad\n"));
446 f << "###";
447 ascFile.addPos(pos);
448 ascFile.addNote(f.str().c_str());
449 break;
450 }
451 switch (type) {
452 case 0x3842494d:
453 switch (id) {
454 case 1006:
455 if (len==0)
456 break;
457 else {
458 int sSz=int(input->readULong(1));
459 if (1+sSz>len) {
460 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[8bim,1006]: can not find the string size\n"));
461 f << "###";
462 break;
463 }
464 std::string name;
465 for (int k=0; k<sSz; ++k) {
466 char c=char(input->readULong(1));
467 if (!c)
468 break;
469 name+=c;
470 }
471 f << name << ",";
472 }
473 break;
474 case 1007: {
475 if ((len%14)!=0) {
476 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[8bim,1007]: the size seems bad\n"));
477 f << "###";
478 break;
479 }
480 int nUnkn=int(len/14);
481 f << "unkn=[";
482 for (int k=0; k<nUnkn; ++k) {
483 f << "[";
484 for (int l=0; l<7; ++l) {
485 val=int(input->readLong(2));
486 int const expected[]= {0,0/* or 255*/,0,0,0,50 /* or 100 */, 0};
487 if (val!=expected[l])
488 f << "f" << l << "=" << val << ",";
489 }
490 f << "],";
491 }
492 f << "],";
493 break;
494 }
495 default:
496 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[8bim]: unknown id=%d\n", id));
497 f << "###";
498 break;
499 }
500 break;
501 default:
502 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim[8bim]: unknown type=%s\n", getString(type).c_str()));
503 f << "###";
504 }
505 if (input->tell()!=pos+12+len)
506 ascFile.addDelimiter(input->tell(),'|');
507 input->seek(pos+12+len, librevenge::RVNG_SEEK_SET);
508 ascFile.addPos(pos);
509 ascFile.addNote(f.str().c_str());
510 }
511
512 input->seek(endBimBlock, librevenge::RVNG_SEEK_SET);
513
514 if (version<9)
515 return true;
516
517 if (input->isEnd()) // bitmap in cvi file ends here
518 return true;
519 // last block: unknown
520 pos=input->tell();
521 len=input->readLong(4);
522 f.str("");
523 f << "Bitmap[unknown]:";
524 long endUnknownBlock=pos+4+len;
525 if (len<0 || endUnknownBlock<pos+4 || !input->checkPosition(endUnknownBlock)) {
526 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: can not read unknown block\n"));
527 f << "###";
528 ascFile.addPos(pos);
529 ascFile.addNote(f.str().c_str());
530 return false;
531 }
532 if (len) {
533 MWAW_DEBUG_MSG(("Canvas5Structure::readBitmapDAD58Bim: find an unknown block\n"));
534 f << "###";
535 ascFile.addPos(pos);
536 ascFile.addNote(f.str().c_str());
537 input->seek(endUnknownBlock, librevenge::RVNG_SEEK_SET);
538 }
539 else {
540 ascFile.addPos(pos);
541 ascFile.addNote("_");
542 }
543 return true;
544 }
545
546 bool readPreview(Stream &stream, bool hasPreviewBitmap)
547 {
548 auto input=stream.input();
549 if (!input) return false;
550 long pos=input->tell();
551 if (!input->checkPosition(pos+12+(hasPreviewBitmap ? 12 : 0))) {
552 MWAW_DEBUG_MSG(("Canvas5Structure::readPreview: the zone is too short\n"));
553 return false;
554 }
555 libmwaw::DebugStream f;
556 auto &ascFile=stream.ascii();
557 f << "Entries(Preview):";
558 int dims[3];
559 for (auto &d : dims) d=int(input->readLong(4));
560 f << "dim=" << MWAWVec2i(dims[1], dims[0]) << "[" << dims[2] << "],";
561 int width=hasPreviewBitmap ? int(input->readLong(4)) : 0;
562 if (width) f << "w=" << width << ",";
563 long endPos=pos+(hasPreviewBitmap ? 24 : 12)+long(width*dims[0]);
564 if (!hasPreviewBitmap || dims[0]<=0 || dims[1]<=0 || dims[2]!=3 || width<dims[1]*dims[2] ||
565 endPos<=pos+24 || !input->checkPosition(endPos)) {
566 if (dims[0]==0 && dims[1]==0 && input->checkPosition(endPos)) {
567 ascFile.addPos(pos);
568 ascFile.addNote(f.str().c_str());
569 input->seek(endPos, librevenge::RVNG_SEEK_SET);
570 ascFile.skipZone(input->tell(), endPos-1);
571 return true;
572 }
573 f << "###";
574 MWAW_DEBUG_MSG(("Canvas5Structure::readPreview: the dimensions seems bad\n"));
575 ascFile.addPos(pos);
576 ascFile.addNote(f.str().c_str());
577 return false;
578 }
579 for (int i=0; i<2; ++i) {
580 int val=int(input->readLong(4));
581 int const expected[]= {3,1};
582 if (val!=expected[i])
583 f << "f" << i << "=" << val << ",";
584 }
585 ascFile.addPos(pos);
586 ascFile.addNote(f.str().c_str());
587
588 pos=input->tell();
589 MWAWPictBitmapColor pict(MWAWVec2i(dims[1], dims[0]), dims[2]==4);
590 for (int y=0; y<dims[0]; ++y) {
591 long actPos=input->tell();
592 unsigned char cols[4]= {0,0,0,0};
593 for (int w=0; w<dims[1]; ++w) {
594 for (int c=0; c<dims[2]; ++c) cols[c]=(unsigned char)(input->readULong(1));
595 if (dims[2]==4)
596 pict.set(w, y, MWAWColor(cols[1], cols[2], cols[3], (unsigned char)(255-cols[0])));
597 else
598 pict.set(w, y, MWAWColor(cols[0], cols[1], cols[2]));
599 }
600 input->seek(actPos+width, librevenge::RVNG_SEEK_SET);
601 }
602
603 input->seek(endPos, librevenge::RVNG_SEEK_SET);
604 ascFile.skipZone(pos, endPos-1);
605 #ifdef DEBUG_WITH_FILES
606 MWAWEmbeddedObject obj;
607 if (pict.getBinary(obj) && !obj.m_dataList.empty())
608 libmwaw::Debug::dumpFile(obj.m_dataList[0], "file.png");
609 #endif
610
611 return true;
612 }
613
614 ////////////////////////////////////////////////////////////
615 // decoder
616 ////////////////////////////////////////////////////////////
617
618 //! a basic Unpack decoder
619 struct UnpackDecoder {
620 //! constructor
621 UnpackDecoder(unsigned char const *data, unsigned long len)
622 : m_data(data)
623 , m_len(len)
624
625 , m_pos(0)
626 {
627 }
628
629 bool decode(unsigned long expectedLength, std::vector<unsigned char> &output)
630 {
631 output.clear();
632 output.reserve(expectedLength > 0x8000 ? 0x8000 : expectedLength);
633 while (m_pos+2<=m_len) {
634 unsigned num=unsigned(m_data[m_pos++]);
635 unsigned char val=m_data[m_pos++];
636 if (output.size()+num>expectedLength)
637 return false;
638 for (unsigned i=0; i<num; ++i)
639 output.push_back(val);
640 }
641 return output.size()==expectedLength;
642 }
643 protected:
644
645 unsigned char const *m_data;
646 unsigned long m_len;
647 mutable unsigned long m_pos;
648 };
649
650 //! a basic NIB decoder
651 struct NIBDecoder {
652 //! constructor
653 NIBDecoder(unsigned char const *data, unsigned long len)
654 : m_data(data)
655 , m_len(len)
656
657 , m_pos(0)
658 {
659 }
660
661 bool decode(unsigned long expectedLength, std::vector<unsigned char> &output)
662 {
663 output.clear();
664 output.reserve(expectedLength > 0x8000 ? 0x8000 : expectedLength);
665 unsigned char dict[30];
666 std::set<unsigned char> dictKeys;
667
668 if (m_pos+30>m_len) {
669 MWAW_DEBUG_MSG(("Canvas5Structure::NIBDecoder::can not read a dictionary at pos=%lx\n", m_pos));
670 return false;
671 }
672 for (auto &c : dict) c=m_data[m_pos++];
673 dictKeys.clear();
674 for (auto &c : dict) dictKeys.insert(c);
675
676 int newC=0;
677 bool readC=false;
678 unsigned char c;
679 while (m_pos<=m_len) {
680 bool ok=true;
681 for (int st=0; st<4; ++st) {
682 int val;
683 if (!readC) {
684 if (m_pos>m_len) {
685 ok=false;
686 break;
687 }
688 c=m_data[m_pos++];
689 val=int(c>>4);
690 }
691 else
692 val=int(c&0xf);
693 readC=!readC;
694
695 if (val && st<2) {
696 output.push_back(dict[15*st+val-1]);
697 break;
698 }
699 newC=(newC<<4)|val;
700 if (st==3) {
701 if (dictKeys.find((unsigned char) newC)!=dictKeys.end()) {
702 ok=false;
703 break;
704 }
705 output.push_back((unsigned char) newC);
706 newC=0;
707 }
708 }
709 if (!ok)
710 break;
711 if (m_pos+1>=m_len && output.size()==expectedLength)
712 break;
713 }
714 return output.size()==expectedLength;
715 }
716 protected:
717
718 unsigned char const *m_data;
719 unsigned long m_len;
720 mutable unsigned long m_pos;
721 };
722
723 /** a basic LWZ decoder
724
725 \note this code is freely inspired from https://github.com/MichaelDipperstein/lzw GLP 3
726 */
727 struct LWZDecoder {
728 static int const e_firstCode=(1<<8);
729 static int const e_maxCodeLen=12;
730 static int const e_maxCode=(1<<e_maxCodeLen);
731
732 //! constructor
733 LWZDecoder(unsigned char const *data, unsigned long len)
734 : m_data(data)
735 , m_len(len)
736
737 , m_pos(0)
738 , m_bit(0)
739 , m_dictionary()
740 {
741 initDictionary();
742 }
743
744 bool decode(std::vector<unsigned char> &output);
745
746 protected:
747 void initDictionary()
748 {
749 m_dictionary.resize(2); // 100 and 101
750 m_dictionary.reserve(e_maxCode - e_firstCode); // max table 4000
751 }
752
753 unsigned getBit() const
754 {
755 if (m_pos>=m_len)
756 throw libmwaw::ParseException();
757 unsigned val=(m_data[m_pos]>>(7-m_bit++))&1;
758 if (m_bit==8) {
759 ++m_pos;
760 m_bit=0;
761 }
762 return val;
763 }
764 unsigned getCodeWord(unsigned codeLen) const
765 {
766 unsigned code=0;
767 for (unsigned i=0; i<codeLen;) {
768 if (m_bit==0 && (codeLen-i)>=8 && m_pos<m_len) {
769 code = (code<<8) | unsigned(m_data[m_pos++]);
770 i+=8;
771 continue;
772 }
773 code = (code<<1) | getBit();
774 ++i;
775 }
776 return code;
777 }
778
779 struct LWZEntry {
780 //! constructor
781 explicit LWZEntry(unsigned int prefixCode=0, unsigned char suffix=0)
782 : m_suffix(suffix)
783 , m_prefixCode(prefixCode)
784 {
785 }
786 /** last char in encoded string */
787 unsigned char m_suffix;
788 /** code for remaining chars in string */
789 unsigned int m_prefixCode;
790 };
791
792 unsigned char decodeRec(unsigned int code, std::vector<unsigned char> &output)
793 {
794 unsigned char c;
795 unsigned char firstChar;
796
797 if (code >= e_firstCode) {
798 if (code-e_firstCode >= m_dictionary.size()) {
799 MWAW_DEBUG_MSG(("Canvas5Structure::LWZDecoder::decodeRec: bad id=%x/%x\n", code, unsigned(m_dictionary.size())));
800 throw libmwaw::ParseException();
801 }
802 /* code word is string + c */
803 c = m_dictionary[code - e_firstCode].m_suffix;
804 code = m_dictionary[code - e_firstCode].m_prefixCode;
805
806 /* evaluate new code word for remaining string */
807 firstChar = decodeRec(code, output);
808 }
809 else /* code word is just c */
810 firstChar = c = (unsigned char)code;
811
812 output.push_back(c);
813 return firstChar;
814 }
815 LWZDecoder(LWZDecoder const &)=delete;
816 LWZDecoder &operator=(LWZDecoder const &)=delete;
817 unsigned char const *m_data;
818 unsigned long m_len;
819 mutable unsigned long m_pos, m_bit;
820
821 std::vector<LWZEntry> m_dictionary;
822 };
823
824 bool LWZDecoder::decode(std::vector<unsigned char> &output)
825 try
826 {
827 output.reserve(0x8000);
828
829 unsigned int const currentCodeLen = 12;
830 unsigned lastCode=0;
831 unsigned char c=(unsigned char) 0;
832 bool first=true;
833
834 while (true) {
835 unsigned code=getCodeWord(currentCodeLen);
836 if (code==0x100) {
837 initDictionary();
838 first=true;
839 continue;
840 }
841 if (code==0x101) // end of code
842 break;
843 if (code < e_firstCode+m_dictionary.size())
844 /* we have a known code. decode it */
845 c = decodeRec(code, output);
846 else {
847 /***************************************************************
848 * We got a code that's not in our dictionary. This must be due
849 * to the string + char + string + char + string exception.
850 * Build the decoded string using the last character + the
851 * string from the last code.
852 ***************************************************************/
853 unsigned char tmp = c;
854 c = decodeRec(lastCode, output);
855 output.push_back(tmp);
856 }
857
858 /* if room, add new code to the dictionary */
859 if (!first && m_dictionary.size() < e_maxCode) {
860 if (lastCode>=e_firstCode+m_dictionary.size()) {
861 MWAW_DEBUG_MSG(("Canvas5Structure::LWZDecoder::decode: oops a loop with %x/%x\n", lastCode, unsigned(m_dictionary.size())));
862 break;
863 }
864 m_dictionary.push_back(LWZEntry(lastCode, c));
865 }
866
867 /* save character and code for use in unknown code word case */
868 lastCode = code;
869 first=false;
870 }
871 return true;
872 }
873 catch (...)
874 {
875 return false;
876 }
877
878
879 bool decodeZone5(MWAWInputStreamPtr input, long endPos, int type, unsigned long finalLength,
880 std::shared_ptr<MWAWStringStream> &stream)
881 {
882 if (type<0 || type>8) {
883 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5: unknown type\n"));
884 return false;
885 }
886 std::vector<unsigned long> lengths;
887 lengths.push_back(finalLength);
888 // checkme this code is only tested when type==0, 7, 8
889 int const nExtraLength[]= {
890 0, 0, 0, 0, 2, // _, _, Z, N, N+Z
891 0, 0, 2, 3 // _, P, P+N, P+N+Z
892 };
893 long pos=input->tell();
894 if (pos+4*nExtraLength[type]>endPos) {
895 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5: can not read the extra length\n"));
896 return false;
897 }
898 bool readInverted=input->readInverted();
899 input->setReadInverted(false);
900 for (int n=0; n<nExtraLength[type]; ++n)
901 lengths.push_back(input->readULong(4));
902 if (lengths.size()==1)
903 lengths.push_back((unsigned long)(endPos-pos));
904 input->setReadInverted(readInverted);
905
906 auto l=lengths.back();
907 lengths.pop_back();
908 for (size_t i=lengths.size(); i>0 && l==0xFFFFFFFF; --i) l=lengths[i-1];
909
910 pos=input->tell();
911 unsigned long read;
912 unsigned char const *dt = l<=(unsigned long)(endPos-pos) ? input->read(l, read) : nullptr;
913 if (!dt || read != l) {
914 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5: can not read some data\n"));
915 return false;
916 }
917 std::vector<unsigned char> data(dt, dt+l);
918
919 if (type==2 || type==4 || type==8) { // find with type==8
920 l=lengths.back();
921 lengths.pop_back();
922 for (size_t i=lengths.size(); i>0 && l==0xFFFFFFFF; --i) l=lengths[i-1];
923 if (l!=0xffffffff && l!=data.size()) {
924 Canvas5Structure::LWZDecoder decoder(data.data(), data.size());
925 std::vector<unsigned char> data2;
926 if (!decoder.decode(data2) || data2.size()!=l) {
927 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5[LWZ]: can not decode some data\n"));
928 return false;
929 }
930 std::swap(data, data2);
931 }
932 }
933
934 if (type==3 || type==4 || type==7 || type==8) { // find with type==7,8
935 l=lengths.back();
936 lengths.pop_back();
937 for (size_t i=lengths.size(); i>0 && l==0xFFFFFFFF; --i) l=lengths[i-1];
938 if (l!=0xffffffff && l!=data.size()) {
939 Canvas5Structure::NIBDecoder decoder(data.data(), data.size());
940 std::vector<unsigned char> data2;
941 if (!decoder.decode(l, data2)) {
942 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5[NIB]: can not decode some data\n"));
943 return false;
944 }
945 std::swap(data, data2);
946 }
947 }
948
949 if (type==6 || type==7 || type==8) { // find with type==7,8
950 l=lengths.back();
951 lengths.pop_back();
952 for (size_t i=lengths.size(); i>0 && l==0xFFFFFFFF; --i) l=lengths[i-1];
953 if (l!=0xffffffff && l!=data.size()) {
954 Canvas5Structure::UnpackDecoder decoder(data.data(), data.size());
955 std::vector<unsigned char> data2;
956 if (!decoder.decode(l, data2)) {
957 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5[pack]: can not decode some data\n"));
958 return false;
959 }
960 std::swap(data, data2);
961 }
962 }
963
964 if (data.size()!=finalLength) {
965 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5[pack]: problem decoding data %lx/%lx\n", (unsigned long)data.size(), finalLength));
966 return false;
967 }
968
969 stream->append(data.data(), unsigned(data.size()));
970
971 if (input->tell()!=endPos) {
972 MWAW_DEBUG_MSG(("Canvas5Structure::decodeZone5: find extra data\n"));
973 input->seek(endPos, librevenge::RVNG_SEEK_SET);
974 }
975 return true;
976 }
977
978 }
979 // vim: set filetype=cpp tabstop=2 shiftwidth=2 cindent autoindent smartindent noexpandtab:
980