Tools/IMP.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Tools/MSReader.pm ↑ Summary Tools/LZSS.pm »
1 package EBook::Tools::IMP;
2 2 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use version 0.74; our $VERSION = qv("0.5.0");
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 ## Perl Critic overrides:
7 # RequireBriefOpen seems to be way too brief to be useful
8 ## no critic (RequireBriefOpen)
9 # We're not interpolating constants and not making them lexical makes identifying them easier
10 ## no critic (ProhibitConstantPragma)
11  
12 =head1 NAME
13  
14 EBook::Tools::IMP - Object class for manipulating the SoftBook/GEB/REB/eBookWise C<.IMP> and C<.RES> e-book formats
15  
16 =head1 SYNOPSIS
17  
18 use EBook::Tools::IMP qw(:all)
19 my $imp = EBook::Tools::IMP->new();
20 $imp->load('myfile.imp');
21  
22 =cut
23  
24 require Exporter;
25 2 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 our @EXPORT_OK;
28 @EXPORT_OK = qw (
29 &detect_resource_type
30 &parse_imp_resource_v1
31 &parse_imp_resource_v2
32 );
33 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
34  
35 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 2 ▶use Cwd qw(getcwd realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
37 0 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
38 use EBook::Tools::LZSS qw(:all);
39 use Encode;
40 use File::Basename qw(basename dirname fileparse);
41 use File::Path; # Exports 'mkpath' and 'rmtree'
42 use Image::Size;
43 use List::MoreUtils qw(any none);
44 binmode(STDERR,':encoding(UTF-8)');
45  
46 my $drmsupport = 0;
47 eval
48 {
49 require EBook::Tools::DRM;
50 EBook::Tools::DRM->import();
51 }; # Trailing semicolon is required here
52 unless($@){ $drmsupport = 1; }
53  
54  
55 # Constants for $self->{device},
56 use constant DEVICE_SB200 => 0; # SoftBook 200/250
57 use constant DEVICE_REB1200 => 1; # REB 1200/GEB 2150
58 use constant DEVICE_EBW1150 => 2; # EBW 1150/GEB 1150
59  
60 use constant IMAGETYPES => ('png','jpg','gif','pic');
61 use constant IMAGERESOURCES => ('GIF ','JPEG','PICT','PIC2','PNG ');
62 my %IMAGE_RESOURCE_MAP = (
63 'GIF ' => 'gif',
64 'JPEG' => 'jpg',
65 'PICT' => 'pic',
66 'PIC2' => 'png',
67 'PNG ' => 'png',
68 );
69  
70  
71 ####################################################
72 ########## CONSTRUCTOR AND INITIALIZATION ##########
73 ####################################################
74  
75 my %rwfields = (
76 'version' => 'integer',
77 'filename' => 'string',
78 'filecount' => 'integer',
79 'resdirlength' => 'integer',
80 'resdiroffset' => 'integer',
81 'compression' => 'integer',
82 'encryption' => 'integer',
83 'device' => 'integer',
84 'zoomstates' => 'integer',
85 'identifier' => 'string',
86 'category' => 'string',
87 'subcategory' => 'string',
88 'title' => 'string',
89 'lastname' => 'string',
90 'middlename' => 'string',
91 'firstname' => 'string',
92 'etiserverdata' => 'hash', # Extra data after book properties
93 'resdirname' => 'string',
94 'RSRC.INF' => 'string',
95 'resfiles' => 'array', # Array of hashrefs
96 'toc' => 'array', # Table of Contents, array of hashes
97 'resources' => 'hash', # Hash of hashrefs keyed on 'type'
98 'lzsslengthbits' => 'integer',
99 'lzssoffsetbits' => 'integer',
100 'text' => 'string', # Uncompressed text
101 'imrn' => 'hash', # Hash of hashes of ImRn resource data
102 'gif' => 'hash', # Hash of hashes of GIF image data
103 'jpg' => 'hash', # Hash of hashes of JPEG image data
104 'pic' => 'hash', # Hash of hashes of PICT image data
105 'png' => 'hash', # Hash of hashes of PNG image data
106 'offsetelements' => 'hash', # Hash of text offsets to HTML elements
107 );
108  
109 my %rofields = (
110 'unknown0x0a' => 'string',
111 'unknown0x18' => 'integer',
112 'unknown0x1c' => 'integer',
113 'unknown0x28' => 'integer',
114 'unknown0x2a' => 'integer',
115 'unknown0x2c' => 'integer',
116 );
117 my %privatefields = (
118 );
119  
120 # A simple 'use fields' will not work here: use takes place inside
121 # BEGIN {}, so the @...fields variables won't exist.
122 require fields;
123 fields->import(
124 keys(%rwfields),keys(%rofields),keys(%privatefields)
125 );
126  
127  
128 =head1 CONSTRUCTOR AND INITIALIZATION
129  
130 =head2 C<new($filename)>
131  
132 Instantiates a new EBook::Tools::IMP object. If C<$filename> is
133 specified, it will also immediately initialize itself via the C<load>
134 method.
135  
136 =cut
137  
138 sub new ## no critic (Always unpack @_ first)
139 {
140 my $self = shift;
141 my $class = ref($self) || $self;
142 my ($filename) = @_;
143 my $subname = (caller(0))[3];
144 debug(2,"DEBUG[",$subname,"]");
145  
146 $self = fields::new($class);
147 if($filename)
148 {
149 $self->{filename} = $filename;
150 $self->load();
151 }
152 return $self;
153 }
154  
155  
156 =head2 C<load($filename)>
157  
158 Loads a .imp file, parsing it into the various object attributes.
159 Returns 1 on success, or undef on failure.
160  
161 =cut
162  
163 sub load :method
164 {
165 my ($self,$filename) = @_;
166 my $subname = (caller(0))[3];
167 croak($subname . "() called as a procedure!\n") unless(ref $self);
168 debug(2,"DEBUG[",$subname,"]");
169  
170 if(not $self->{filename} and not $filename)
171 {
172 carp($subname,"(): no filename specified!\n");
173 return;
174 }
175  
176 $self->{filename} = $filename if($filename);
177 $filename = $self->{filename} if(!$filename);
178  
179 my $fh_imp;
180 my $headerdata;
181 my $bookpropdata;
182 my $retval;
183 my $toc_size;
184 my $tocdata;
185 my $entrydata;
186 my $resource; # Hashref
187  
188  
189 if(! -f $filename)
190 {
191 carp($subname,"(): '",$filename,"' not found!\n");
192 return;
193 }
194  
195 open($fh_imp,'<:raw',$filename)
196 or croak($subname,"(): unable to open '",$filename,
197 "' for reading!\n");
198 sysread($fh_imp,$headerdata,48);
199 $retval = $self->parse_imp_header($headerdata);
200 if(!$retval)
201 {
202 carp($subname,"(): '",$filename,"' is not an IMP file!\n");
203 return;
204 }
205  
206 if(!$self->{resdiroffset})
207 {
208 carp($subname,"(): '",$filename,"' has no res dir offset!\n");
209 return;
210 }
211 my $bookproplength = $self->{resdiroffset} - 24;
212 sysread($fh_imp,$bookpropdata,$bookproplength);
213 $retval = $self->parse_imp_book_properties($bookpropdata);
214  
215 if(!$self->{resdirlength})
216 {
217 carp($subname,"(): '",$filename,"' has no directory name!\n");
218 return;
219 }
220  
221 sysread($fh_imp,$self->{resdirname},$self->{resdirlength});
222  
223 debug(1,"DEBUG: resource directory = '",$self->{resdirname},"'");
224  
225 if($self->{version} == 1)
226 {
227 $toc_size = 10 * $self->{filecount};
228 sysread($fh_imp,$tocdata,$toc_size)
229 or croak($subname,"(): unable to read TOC data!\n");
230 $self->parse_imp_toc_v1($tocdata);
231  
232 $self->{resources} = ();
233 foreach my $entry (@{$self->{toc}})
234 {
235 sysread($fh_imp,$entrydata,$entry->{size}+10);
236 $resource = parse_imp_resource_v1($entrydata);
237 if($resource->{type} ne $entry->{type})
238 {
239 carp($subname,"():\n",
240 " '",$entry->{type},"' TOC entry pointed to '",
241 $resource->{type},"' resource!\n");
242 }
243 $self->{resources}->{$resource->{type}} = $resource;
244 }
245 }
246 elsif($self->{version} == 2)
247 {
248 $toc_size = 20 * $self->{filecount};
249 sysread($fh_imp,$tocdata,$toc_size)
250 or croak($subname,"(): unable to read TOC data!\n");
251 $self->parse_imp_toc_v2($tocdata);
252  
253 $self->{resources} = ();
254 foreach my $entry (@{$self->{toc}})
255 {
256 sysread($fh_imp,$entrydata,$entry->{size}+20);
257 $resource = parse_imp_resource_v2($entrydata);
258 $self->{resources}->{$resource->{type}} = $resource;
259 }
260 }
261 else
262 {
263 carp($subname,"(): IMP version ",$self->{version}," not supported!\n");
264 return;
265 }
266  
267 $self->parse_resource_images();
268 $self->parse_resource_imrn();
269 $self->parse_text();
270  
271 close($fh_imp)
272 or croak($subname,"(): failed to close '",$filename,"'!\n");
273  
274 debug(3,$self->{text});
275 return 1;
276 }
277  
278  
279 =head2 C<load_resdir($dirname)>
280  
281 Loads a C<.RES> resource directory, parsing it into the object
282 attributes. Returns 1 on success, or undef on failure.
283  
284 =cut
285  
286 sub load_resdir
287 {
288 my ($self,$dirname) = @_;
289 my $subname = (caller(0))[3];
290 croak($subname . "() called as a procedure!\n") unless(ref $self);
291 debug(2,"DEBUG[",$subname,"]");
292  
293 if(!$dirname)
294 {
295 carp($subname,"(): no resource directory specified!\n");
296 return;
297 }
298  
299 if(! -d $dirname)
300 {
301 carp($subname,"(): resource directory '",$dirname,"' not found!\n");
302 return;
303 }
304  
305 if(! -f $dirname . '/DATA.FRK')
306 {
307 carp($subname,"():\n",
308 " resource directory '",$dirname,"' has no text resource!\n");
309 return;
310 }
311 if(! -f $dirname . '/RSRC.INF')
312 {
313 carp($subname,"()\n",
314 " resource directory '",$dirname,"' has no RSRC.INF!\n");
315 return;
316 }
317  
318 my $fh_resource;
319 my $rsrcinf;
320 my @list;
321  
322 open($fh_resource,'<:raw',$dirname . '/RSRC.INF')
323 or croak($subname,"():\n",
324 " unable to open '$dirname/RSRC.INF' for reading!\n");
325 sysread($fh_resource,$rsrcinf,-s "$dirname/RSRC.INF");
326 close($fh_resource)
327 or croak($subname,"():\n",
328 " unable to close '$dirname/RSRC.INF'!\n");
329  
330 if(length($rsrcinf) < 48)
331 {
332 carp($subname,"():\n",
333 " RSRC.INF is too short (only ",length($rsrcinf)," bytes)!\n");
334 return;
335 }
336  
337 if(substr($rsrcinf,2,8) ne 'BOOKDOUG')
338 {
339 carp($subname,"():\n",
340 " RSRC.INF does not contain a valid header!\n");
341 return;
342 }
343  
344 $self->{resdirname} = basename($dirname);
345 $self->{resdirlength} = length($self->{resdirname});
346 debug(2,"DEBUG: IMP resdir name = ",$self->{resdirname});
347  
348 # We have no idea what to put here, so fill it with nulls
349 $self->{unknown0x0a} = "\x00\x00\x00\x00\x00\x00\x00\x00";
350  
351 # No matter what the RSRC.INF says, we're going to use a v2 format
352 $self->{version} = 2;
353 @list = unpack('nNNNNnCCN',substr($rsrcinf,10,26));
354 $self->{resdiroffset} = $list[0];
355 $self->{unknown0x18} = $list[1];
356 $self->{unknown0x1c} = $list[2];
357 $self->{compression} = $list[3];
358 $self->{encryption} = $list[4];
359 $self->{unknown0x28} = $list[5];
360 $self->{unknown0x2a} = $list[6];
361 $self->{device} = $list[7] >> 4;
362 $self->{zoomstates} = $list[7] & 0x0f;
363 $self->{unknown0x2c} = $list[8];
364  
365 debug(2,"DEBUG: IMP resdir offset = ",$self->{resdiroffset});
366 debug(2,"DEBUG: Unknown 0x18 = ",$self->{unknown0x18});
367 debug(2,"DEBUG: Unknown 0x1c = ",$self->{unknown0x1c});
368 debug(2,"DEBUG: IMP compression = ",$self->{compression});
369 debug(2,"DEBUG: IMP encryption = ",$self->{encryption});
370 debug(2,"DEBUG: Unknown 0x28 = ",$self->{unknown0x28});
371 debug(2,"DEBUG: Unknown 0x2A = ",$self->{unknown0x2a});
372 debug(2,"DEBUG: IMP device = ",$self->{device});
373 debug(2,"DEBUG: IMP zoom state = ",$self->{zoomstates});
374 debug(2,"DEBUG: Unknown 0x2c = ",$self->{unknown0x2c});
375  
376 @list = unpack('Z*Z*Z*Z*Z*Z*Z*',substr($rsrcinf,36));
377 $self->{identifier} = $list[0];
378 $self->{category} = $list[1];
379 $self->{subcategory} = $list[2];
380 $self->{title} = $list[3];
381 $self->{lastname} = $list[4];
382 $self->{middlename} = $list[5];
383 $self->{firstname} = $list[6];
384  
385 my $proplength = $self->bookproplength;
386 if(length($rsrcinf) > $proplength + 36)
387 {
388 debug(1,"Book properties data has extra ETI server data appended");
389 $self->parse_eti_server_data(substr($rsrcinf,$proplength + 36));
390 }
391  
392 my $cwd = getcwd();
393  
394 if(! chdir($dirname))
395 {
396 carp($subname,"(): unable to enter directory '",$dirname,"'!\n");
397 return;
398 }
399  
400 my @filelist = glob '*';
401 $self->{resources} = {};
402 $self->{toc} = ();
403 foreach my $file (@filelist)
404 {
405 my $resdata;
406 my %resource;
407 my %tocentry;
408  
409 next if($file eq 'RSRC.INF');
410 unless($file =~ /^ ([A-Z]{4} | DATA\.FRK) $/x)
411 {
412 debug(1,"DEBUG: invalid resource filename '",$file,
413 "' -- skipping");
414 next;
415 }
416 if(-z $file)
417 {
418 debug(1,"DEBUG: resource file '",$file,
419 "' has zero size -- skipping");
420 next;
421 }
422 open($fh_resource,'<:raw',$file)
423 or croak($subname,"():\n",
424 " unable to open '",$file,"' for reading!\n");
425 sysread($fh_resource,$resdata,-s $file);
426 close($fh_resource)
427 or croak($subname,"(): unable to close '",$file,"'!\n");
428 if($file eq 'DATA.FRK')
429 {
430 $resource{name} = ' ';
431 $resource{type} = ' ';
432 }
433 else
434 {
435 $resource{name} = $file;
436 $resource{type} = detect_resource_type(\$resdata);
437 }
438 if(! $resource{type})
439 {
440 debug(1,"DEBUG: unable to determine resource type for file '",
441 $file,"' -- skipping");
442 next;
443 }
444 $resource{unknown1} = 0;
445 $resource{unknown2} = 0;
446 $resource{size} = length($resdata);
447 %tocentry = %resource;
448 push(@{$self->{toc}},\%tocentry);
449  
450 $resource{data} = $resdata;
451 $self->{resources}->{$resource{type}} = \%resource;
452 debug(2,"DEBUG: found resource '",$resource{name},
453 "', type '",$resource{type},"' [",$resource{size}," bytes]");
454 }
455 chdir($cwd);
456  
457 $self->parse_resource_images();
458 $self->parse_resource_imrn();
459 $self->parse_text();
460  
461 return 1;
462 }
463  
464  
465 ######################################
466 ########## ACCESSOR METHODS ##########
467 ######################################
468  
469  
470 =head2 C<author()>
471  
472 Returns the full name of the author of the book.
473  
474 Author information can either be found entirely in the
475 C<< $self->{firstname} >> attribute or split up into
476 C<< $self->{firstname} >>, C<< $self->{middlename} >>, and
477 C<< $self->{lastname} >>. If the last name is found separately,
478 the full name is returned in the format "Last, First Middle".
479 Otherwise, the full name is returned in the format "First Middle".
480  
481 =cut
482  
483 sub author :method
484 {
485 my $self = shift;
486 my $subname = (caller(0))[3];
487 croak($subname . "() called as a procedure!\n") unless(ref $self);
488 debug(2,"DEBUG[",$subname,"]");
489  
490 my $author;
491 if($self->{lastname})
492 {
493 $author = $self->{lastname};
494 if($self->{firstname})
495 {
496 $author .= ", " . $self->{firstname};
497 $author .= " " . $self->{middlename} if($self->{middlename});
498 }
499 }
500 else
501 {
502 $author = $self->{firstname};
503 $author .= " " . $self->{middlename} if($self->{middlename});
504 }
505  
506 return $author;
507 }
508  
509  
510 =head2 C<bookproplength()>
511  
512 Returns the total length in bytes of the book properties data,
513 including the trailing null used to pack the C-style strings, but
514 excluding any ETI server data appended to the end of the standard book
515 properties.
516  
517 =cut
518  
519 sub bookproplength :method
520 {
521 my $self = shift;
522 my $subname = (caller(0))[3];
523 croak($subname . "() called as a procedure!\n") unless(ref $self);
524 debug(2,"DEBUG[",$subname,"]");
525  
526 my $length = 0;
527 $length += length($self->{identifier}) + 1;
528 $length += length($self->{category}) + 1;
529 $length += length($self->{subcategory}) + 1;
530 $length += length($self->{title}) + 1;
531 $length += length($self->{lastname}) + 1;
532 $length += length($self->{middlename}) + 1;
533 $length += length($self->{firstname}) + 1;
534  
535 return $length;
536 }
537  
538  
539 =head2 C<filecount()>
540  
541 Returns the number of resource files as stored in
542 C<< $self->{filecount} >>. Note that this does NOT recompute that value
543 from the actual number of resources in C<< $self->{resources} >>. To do
544 that, use L</create_toc_from_resources()>.
545  
546 =cut
547  
548 sub filecount :method
549 {
550 my $self = shift;
551 my $subname = (caller(0))[3];
552 croak($subname . "() called as a procedure!\n") unless(ref $self);
553 debug(2,"DEBUG[",$subname,"]");
554 return $self->{filecount};
555 }
556  
557  
558 =head2 C<find_image_type($id,@excluded)>
559  
560 Goes through all stored images searching for one with the specified id
561 value, returning the first image type found or undef if there were no
562 matches or if no image id was specified. If the optional argument
563 C<@excluded> is specified, any types in the list will be skipped
564 during the search.
565  
566 Expected types are 'png', 'jpg', 'gif', and 'pic', searched for in
567 that order.
568  
569 This can be used to attempt to locate an alternate image for an
570 undisplayable PICT image.
571  
572 =cut
573  
574 sub find_image_type :method
575 {
576 my ($self,$id,@excluded) = @_;
577 my $subname = (caller(0))[3];
578 croak($subname . "() called as a procedure!\n") unless(ref $self);
579 debug(2,"DEBUG[",$subname,"]");
580  
581 return unless($id);
582  
583 foreach my $type (IMAGETYPES)
584 {
585 next if(any {$type eq $_} @excluded);
586 return $type if($self->{$type}->{$id});
587 }
588 return;
589 }
590  
591  
592 =head2 C<find_resource_by_name($name)>
593  
594 Takes as a single argument a resource name and if a resource with that
595 name exists in C<< $self->{resources} >> returns the resource type
596 used as the hash key.
597  
598 Returns undef if no match was found or a name was not specified.
599  
600 =cut
601  
602 sub find_resource_by_name :method
603 {
604 my ($self,$name) = @_;
605 my $subname = (caller(0))[3];
606 croak($subname . "() called as a procedure!\n") unless(ref $self);
607 debug(2,"DEBUG[",$subname,"]");
608  
609 return unless($name);
610 return unless($self->{resources});
611  
612 foreach my $type (keys %{$self->{resources}})
613 {
614 return $type if($self->{resources}->{$type}->{name} eq $name);
615 }
616 return;
617 }
618  
619  
620 =head2 C<image($type,$id)>
621  
622 Returns the image data stored in the resource of the specified type
623 (specifically, stored in C<< $self->{$type}->{$id}->{data} >> as
624 parsed from the JPEG resource) corresponding to the 16-bit identifier
625 provided as C<$id>.
626  
627 Valid values for C<$type> are 'gif','jpg', and 'png'.
628  
629 Carps a warning and returns undef if C<$type> is not provided or is
630 not valid, or if C<$id> is not provided.
631  
632 =cut
633  
634 sub image :method
635 {
636 my ($self,$type,$id) = @_;
637 my $subname = (caller(0))[3];
638 croak($subname . "() called as a procedure!\n") unless(ref $self);
639 debug(2,"DEBUG[",$subname,"]");
640  
641 if(!$type)
642 {
643 carp($subname,"(): no image type specified!\n");
644 return;
645 }
646 if(none { $type eq $_ } IMAGETYPES)
647 {
648 carp($subname,"(): invalid image type '",$type,"'!\n");
649 return;
650 }
651 if(!$id)
652 {
653 carp($subname,"(): ID not specified!\n");
654 return;
655 }
656 return $self->{$type}->{$id}->{data};
657 }
658  
659  
660 =head2 C<image_hashref($type,$id)>
661  
662 Returns the raw object hashref used to store parsed image data for the
663 specified type, as stored in C<< $self->{$type} >>. Valid types are
664 'gif', 'jpg', and 'png'.
665  
666 Carps a warning and returns undef if C<$type> is not provided or is
667 not valid.
668  
669 If C<$id> is not specified, the keys of the returned hash are the
670 image IDs for the specified image type, and the values are hashrefs
671 pointing to hashes containing the following keys:
672  
673 =over
674  
675 =item * C<unknown>
676  
677 A 16-bit integer only available on EBW 1150 resources. Use with
678 caution. This key may be renamed if more information is found.
679  
680 =item * C<length>
681  
682 The length of the actual image data
683  
684 =item * C<offset>
685  
686 The byte offset inside of the raw resource data in which the JPEG
687 image data can be found.
688  
689 =item * C<const0>
690  
691 An unknown value, but it appears to always be zero. Use with caution.
692 This key may be renamed if more information is found.
693  
694 =back
695  
696 If the optional argument C<$id> is specified, only the hash for that
697 specific ID is returned, rather than the entire hash of hashrefs.
698  
699 =cut
700  
701 sub image_hashref :method
702 {
703 my ($self,$type,$id) = @_;
704 my $subname = (caller(0))[3];
705 croak($subname . "() called as a procedure!\n") unless(ref $self);
706 debug(2,"DEBUG[",$subname,"]");
707  
708 if(!$type)
709 {
710 carp($subname,"(): no image type specified!\n");
711 return;
712 }
713 if(none { $type eq $_ } IMAGETYPES)
714 {
715 carp($subname,"(): invalid image type '",$type,"'!\n");
716 return;
717 }
718  
719 if($id)
720 {
721 return $self->{$type}->{$id};
722 }
723 return $self->{$type};
724 }
725  
726  
727 =head2 C<image_ids($type)>
728  
729 Returns a list of the 16-bit integer IDs of the the specified type of
730 image data stored in the associated resource (specifically, stored in
731 C<< $self->{$type} >> as parsed from the JPEG resource).
732  
733 Valid types are 'gif', 'jpg', and 'png'. The method will carp a
734 warning and return undef if another type is specified, or no type is
735 specified.
736  
737 =cut
738  
739 sub image_ids :method
740 {
741 my ($self,$type) = @_;
742 my $subname = (caller(0))[3];
743 croak($subname . "() called as a procedure!\n") unless(ref $self);
744 debug(2,"DEBUG[",$subname,"]");
745  
746 if(!$type)
747 {
748 carp($subname,"(): no image type specified!\n");
749 return;
750 }
751  
752 if(none { $type eq $_ } IMAGETYPES)
753 {
754 carp($subname,"(): invalid image type '",$type,"'!\n");
755 return;
756 }
757  
758 return keys %{$self->{$type}};
759 }
760  
761  
762 =head2 C<is_1150()>
763  
764 Returns 1 if C<< $self->{device} == 2 >>, returns 0 if it is some
765 other value, and undef it is undefined. This has value because
766 resources packed for a EBW 1150 or GEB 1150 are in a different format
767 than resources packed for other IMP readers.
768  
769 =cut
770  
771 sub is_1150
772 {
773 my $self = shift;
774 my $subname = (caller(0))[3];
775 croak($subname . "() called as a procedure!\n") unless(ref $self);
776 debug(2,"DEBUG[",$subname,"]");
777  
778 return if(!defined $self->{device});
779 return 1 if($self->{device} == 2);
780 return 0;
781 }
782  
783  
784 =head2 C<offsetelement($offset)>
785  
786 Returns the text of the element corresponding to the given text offset
787 as stored in C<< $self->{offsetelements} >>, or undef if no such
788 element exists.
789  
790 =cut
791  
792 sub offsetelement :method
793 {
794 my ($self,$offset) = @_;
795 my $subname = (caller(0))[3];
796 croak($subname . "() called as a procedure!\n") unless(ref $self);
797 debug(2,"DEBUG[",$subname,"]");
798  
799 return unless($offset);
800 return unless($self->{offsetelements});
801 return $self->{offsetelements}->{$offset};
802 }
803  
804  
805 =head2 C<pack_imp_book_properties()>
806  
807 Packs object attributes into the 7 null-terminated strings that
808 constitute the book properties section of the header. Returns that
809 string.
810  
811 Note that this does NOT pack the ETI server data appended to this
812 section in encrypted books downloaded directly from the ETI servers,
813 even if that data was found when the .imp file was loaded. This is
814 because the extra data can confuse the GEBLibrarian application, and
815 is not needed to read the book. The L</bookproplength()> and
816 L</pack_imp_header()> methods also assume that this data will not be
817 present.
818  
819 =cut
820  
821 sub pack_imp_book_properties :method
822 {
823 my $self = shift;
824 my $subname = (caller(0))[3];
825 croak($subname . "() called as a procedure!\n") unless(ref $self);
826 debug(2,"DEBUG[",$subname,"]");
827  
828 my $bookpropdata = pack("Z*Z*Z*Z*Z*Z*Z*",
829 $self->{identifier},
830 $self->{category},
831 $self->{subcategory},
832 $self->{title},
833 $self->{lastname},
834 $self->{middlename},
835 $self->{firstname});
836  
837 return $bookpropdata;
838 }
839  
840  
841 =head2 C<pack_imp_header()>
842  
843 Packs object attributes into the 48-byte string representing the IMP
844 header. Returns that string on success, carps a warning and returns
845 undef if a required attribute did not contain valid data.
846  
847 Note that in the case of an encrypted e-book with ETI server data in
848 it, this header will not be identical to the original -- the
849 resdiroffset value is recalculated for the position with the ETI
850 server data stripped. See L</bookproplength()> and
851 L</pack_imp_book_properties()>.
852  
853 =cut
854  
855 sub pack_imp_header :method
856 {
857 my $self = shift;
858 my $subname = (caller(0))[3];
859 croak($subname . "() called as a procedure!\n") unless(ref $self);
860 debug(2,"DEBUG[",$subname,"]");
861  
862 my $header;
863 my $filecount = scalar(keys %{$self->{resources}});
864 my $resdir = $self->{resdirname};
865  
866 if(!$filecount)
867 {
868 carp($subname,"():\n",
869 " No resources found (has a file been loaded?)\n");
870 return;
871 }
872  
873 if(!$resdir)
874 {
875 carp($subname,"():\n",
876 " No resource directory name specified!\n");
877 return;
878 }
879  
880 if(!$self->{version})
881 {
882 carp($subname,"():\n",
883 " No version specified (has a file been loaded?)\n");
884 return;
885 }
886 if($self->{version} > 2)
887 {
888 carp($subname,"():\n",
889 " invalid version ",$self->{version},"\n");
890 return;
891 }
892  
893 $header = pack('n',$self->{version});
894 $header .= 'BOOKDOUG';
895 if(not $self->{unknown0x0a}
896 or length($self->{unknown0x0a}) != 8)
897 {
898 carp($subname,"():\n",
899 " unknown data at 0x0a has incorrect length",
900 " -- substituting nulls\n");
901 $self->{unknown0x0a} = "\x00\x00\x00\x00\x00\x00\x00\x00";
902 }
903 $header .= $self->{unknown0x0a};
904 $header .= pack('nn',$filecount,length($resdir));
905 $header .= pack('n',$self->bookproplength + 24);
906 $header .= pack('NN',$self->{unknown0x18},$self->{unknown0x1c});
907 $header .= pack('NN',$self->{compression},$self->{encryption});
908 $header .= pack('nC',$self->{unknown0x28},$self->{unknown0x2a});
909 $header .= pack('C',$self->{device} * 16 + $self->{zoomstates});
910 $header .= pack('N',$self->{unknown0x2c});
911  
912 if(length($header) != 48)
913 {
914 croak($subname,"():\n",
915 " total header length not 48 bytes (found ",
916 length($header),")\n");
917 }
918 return $header;
919 }
920  
921  
922 =head2 C<pack_imp_resource(%args)>
923  
924 Packs the specified resource stored in C<< $self->{resources} >> into
925 a a data string suitable for writing into a .imp file, with a header
926 format determined by C<< $self->{version} >>.
927  
928 Returns a reference to that string if the resource was found, or undef
929 it was not.
930  
931 =head3 Arguments
932  
933 =over
934  
935 =item * C<name>
936  
937 Select the resource by resource name.
938  
939 If both this and C<type> are specified, the type is checked first and
940 the name is only used if the type lookup fails.
941  
942 =item * C<type>
943  
944 Select the resource by resource type. This is faster than selecting
945 by name (since resources are stored in a hash keyed by type) and is
946 recommended for most use.
947  
948 If both this and C<name> are specified, the type is checked first and
949 the name is only used if the type lookup fails.
950  
951 =back
952  
953 =cut
954  
955 sub pack_imp_resource :method
956 {
957 my ($self,%args) = @_;
958 my $subname = (caller(0))[3];
959 croak($subname . "() called as a procedure!\n") unless(ref $self);
960 debug(2,"DEBUG[",$subname,"]");
961  
962 my %valid_args = (
963 'name' => 1,
964 'type' => 1,
965 );
966 foreach my $arg (keys %args)
967 {
968 croak($subname,"(): invalid argument '",$arg,"'")
969 if(!$valid_args{$arg});
970 }
971 if(not $args{name} and not $args{type})
972 {
973 carp($subname,"():\n",
974 " at least one of name or type must be specified!\n");
975 return;
976 }
977  
978 my $type = $args{type};
979 my $resource;
980 my $resdata;
981  
982 if(not ($type and $self->{resources}->{$type}) and $args{name})
983 {
984 $type = $self->find_resource_by_name($args{name});
985 if(not $type or not $self->{resources}->{$type})
986 {
987 carp($subname,"():\n",
988 " no resource with name '",$args{name},"' found!\n");
989 return;
990 }
991 }
992 if(!$self->{resources}->{$type})
993 {
994 carp($subname,"()\n",
995 " no resource with type '",$args{type},"' found!\n");
996 return;
997 }
998  
999 $resource = $self->{resources}->{$type};
1000 if($self->{version} == 1)
1001 {
1002 $resdata = pack('a[4]nN',
1003 $resource->{name},
1004 $resource->{unknown1},
1005 $resource->{size});
1006 $resdata .= $resource->{data};
1007 }
1008 elsif($self->{version} == 2)
1009 {
1010 $resdata = pack('a[4]NNa[4]N',
1011 $resource->{name},
1012 $resource->{unknown1},
1013 $resource->{size},
1014 $resource->{type},
1015 $resource->{unknown2});
1016 $resdata .= $resource->{data};
1017 }
1018 else
1019 {
1020 carp($subname,"(): invalid version ",$self->{version},"!\n");
1021 return;
1022 }
1023  
1024 if(!$resdata)
1025 {
1026 carp($subname,"(): no resource data packed!\n");
1027 return;
1028 }
1029  
1030 return \$resdata;
1031 }
1032  
1033  
1034 =head2 C<pack_imp_rsrc_inf()>
1035  
1036 Packs object attributes into the data string that would be the content
1037 of the RSRC.INF file. Returns that string.
1038  
1039 =cut
1040  
1041 sub pack_imp_rsrc_inf :method
1042 {
1043 my $self = shift;
1044 my $subname = (caller(0))[3];
1045 croak($subname . "() called as a procedure!\n") unless(ref $self);
1046 debug(2,"DEBUG[",$subname,"]");
1047  
1048 my $rsrc;
1049  
1050 # Data from header
1051 $rsrc = pack('na[8]n',1,'BOOKDOUG',$self->{resdiroffset});
1052 $rsrc .= pack('NNNNnCCN',
1053 $self->{unknown0x18},$self->{unknown0x1c},
1054 $self->{compression},$self->{encryption},
1055 $self->{unknown0x28},$self->{unknown0x2a},
1056 ($self->{device} * 16) + $self->{zoomstates},
1057 $self->{unknown0x2c});
1058  
1059 # Data from book properties
1060 $rsrc .= pack('Z*',$self->{identifier});
1061 $rsrc .= pack('Z*Z*Z*',
1062 $self->{category},$self->{subcategory},$self->{title});
1063 $rsrc .= pack('Z*Z*Z*',
1064 $self->{lastname},$self->{middlename},$self->{firstname});
1065  
1066 if($self->{etiserverdata})
1067 {
1068 my $length = length($rsrc);
1069 my $padsize = length($self->{etiserverdata}->{pad});
1070  
1071 # Pad must result in the following record being 4-byte aligned
1072 if( ($length + $padsize) % 4 )
1073 {
1074 carp($subname,"():\n",
1075 " ETI server data has invalid pad, regenerating it...\n");
1076 undef($self->{etiserverdata}->{pad});
1077 $padsize = $length % 4;
1078 if($padsize)
1079 {
1080 $padsize = 4 - $padsize;
1081 $self->{etiserverdata}->{pad} = pack("a[$padsize]","\0");
1082 }
1083 }
1084  
1085 $rsrc .= $self->{etiserverdata}->{pad};
1086 $rsrc .= pack('NNZ*Z*',
1087 $self->{etiserverdata}->{unknown1},
1088 $self->{etiserverdata}->{issuenumber},
1089 $self->{etiserverdata}->{contentfeed},
1090 $self->{etiserverdata}->{source});
1091 if($self->{etiserverdata}->{unknown2})
1092 {
1093 $rsrc .= pack('N',$self->{etiserverdata}->{unknown2});
1094 }
1095 } # if($self->{etiserverdata}
1096  
1097 return $rsrc;
1098 }
1099  
1100  
1101 =head2 C<pack_imp_toc()>
1102  
1103 Packs the C<< $self->{toc} >> object attribute into a data string
1104 suitable for writing into a .imp file. The format is determined by
1105 C<< $self->{version} >>.
1106  
1107 Returns that string, or undef if valid version or TOC data is not
1108 found.
1109  
1110 =cut
1111  
1112 sub pack_imp_toc :method
1113 {
1114 my $self = shift;
1115 my $subname = (caller(0))[3];
1116 croak($subname . "() called as a procedure!\n") unless(ref $self);
1117 debug(2,"DEBUG[",$subname,"]");
1118  
1119 my $tocdata;
1120  
1121 if(!$self->{version})
1122 {
1123 carp($subname,"():\n",
1124 " no version information found (did you load a file first?)\n");
1125 return;
1126 }
1127 if($self->{version} > 2)
1128 {
1129 carp($subname,"():\n",
1130 " invalid version ",$self->{version},"!\n");
1131 return;
1132 }
1133  
1134 if(!$self->{toc})
1135 {
1136 carp($subname,"(): no TOC data found!\n");
1137 return;
1138 }
1139  
1140 foreach my $entry (@{$self->{toc}})
1141 {
1142 if($self->{version} == 1)
1143 {
1144 $tocdata .= pack('a[4]nN',
1145 $entry->{name},
1146 $entry->{unknown1},
1147 $entry->{size});
1148 }
1149 elsif($self->{version} == 2)
1150 {
1151 $tocdata .= pack('a[4]NNa[4]N',
1152 $entry->{name},
1153 $entry->{unknown1},
1154 $entry->{size},
1155 $entry->{type},
1156 $entry->{unknown2});
1157 }
1158 }
1159  
1160 if(!length($tocdata))
1161 {
1162 carp($subname,"(): no valid TOC data produced!\n");
1163 return;
1164 }
1165  
1166 return $tocdata;
1167 }
1168  
1169  
1170 =head2 C<resdirbase()>
1171  
1172 In scalar context, this returns the basename of C<< $self->{resdirname} >>.
1173 In list context, it actually returns the basename, directory, and
1174 extension as per C<fileparse> from L<File::Basename>.
1175  
1176 =cut
1177  
1178 sub resdirbase :method
1179 {
1180 my $self = shift;
1181 return fileparse($self->{resdirname},'\.\w+$');
1182 }
1183  
1184  
1185 =head2 C<resdirlength()>
1186  
1187 Returns the length of the .RES directory name as stored in
1188 C<< $self->{resdirlength} >>. Note that this does NOT recompute the
1189 length from the actual name stored in C<< $self->{resdirname} >> --
1190 for that, use L</set_resdirlength()>.
1191  
1192 =cut
1193  
1194 sub resdirlength :method
1195 {
1196 my $self = shift;
1197 my $subname = (caller(0))[3];
1198 croak($subname . "() called as a procedure!\n") unless(ref $self);
1199 debug(2,"DEBUG[",$subname,"]");
1200 return $self->{resdirlength};
1201 }
1202  
1203  
1204 =head2 C<resdirname()>
1205  
1206 Returns the .RES directory name stored in C<< $self->{resdirname} >>.
1207  
1208 =cut
1209  
1210 sub resdirname :method
1211 {
1212 my $self = shift;
1213 my $subname = (caller(0))[3];
1214 croak($subname . "() called as a procedure!\n") unless(ref $self);
1215 debug(2,"DEBUG[",$subname,"]");
1216 return $self->{resdirname};
1217 }
1218  
1219  
1220 =head2 C<resource($type)>
1221  
1222 Returns a hashref containing the resource data for the specified
1223 resource type, as stored in C<< $self->{resources}->{$type} >>.
1224  
1225 Returns undef if C<$type> is not specified, or if the specified type
1226 is not found.
1227  
1228 =cut
1229  
1230 sub resource :method
1231 {
1232 my ($self,$type) = @_;
1233 my $subname = (caller(0))[3];
1234 croak($subname . "() called as a procedure!\n") unless(ref $self);
1235 debug(2,"DEBUG[",$subname,"]");
1236 return unless($type);
1237 return $self->{resources}->{$type};
1238 }
1239  
1240  
1241 =head2 C<resources()>
1242  
1243 Returns a hashref of hashrefs containing all of the resource data
1244 keyed by type, as stored in C<< $self->{resources} >>.
1245  
1246 =cut
1247  
1248 sub resources :method
1249 {
1250 my $self = shift;
1251 my $subname = (caller(0))[3];
1252 croak($subname . "() called as a procedure!\n") unless(ref $self);
1253 debug(2,"DEBUG[",$subname,"]");
1254 return $self->{resources};
1255 }
1256  
1257  
1258 =head2 C<text()>
1259  
1260 Returns the uncompressed text originally stored in the DATA.FRK
1261 (C<' '>) resource. This will only work if the text was unencrypted.
1262  
1263 =cut
1264  
1265 sub text :method
1266 {
1267 my $self = shift;
1268 my $subname = (caller(0))[3];
1269 croak($subname . "() called as a procedure!\n") unless(ref $self);
1270 debug(2,"DEBUG[",$subname,"]");
1271 return $self->{text};
1272 }
1273  
1274  
1275 =head2 C<title()>
1276  
1277 Returns the book title as stored in C<< $self->{title} >>.
1278  
1279 =cut
1280  
1281 sub title :method
1282 {
1283 my $self = shift;
1284 my $subname = (caller(0))[3];
1285 croak($subname . "() called as a procedure!\n") unless(ref $self);
1286 debug(2,"DEBUG[",$subname,"]");
1287 return $self->{title};
1288 }
1289  
1290  
1291 =head2 C<tocentry($index)>
1292  
1293 Takes as a single argument an integer index to the table of contents
1294 data stored in C<< $self->{toc} >>. Returns the hashref corresponding
1295 to that TOC entry, if it exists, or undef otherwise.
1296  
1297 =cut
1298  
1299 sub tocentry :method
1300 {
1301 my ($self,$index) = @_;
1302 my $subname = (caller(0))[3];
1303 croak($subname . "() called as a procedure!\n") unless(ref $self);
1304 debug(2,"DEBUG[",$subname,"]");
1305 return $self->{toc}->[$index];
1306 }
1307  
1308  
1309 =head2 C<version()>
1310  
1311 Returns the version of the IMP format used to determine TOC and
1312 resource metadata size as stored in C<< $self->{version} >>. Expected
1313 values are 1 (10-byte metadata) and 2 (20-byte metadata).
1314  
1315 =cut
1316  
1317 sub version :method
1318 {
1319 my $self = shift;
1320 my $subname = (caller(0))[3];
1321 croak($subname . "() called as a procedure!\n") unless(ref $self);
1322 debug(2,"DEBUG[",$subname,"]");
1323 return $self->{version};
1324 }
1325  
1326  
1327 =head2 C<write_images(%args)>
1328  
1329 Writes the images, if any, to the specified output directory.
1330 Filenames are in the format C<JPEG_XXXX.jpg> or C<PNG_XXXX.png> where
1331 C<XXXX> is the image ID for that image type formatted as four
1332 hexadecimal characters.
1333  
1334 =head3 Arguments
1335  
1336 =over
1337  
1338 =item * C<dir>
1339  
1340 The output directory in which to write the file. This will be created
1341 if it does not exist. Defaults to the basename of the stored resource
1342 directory (see also L</resdirname()>).
1343  
1344 =back
1345  
1346 =cut
1347  
1348 sub write_images :method
1349 {
1350 my ($self,%args) = @_;
1351 my $subname = (caller(0))[3];
1352 croak($subname . "() called as a procedure!\n") unless(ref $self);
1353 debug(2,"DEBUG[",$subname,"]");
1354  
1355 my %valid_args = (
1356 'dir' => 1,
1357 );
1358 foreach my $arg (keys %args)
1359 {
1360 croak($subname,"(): invalid argument '",$arg,"'")
1361 if(!$valid_args{$arg});
1362 }
1363  
1364 my $dirname = $args{dir} || $self->resdirbase;
1365 my $cwd = usedir($dirname);
1366  
1367 foreach my $imagetype (IMAGETYPES)
1368 {
1369 foreach my $id (keys %{$self->{$imagetype}})
1370 {
1371 my $hexid = sprintf('%04X',$id);
1372 my $prefix = uc($imagetype) . '_';
1373 my $filename = "${prefix}${hexid}.${imagetype}";
1374 my $fh_image;
1375  
1376 if(! $self->{$imagetype}->{$id})
1377 {
1378 carp($subname,"(): data for image 0x",$hexid," not found!\n");
1379 next;
1380 }
1381  
1382 if(!open($fh_image,'>:raw',$filename))
1383 {
1384 carp($subname,"():\n",
1385 " unable to open '",$filename,"' for writing!\n");
1386 return;
1387 }
1388 print {*$fh_image} $self->{$imagetype}->{$id}->{data};
1389 if(!close($fh_image))
1390 {
1391 carp($subname,"():\n",
1392 " unable to close '",$filename,"'!\n");
1393 return;
1394 }
1395 } # foreach my $id (keys %{$self->{$imagetype}})
1396 }
1397 chdir($cwd);
1398 return 1;
1399 }
1400  
1401  
1402 =head2 C<write_imp($filename)>
1403  
1404 Takes as a sole argument the name of a file to write to, and writes a
1405 .imp file to that filename using the object attribute data.
1406  
1407 Returns 1 on success, or undef if required data (including the
1408 filename) was invalid or missing, or the file could not be written.
1409  
1410 =cut
1411  
1412 sub write_imp :method
1413 {
1414 my ($self,$filename) = @_;
1415 my $subname = (caller(0))[3];
1416 croak($subname . "() called as a procedure!\n") unless(ref $self);
1417 debug(2,"DEBUG[",$subname,"]");
1418  
1419 return unless($filename);
1420  
1421 my $fh_imp;
1422 if(!open($fh_imp,'>:raw',$filename))
1423 {
1424 carp($subname,"():\n",
1425 " unable to open '",$filename,"' for writing!\n");
1426 return;
1427 }
1428  
1429 my $headerdata = $self->pack_imp_header();
1430 my $bookpropdata = $self->pack_imp_book_properties();
1431 my $tocdata = $self->pack_imp_toc;
1432  
1433 if(not $headerdata or length($headerdata) != 48)
1434 {
1435 carp($subname,"(): invalid header data!\n");
1436 return;
1437 }
1438 if(!$bookpropdata)
1439 {
1440 carp($subname,"(): invalid book properties data!\n");
1441 return;
1442 }
1443 if(!$tocdata)
1444 {
1445 carp($subname,"(): invalid table of contents data!\n");
1446 return;
1447 }
1448 if(!$self->{resdirname})
1449 {
1450 carp($subname,"(): invalid .RES directory name!\n");
1451 return;
1452 }
1453 if(!scalar(keys %{$self->{resources}}))
1454 {
1455 carp($subname,"(): no resources found!\n");
1456 return;
1457 }
1458  
1459 print {*$fh_imp} $headerdata;
1460 print {*$fh_imp} $bookpropdata;
1461 print {*$fh_imp} $self->{resdirname};
1462 print {*$fh_imp} $tocdata;
1463  
1464 foreach my $tocentry (@{$self->{toc}})
1465 {
1466 print {*$fh_imp} ${$self->pack_imp_resource(type => $tocentry->{type})};
1467 }
1468  
1469 return 1;
1470 }
1471  
1472  
1473 =head2 C<write_resdir()>
1474  
1475 Writes a C<.RES> resource directory from the object attribute data,
1476 using C<< $self->{resdirname} >> as the directory name.
1477  
1478 =cut
1479  
1480 sub write_resdir :method
1481 {
1482 my $self = shift;
1483 my $subname = (caller(0))[3];
1484 croak($subname . "() called as a procedure!\n") unless(ref $self);
1485 debug(2,"DEBUG[",$subname,"]");
1486  
1487 if(!$self->{resdirname})
1488 {
1489 carp($subname,"(): .RES directory name not known!\n");
1490 return;
1491 }
1492  
1493 my $cwd = getcwd();
1494 my $fh_resource;
1495  
1496 mkpath($self->{resdirname});
1497 if(! -d $self->{resdirname})
1498 {
1499 croak($subname,"():\n",
1500 " unable to create .RES directory '",$self->{resdirname},
1501 "'!\n");
1502 }
1503 chdir($self->{resdirname});
1504  
1505 $self->{'RSRC.INF'} = $self->pack_imp_rsrc_inf;
1506  
1507 if($self->{'RSRC.INF'})
1508 {
1509 open($fh_resource,'>:raw','RSRC.INF')
1510 or croak($subname,"():\n",
1511 " unable to open 'RSRC.INF' for writing!\n");
1512  
1513 print {*$fh_resource} $self->{'RSRC.INF'};
1514 close($fh_resource)
1515 or croak($subname,"():\n",
1516 " unable to close 'RSRC.INF'!\n");
1517 }
1518 else
1519 {
1520 carp($subname,"():\n",
1521 " WARNING: no RSRC.INF data found!\n");
1522 }
1523  
1524 foreach my $restype (keys %{$self->{resources}})
1525 {
1526 my $filename = $self->{resources}->{$restype}->{name};
1527 $filename = 'DATA.FRK' if($filename eq ' ');
1528  
1529 open($fh_resource,'>:raw',$filename)
1530 or croak($subname,"():\n",
1531 " unable to open '",$filename,"' for writing!\n");
1532  
1533 print {*$fh_resource} $self->{resources}->{$restype}->{data};
1534 close($fh_resource)
1535 or croak($subname,"():\n",
1536 " unable to close '",$filename,"'!\n");
1537 }
1538  
1539 chdir($cwd);
1540 return 1;
1541 }
1542  
1543  
1544 =head2 C<write_text(%args)>
1545  
1546 Writes the uncompressed text, if any, to the specified output
1547 directory and file.
1548  
1549 =head3 Arguments
1550  
1551 =over
1552  
1553 =item * C<dir>
1554  
1555 The output directory in which to write the file. This will be created
1556 if it does not exist. Defaults to the basename of the stored resource
1557 directory (see also L</resdirname()>).
1558  
1559 =item * C<filename>
1560  
1561 The filename of the output file to write. If not specified, a warning
1562 will be carped and the method will return undef.
1563  
1564 =back
1565  
1566 =cut
1567  
1568 sub write_text :method
1569 {
1570 my ($self,%args) = @_;
1571 my $subname = (caller(0))[3];
1572 croak($subname . "() called as a procedure!\n") unless(ref $self);
1573 debug(2,"DEBUG[",$subname,"]");
1574  
1575 my %valid_args = (
1576 'dir' => 1,
1577 'filename' => 1,
1578 );
1579 foreach my $arg (keys %args)
1580 {
1581 croak($subname,"(): invalid argument '",$arg,"'")
1582 if(!$valid_args{$arg});
1583 }
1584  
1585 if(!$self->{text})
1586 {
1587 carp($subname,"(): no text to write!\n");
1588 return;
1589 }
1590  
1591 my $dirname = $args{dir} || $self->resdirbase;
1592 my $filename = $args{filename} || $self->resdirbase . '.html';
1593 $filename = $dirname . '/' . $filename;
1594 my $fh_text;
1595  
1596 mkpath($dirname) if(! -d $dirname);
1597  
1598 if(! -d $dirname)
1599 {
1600 carp($subname,"(): unable to create directory '",$dirname,"'!\n");
1601 return;
1602 }
1603  
1604 if(!open($fh_text,'>:raw',$filename))
1605 {
1606 carp($subname,"(): unable to open '",$filename,"' for writing!\n");
1607 return;
1608 }
1609 print {*$fh_text} $self->text;
1610 if(!close($fh_text))
1611 {
1612 carp($subname,"(): unable to close '",$filename,"'!\n");
1613 return;
1614 }
1615  
1616 return 1;
1617 }
1618  
1619  
1620 ######################################
1621 ########## MODIFIER METHODS ##########
1622 ######################################
1623  
1624 =head2 C<create_toc_from_resources()>
1625  
1626 Creates appropriate table of contents data from the metadata in
1627 C<< $self->{resources} >>, in the format specified by
1628 C<< $self->{version} >>. This will also set C<< $self->{filecount} >>
1629 to match the actual number of resources.
1630  
1631 Returns the number of resources found.
1632  
1633 =cut
1634  
1635 sub create_toc_from_resources :method
1636 {
1637 my $self = shift;
1638 my $subname = (caller(0))[3];
1639 croak($subname . "() called as a procedure!\n") unless(ref $self);
1640 debug(2,"DEBUG[",$subname,"]");
1641  
1642 $self->{toc} = ();
1643 return 0 unless($self->{resources});
1644  
1645 foreach my $type (sort keys %{$self->{resources}})
1646 {
1647 my %tocentry;
1648 $tocentry{name} = $self->{resources}->{$type}->{name};
1649 $tocentry{type} = $type;
1650 $tocentry{size} = length($self->{resources}->{$type}->{data});
1651 $tocentry{unknown1} = $self->{resources}->{$type}->{unknown1};
1652 $tocentry{unknown2} = $self->{resources}->{$type}->{unknown2};
1653 push(@{$self->{toc}},\%tocentry);
1654 }
1655  
1656 $self->{filecount} = scalar($self->{toc});
1657 debug(2,"DEBUG: created TOC data from ",$self->{filecount}," records");
1658 return $self->{filecount};
1659 }
1660  
1661  
1662 =head2 C<parse_eti_server_data($data)>
1663  
1664 Parses ETI server data, as potentially found appended to the end of
1665 .imp book properties or a RSRC.INF resource file on encrypted books
1666 downloaded directly from ETI servers.
1667  
1668 Takes as a single argument a string containing just the extra appended
1669 data, and stores the parsed values in C<< $self->{etiserverdata} >> as
1670 a hash. Note that parsing requires knowledge of the length of the
1671 book properties at the time this data was inserted; if the book
1672 properties have not been properly parsed or have been modified, the
1673 resulting behaviour of this method is not defined.
1674  
1675 Returns the number of bytes handled, zero if no data was provided.
1676  
1677 The data has the following format and keys:
1678  
1679 =over
1680  
1681 =item * [0-3 bytes]: padding data to make sure the following data is
1682 4-byte aligned, stored in key C<pad>.
1683  
1684 =item * [4 bytes, big-endian unsigned long int]: unknown value,
1685 usually = 2, stored in key C<unknown1>
1686  
1687 =item * [4 bytes, big-endian unsigned long int]: issue number for
1688 periodicals (always 0xffffffff for books), stored in key
1689 C<issuenumber>.
1690  
1691 =item * [variable-length null-terminated string]: content feed for
1692 periodicals, null string for books, stored in key C<contentfeed>.
1693  
1694 =item * [variable-length null-terminated string]: source string in the
1695 format C<'SOURCE_ID:SOURCE_TYPE:None'>, where C<SOURCE_ID> is usually
1696 '3' and C<SOURCE_TYPE> is usually 'B'.
1697  
1698 =item * [4 bytes, big-endian unsigned long int]: unknown value, stored
1699 in key C<unknown2>. This value may not be present at all.
1700  
1701 =back
1702  
1703 =cut
1704  
1705 sub parse_eti_server_data :method
1706 {
1707 my ($self,$data) = @_;
1708 my $subname = (caller(0))[3];
1709 croak($subname . "() called as a procedure!\n") unless(ref $self);
1710 debug(2,"DEBUG[",$subname,"]");
1711  
1712 return 0 unless($data);
1713  
1714 my $proplength = $self->bookproplength;
1715 my $length = length($data);
1716 if($length < 10)
1717 {
1718 carp($subname,"():\n",
1719 " data is too short to contain ETI server data! [",
1720 $length," bytes]\n");
1721 return 0;
1722 }
1723  
1724 $self->{etiserverdata} = {};
1725  
1726 # Up to 3 bytes of padding to make sure that the following data is
1727 # 4-byte aligned.
1728 my $padlength = $proplength % 4;
1729 my @list;
1730 if($padlength)
1731 {
1732 $padlength = 4 - $padlength;
1733 $self->{etiserverdata}->{pad} = substr($data,0,$padlength);
1734 $proplength += $padlength;
1735 }
1736  
1737 @list = unpack('NNZ*Z*N',substr($data,$padlength));
1738 $self->{etiserverdata}->{unknown1} = $list[0];
1739 $self->{etiserverdata}->{issuenumber} = $list[1];
1740 $self->{etiserverdata}->{contentfeed} = $list[2];
1741 $self->{etiserverdata}->{source} = $list[3];
1742 $self->{etiserverdata}->{unknown2} = $list[4];
1743 debug(2," pad=",hexstring($self->{etiserverdata}->{pad}))
1744 if($self->{etiserverdata}->{pad});
1745 debug(2,
1746 " unknown1=",$list[0]," \t\tissuenumber=",$list[1],"\n",
1747 " contentfeed='",$list[2],"' \tsource='",$list[3],"'");
1748 debug(2," unknown2=",$list[4]) if(defined $list[4]);
1749  
1750 return($length);
1751 }
1752  
1753  
1754 =head2 C<parse_imp_book_properties($propdata)>
1755  
1756 Takes as a single argument a string containing the book properties
1757 data. Sets the object variables from its contents, which should be
1758 seven null-terminated strings in the following order:
1759  
1760 =over
1761  
1762 =item * Identifier
1763  
1764 =item * Category
1765  
1766 =item * Subcategory
1767  
1768 =item * Title
1769  
1770 =item * Last Name
1771  
1772 =item * Middle Name
1773  
1774 =item * First Name
1775  
1776 =back
1777  
1778 Note that the entire name is frequently placed into the "First Name"
1779 component, and the "Last Name" and "Middle Name" components are left
1780 blank.
1781  
1782 In addition, ETI server data may be appended to this data on encrypted
1783 books downloaded from ETI servers. If present, that data will be
1784 stored in the hash C<< $self->{etiserverdata} >>. See
1785 L</parse_eti_server_data($data)> for details.
1786  
1787 A warning will be carped if the length of the parsed properties
1788 (including the C null string terminators) is not equal to the length
1789 of the data passed.
1790  
1791 =cut
1792  
1793 sub parse_imp_book_properties :method
1794 {
1795 my ($self,$propdata) = @_;
1796 my $subname = (caller(0))[3];
1797 croak($subname . "() called as a procedure!\n") unless(ref $self);
1798 debug(2,"DEBUG[",$subname,"]");
1799  
1800 my @properties = unpack("Z*Z*Z*Z*Z*Z*Z*",$propdata);
1801 if(scalar(@properties) != 7)
1802 {
1803 carp($subname,"(): WARNING: expected 7 book properties, but found ",
1804 scalar(@properties),"!\n");
1805 }
1806  
1807 $self->{identifier} = $properties[0];
1808 $self->{category} = $properties[1];
1809 $self->{subcategory} = $properties[2];
1810 $self->{title} = $properties[3];
1811 $self->{lastname} = $properties[4];
1812 $self->{middlename} = $properties[5];
1813 $self->{firstname} = $properties[6];
1814  
1815 debug(2,"DEBUG: found ",scalar(@properties)," properties: ");
1816 debug(2," Identifier: ",$self->{identifier});
1817 debug(2," Category: ",$self->{category});
1818 debug(2," Subcategory: ",$self->{subcategory});
1819 debug(2," Title: ",$self->{title});
1820 debug(2," Last Name: ",$self->{lastname});
1821 debug(2," Middle Name: ",$self->{middlename});
1822 debug(2," First Name: ",$self->{firstname});
1823  
1824  
1825 # On encrypted files, there may be addtional ETI server data
1826 # appended
1827 my $proplength = $self->bookproplength;
1828 if($proplength < length($propdata))
1829 {
1830 debug(1,"Book properties data has extra ETI server data appended");
1831 $self->parse_eti_server_data(substr($propdata,$proplength));
1832 }
1833 return 1;
1834 }
1835  
1836  
1837 =head2 C<parse_imp_header()>
1838  
1839 Parses the first 48 bytes of a .IMP file, setting object variables.
1840 The method croaks if it receives any more or less than 48 bytes.
1841  
1842 =head3 Header Format
1843  
1844 =over
1845  
1846 =item * Offset 0x00 [2 bytes, big-endian unsigned short int]
1847  
1848 Version. Expected values are 1 or 2; the version affects the format
1849 of the table of contents header. If this isn't 1 or 2, the method
1850 carps a warning and returns undef.
1851  
1852 =item * Offset 0x02 [8 bytes]
1853  
1854 Identifier. This is always 'BOOKDOUG', and the method carps a warning
1855 and returns undef if it isn't.
1856  
1857 =item * Offset 0x0A [8 bytes]
1858  
1859 Unknown data, stored in C<< $self->{unknown0x0a} >>. Use with caution
1860 -- this value may be renamed if more information is obtained.
1861  
1862 =item * Offset 0x12 [2 bytes, big-endian unsigned short int]
1863  
1864 Number of included files, stored in C<< $self->{filecount} >>.
1865  
1866 =item * Offset 0x14 [2 bytes, big-endian unsigned short int]
1867  
1868 Length in bytes of the .RES directory name, stored in
1869 C<< $self->{resdirlength} >>.
1870  
1871 =item * Offset 0x16 [2 bytes, big-endian unsigned short int]
1872  
1873 Offset from the point after this value to the .RES directory name,
1874 which also marks the end of the book properties, stored in
1875 C<< $self->{resdiroffset} >>. Note that this is NOT the length of the
1876 book properties. To get the length of the book properties, subtract
1877 24 from this value (the number of bytes remaining in the header after
1878 this point). It is also NOT the offset from the beginning of the file
1879 to the .RES directory name -- to find that, add 24 to this value (the
1880 number of bytes already parsed).
1881  
1882 =item * Offset 0x18 [4 bytes, big-endian unsigned long int?]
1883  
1884 Unknown value, stored in C<< $self->{unknown0x18} >>. Use with
1885 caution -- this value may be renamed if more information is obtained.
1886  
1887 =item * Offset 0x1C [4 bytes, big-endian unsigned long int?]
1888  
1889 Unknown value, stored in C<< $self->{unknown0x1c} >>. Use with
1890 caution -- this value may be renamed if more information is obtained.
1891  
1892 =item * Offset 0x20 [4 bytes, big-endian unsigned long int]
1893  
1894 Compression type, stored in C<< $self->{compression} >>. Expected
1895 values are 0 (no compression) and 1 (LZSS compression).
1896  
1897 =item * Offset 0x24 [4 bytes, big-endian unsigned long int]
1898  
1899 Encryption type, stored in C<< $self->{encryption} >>. Expected
1900 values are 0 (no encryption) and 2 (DES encryption).
1901  
1902 =item * Offset 0x28 [2 bytes, big-ending unsigned short int]
1903  
1904 Unknown value, stored in C<< $self->{unknown0x28} >>. Use with
1905 caution -- this value may be renamed if more information is obtained.
1906  
1907 =item * Offset 0x2A [1 byte]
1908  
1909 Unknown value, stored in C<< $self->{unknown0x2A} >>. Use with
1910 caution -- this value may be renamed if more information is obtained.
1911  
1912 =item * Offset 0x2B [2 nybbles (1 byte)]
1913  
1914 The upper nybble at this position is the IMP reader device for which the
1915 e-book was designed, stored in C<< $self->{device} >>. Expected values
1916 are 0 (Softbook 200/250e), 1 (REB 1200/GEB 2150), and 2 (EBW
1917 1150/GEB1150).
1918  
1919 The lower nybble marks the possible zoom states, stored in
1920 C<< $self->{zoomstates} >>. Expected values are 0 (both zooms), 1
1921 (small zoom), and 2 (large zoom)
1922  
1923 =item * Offset 0x2C [4 bytes, big-endian unsigned long int]
1924  
1925 Unknown value, stored in C<< $self->{unknown0x2c} >>. Use with
1926 caution -- this value may be renamed if more information is obtained.
1927  
1928 =back
1929  
1930 =cut
1931  
1932 sub parse_imp_header :method
1933 {
1934 my ($self,$headerdata) = @_;
1935 my $subname = (caller(0))[3];
1936 croak($subname . "() called as a procedure!\n") unless(ref $self);
1937 debug(2,"DEBUG[",$subname,"]");
1938  
1939 my $length = length($headerdata);
1940 if($length != 48)
1941 {
1942 croak($subname,"(): expected 48 bytes, was passed ",$length,"!\n");
1943 }
1944  
1945 my $identstring = substr($headerdata,2,8);
1946 if($identstring ne 'BOOKDOUG')
1947 {
1948 carp($subname,"(): invalid IMP header!\n");
1949 return;
1950 }
1951  
1952 $self->{version} = unpack('n',$headerdata);
1953 if($self->{version} < 1 or $self->{version} > 2)
1954 {
1955 carp($subname,"(): Version ",$self->{version}," is not supported!\n");
1956 return;
1957 }
1958  
1959 $self->{unknown0x0a} = substr($headerdata,10,8);
1960  
1961 # Unsigned short int values
1962 my @list = unpack('nnn',substr($headerdata,0x12,6));
1963 $self->{filecount} = $list[0];
1964 $self->{resdirlength} = $list[1];
1965 $self->{resdiroffset} = $list[2];
1966 debug(2,"DEBUG: IMP file count = ",$self->{filecount});
1967 debug(2,"DEBUG: IMP resdirlength = ",$self->{resdirlength});
1968 debug(2,"DEBUG: IMP resdir offset = ",$self->{resdiroffset});
1969  
1970 # Unknown long ints
1971 @list = unpack('NN',substr($headerdata,0x18,8));
1972 $self->{unknown0x18} = $list[0];
1973 $self->{unknown0x1c} = $list[1];
1974 debug(2,"DEBUG: Unknown long int at offset 0x18 = ",$self->{unknown0x18});
1975 debug(2,"DEBUG: Unknown long int at offset 0x1c = ",$self->{unknown0x1c});
1976  
1977 # Compression/Encryption/Unknown
1978 @list = unpack('NNnC',substr($headerdata,0x20,11));
1979 $self->{compression} = $list[0];
1980 $self->{encryption} = $list[1];
1981 $self->{unknown0x28} = $list[2];
1982 $self->{unknown0x2a} = $list[3];
1983 debug(2,"DEBUG: IMP compression = ",$self->{compression});
1984 debug(2,"DEBUG: IMP encryption = ",$self->{encryption});
1985 debug(2,"DEBUG: Unknown short int at offset 0x28 = ",$self->{unknown0x28});
1986 debug(2,"DEBUG: Unknown byte at offset 0x2A = ",$self->{unknown0x2a});
1987  
1988 # Zoom State, and Unknown
1989 @list = unpack('CN',substr($headerdata,0x2B,5));
1990 $self->{device} = $list[0] >> 4;
1991 $self->{zoomstates} = $list[0] & 0x0f;
1992 $self->{unknown0x2c} = $list[1];
1993  
1994 debug(2,"DEBUG: IMP device = ",$self->{device});
1995 debug(2,"DEBUG: IMP zoom state = ",$self->{zoomstates});
1996 debug(2,"DEBUG: Unknown long int at offset 0x2c = ",$self->{unknown0x2c});
1997  
1998 return 1;
1999 }
2000  
2001  
2002 =head2 C<parse_resource_cm()>
2003  
2004 Parses the C<!!cm> resource loaded into C<< $self->{resources} >>,
2005 if present, extracting the LZSS uncompression parameters into
2006 C<< $self->{lzssoffsetbits} >> and C<< $self->{lzsslengthbits} >>.
2007  
2008 Returns 1 on success, or undef if no C<!!cm> resource has been loaded
2009 yet or the resource data is invalid.
2010  
2011 =cut
2012  
2013 sub parse_resource_cm :method
2014 {
2015 my $self = shift;
2016 my $subname = (caller(0))[3];
2017 croak($subname . "() called as a procedure!\n") unless(ref $self);
2018 debug(2,"DEBUG[",$subname,"]");
2019  
2020 return unless($self->{resources}->{'!!cm'});
2021  
2022 my @list;
2023 my $version;
2024 my $ident; # Must be constant string '!!cm'
2025 my $unknown1;
2026 my $indexoffset;
2027 my $lzssdata;
2028  
2029 @list = unpack('na[4]NN',$self->{resources}->{'!!cm'}->{data});
2030 $version = $list[0];
2031 $ident = $list[1];
2032 $unknown1 = $list[2];
2033 $indexoffset = $list[3];
2034  
2035 if($ident ne '!!cm')
2036 {
2037 carp($subname,"():\n",
2038 " Invalid '!!cm' record!\n");
2039 return;
2040 }
2041 debug(2,"DEBUG: parsing !!cm v",$version,", index offset ",$indexoffset);
2042 $lzssdata = substr($self->{resources}->{'!!cm'}->{data},$indexoffset-4,4);
2043 @list = unpack('nn',$lzssdata);
2044  
2045 if($list[0] + $list[1] > 32
2046 or $list[0] < 2
2047 or $list[1] < 1)
2048 {
2049 carp($subname,"():\n",
2050 " invalid LZSS compression bit lengths!\n",
2051 "[",$list[0]," offset bits, ",
2052 $list[1]," length bits]\n");
2053 return;
2054 }
2055  
2056 $self->{lzssoffsetbits} = $list[0];
2057 $self->{lzsslengthbits} = $list[1];
2058 debug(2,"DEBUG: !!cm specifies ",$list[0]," offset bits, ",
2059 $list[1]," length bits");
2060 return 1;
2061 }
2062  
2063  
2064 =head2 C<parse_resource_images()>
2065  
2066 Parses the image data resources loaded into C<< $self->{resources} >>,
2067 if present, placing the image data and metadata of each image found
2068 into C<< $self->{jpg} >> and C<< $self->{png} >>, keyed by 16-bit
2069 image resource ID.
2070  
2071 Returns the total number of images found and parsed.
2072  
2073 This method is called automatically by L</load()> and L</load_resdir()>.
2074  
2075 See also accessor methods L</image(%args)> and L</image_hashrefs(%args)>.
2076  
2077 =cut
2078  
2079 sub parse_resource_images :method
2080 {
2081 my $self = shift;
2082 my $subname = (caller(0))[3];
2083 croak($subname . "() called as a procedure!\n") unless(ref $self);
2084 debug(2,"DEBUG[",$subname,"]");
2085  
2086 my $headersize;
2087 my $imgdata;
2088 my $imgcount;
2089 my $total = 0;
2090 my @list;
2091  
2092 if($self->{device} == DEVICE_EBW1150) { $headersize = 14; }
2093 else { $headersize = 12; }
2094  
2095 foreach my $resource (keys %IMAGE_RESOURCE_MAP)
2096 {
2097 next unless($self->{resources}->{$resource});
2098 my $rsize = $self->{resources}->{$resource}->{size};
2099 my $itype = $IMAGE_RESOURCE_MAP{$resource};
2100 next if ($rsize <= 32);
2101  
2102 @list = unpack('na[4]NNnNNNN',$self->{resources}->{$resource}->{data});
2103 my $version = $list[0];
2104 my $ident = $list[1];
2105 my $unknown1 = $list[2];
2106 my $tocoffset = $list[3];
2107 my $unknown2 = $list[4];
2108 my $unknown3 = $list[5];
2109 my $unknown4 = $list[6];
2110 my $unknown5 = $list[7];
2111 my $unknown6 = $list[8];
2112  
2113 if($ident ne $resource)
2114 {
2115 carp($subname,"():\n",
2116 " Invalid '",$resource,"' record!\n");
2117 next;
2118 }
2119  
2120 debug(2,"DEBUG: parsing ",$resource," resource v",$version,
2121 ", index offset ",$tocoffset);
2122  
2123 $imgcount = ($rsize - $tocoffset) / $headersize;
2124  
2125 debug(2,"DEBUG: ",$imgcount," ",$itype," images listed in header");
2126  
2127 $self->{$itype} = {};
2128 foreach my $pos (0 .. ($imgcount - 1))
2129 {
2130 my $id; # Image ID -- this is only unique for each imagetype
2131 my $hexid; # 4-digit hexadecimal string version of $id
2132  
2133 $imgdata = substr($self->{resources}->{$resource}->{data},
2134 $tocoffset + ($headersize * $pos),$headersize);
2135 if($self->{device} == DEVICE_EBW1150)
2136 {
2137 #Standard 1150 Header (14 bytes)
2138 @list = unpack("vvVVv",$imgdata);
2139 $id = $list[0];
2140 $self->{$itype}->{$id}->{unknown} = $list[1];
2141 $self->{$itype}->{$id}->{length} = $list[2];
2142 $self->{$itype}->{$id}->{offset} = $list[3];
2143 $self->{$itype}->{$id}->{const0} = $list[4];
2144 }
2145 else
2146 {
2147 #Standard 1200 Header (12 bytes)
2148 @list = unpack("nNNn",$imgdata);
2149 $id = $list[0];
2150 $self->{$itype}->{$id}->{length} = $list[1];
2151 $self->{$itype}->{$id}->{offset} = $list[2];
2152 $self->{$itype}->{$id}->{const0} = $list[3];
2153 }
2154  
2155 if($EBook::Tools::debug > 2)
2156 {
2157 printf(" id=%04X unk1=0x%04X length=%d offset=%d, const0=0x%04X\n",
2158 $id, $self->{$itype}->{$id}->{unknown},
2159 $self->{$itype}->{$id}->{length},
2160 $self->{$itype}->{$id}->{offset},
2161 $self->{$itype}->{$id}->{const0});
2162 }
2163  
2164 $hexid = sprintf("%04X",$id);
2165  
2166 $self->{$itype}->{$id}->{data} =
2167 substr($self->{resources}->{$resource}->{data},
2168 $self->{$itype}->{$id}->{offset},
2169 $self->{$itype}->{$id}->{length});
2170  
2171 my ($imagex,$imagey,$imagetype) =
2172 imgsize(\$self->{$itype}->{$id}->{data});
2173 if(defined($imagex) && $imagetype)
2174 {
2175 debug(2," ",$itype," image ",$pos," (ID '",$hexid,"') is valid ",
2176 $imagetype," image data (",$imagex," x ",$imagey,")");
2177 }
2178 else
2179 {
2180 carp($subname,"():\n",
2181 " ",$itype," image ",$pos," (ID '",$id,
2182 "') is not valid image data!\n");
2183 next;
2184 }
2185 } # foreach my $pos (0 .. ($imgcount - 1))
2186  
2187 my $found = scalar keys %{$self->{$itype}};
2188 if($found != $imgcount)
2189 {
2190 carp($subname,"()\n",
2191 " resource specified ",$imgcount," images, but found ",
2192 $found,"!\n");
2193 }
2194 $total += $found;
2195 } # foreach my $resource (keys %IMAGE_RESOURCE_MAP)
2196  
2197 return $total;
2198 }
2199  
2200  
2201 =head2 C<parse_resource_imrn()>
2202  
2203 Parses the index of text offsets to all images as stored in
2204 C<< $self->{resources}->{'ImRn'} >>, if present, storing them in
2205 C<< $self->{imrn} >> as a hash of hashrefs indexed by its
2206 32-bit integer offset to the 0x0F control code in the uncompressed
2207 text stored in the DATA.FRK resource.
2208  
2209 Returns the total number of offsets found and parsed.
2210  
2211 The hash keys of each offset hash are:
2212  
2213 =over
2214  
2215 =item * C<width>
2216  
2217 Image display width in pixels.
2218  
2219 =item * C<height>
2220  
2221 Image display height in pixels.
2222  
2223 =item * C<id>
2224  
2225 A 16-bit integer value used to uniquely identify the image inside a
2226 particular resource type.
2227  
2228 =item * C<restype>
2229  
2230 The four-letter resource type string.
2231  
2232 =item * C<constF1>
2233  
2234 A 32-bit value of unknown purpose which should always be 0xFFFFFFFF.
2235  
2236 =item * C<constF2>
2237  
2238 A second 32-bit value of unknown purpose which should always be 0xFFFFFFFF.
2239  
2240 =item * C<const0>
2241  
2242 A 32-bit integer value of unknown purpose which should always be 0x00000000.
2243  
2244 =item * C<constB>
2245  
2246 A 16-bit integer value of unknown purpose which could be 0xFFFA, 0xFFFB,
2247 0xFFFC, or 0xFFFE.
2248  
2249 =item * C<unknown16>
2250  
2251 A 16-bit integer value of unknown purpose found only in 1150 resources.
2252  
2253 =item * C<unknown32>
2254  
2255 A 32-bit integer value of unknown purpose.
2256  
2257 =back
2258  
2259 This method is called automatically by L</load()> and L</load_resdir()>.
2260  
2261 =cut
2262  
2263 sub parse_resource_imrn :method
2264 {
2265 my $self = shift;
2266 my $subname = (caller(0))[3];
2267 croak($subname . "() called as a procedure!\n") unless(ref $self);
2268 debug(2,"DEBUG[",$subname,"]");
2269  
2270 return unless($self->{resources}->{'ImRn'});
2271  
2272 my $headersize;
2273 my $imrndata;
2274 my $imrncount;
2275 my $total = 0;
2276 my @list;
2277 my $idxdata;
2278 my $idxsize;
2279 my $idx1id;
2280 my $idx1size;
2281 my $idx1offset;
2282 my $idx1const0;
2283  
2284 if($self->{device} == DEVICE_EBW1150)
2285 {
2286 $headersize = 36;
2287 $idxsize = 14;
2288 }
2289 else
2290 {
2291 $headersize = 32;
2292 $idxsize = 12;
2293 }
2294  
2295 my $rsize = $self->{resources}->{'ImRn'}->{size};
2296 next if ($rsize <= 32);
2297  
2298 @list = unpack('na[4]NNnNNNN',$self->{resources}->{'ImRn'}->{data});
2299 my $version = $list[0];
2300 my $ident = $list[1];
2301 my $unknown1 = $list[2];
2302 my $tocoffset = $list[3];
2303 my $unknown2 = $list[4];
2304 my $unknown3 = $list[5];
2305 my $unknown4 = $list[6];
2306 my $unknown5 = $list[7];
2307 my $unknown6 = $list[8];
2308  
2309 if($ident ne 'ImRn')
2310 {
2311 carp($subname,"():\n",
2312 " Invalid 'ImRn' record!\n");
2313 next;
2314 }
2315  
2316 debug(2,"DEBUG: parsing 'ImRn' resource v",$version,
2317 ", index offset ",$tocoffset);
2318  
2319 $imrncount = ($rsize - 32 - 12) / $headersize;
2320  
2321 debug(2,"DEBUG: ",$imrncount," images listed in header");
2322  
2323 $self->{imrn} = {};
2324 foreach my $pos (0 .. ($imrncount - 1))
2325 {
2326 my $offset; # offset within DATA.FRK text (0x0F) of image insertion
2327  
2328 # FIX: The last (number $imrncount) image record is 2 bytes shorter and
2329 # will not be of size 36, but 34. Currently this code will read into
2330 # the index record!
2331 $imrndata = substr($self->{resources}->{'ImRn'}->{data},
2332 32 + ($headersize * $pos),$headersize);
2333 if($self->{device} == DEVICE_EBW1150)
2334 {
2335 #imrn 1150 record
2336 @list = unpack("VVvvVvvVVa[4]v",$imrndata);
2337 $offset = $list[7];
2338  
2339 $self->{imrn}->{$offset}->{constF1} = $list[0];
2340 $self->{imrn}->{$offset}->{constF2} = $list[1];
2341 $self->{imrn}->{$offset}->{width} = $list[2];
2342 $self->{imrn}->{$offset}->{height} = $list[3];
2343 $self->{imrn}->{$offset}->{const0} = $list[4];
2344 $self->{imrn}->{$offset}->{unknown16} = $list[5];
2345 $self->{imrn}->{$offset}->{constB} = $list[6];
2346 $self->{imrn}->{$offset}->{unknown32} = $list[8];
2347 $self->{imrn}->{$offset}->{restype} = $list[9];
2348 $self->{imrn}->{$offset}->{id} = $list[10];
2349  
2350 # restypes only reversed in 1150 ebooks
2351 # (restypes in 1200 ebooks are not reversed)
2352 my %restypefix = (
2353 ' FIG' => 'GIF ',
2354 'GEPJ' => 'JPEG',
2355 ' GNP' => 'PNG ',
2356 '2CIP' => 'PIC2',
2357 'TCIP' => 'PICT',
2358 );
2359 my $type = $self->{imrn}->{$offset}->{restype};
2360 $self->{imrn}->{$offset}->{restype} = $restypefix{$type}
2361 if($restypefix{$type});
2362 }
2363 else
2364 {
2365 #imrn 1200 record
2366 @list = unpack("NNnnNnNNa[4]n",$imrndata);
2367 $offset = $list[6];
2368  
2369 $self->{imrn}->{$offset}->{constF1} = $list[0];
2370 $self->{imrn}->{$offset}->{constF2} = $list[1];
2371 $self->{imrn}->{$offset}->{width} = $list[2];
2372 $self->{imrn}->{$offset}->{height} = $list[3];
2373 $self->{imrn}->{$offset}->{const0} = $list[4];
2374 $self->{imrn}->{$offset}->{constB} = $list[5];
2375 $self->{imrn}->{$offset}->{unknown32} = $list[7];
2376 $self->{imrn}->{$offset}->{restype} = $list[8];
2377 $self->{imrn}->{$offset}->{id} = $list[9];
2378 }
2379  
2380 my $restype = $self->{imrn}->{$offset}->{restype};
2381 my $imgtype = $IMAGE_RESOURCE_MAP{$restype};
2382 my $hexid = sprintf('%04X',$self->{imrn}->{$offset}->{id});
2383 my $width = $self->{imrn}->{$offset}->{width};
2384 my $height = $self->{imrn}->{$offset}->{height};
2385  
2386 if(none { $restype eq $_ } (IMAGERESOURCES) )
2387 {
2388 carp($subname,"():\n",
2389 " invalid image type '",$restype,"' at offset ",$offset,"!\n");
2390 next;
2391 }
2392 debug(2,"DEBUG: ImRn offset ",$offset,": '",$restype,"' 0x",$hexid,
2393 " (",$width," x ",$height,")");
2394  
2395 # PICT images are unviewable, so see if there is an alternate to use instead
2396 if($imgtype and $imgtype eq 'pic')
2397 {
2398 my $id = $self->{imrn}->{$offset}->{id};
2399 my $alttype = $self->find_image_type($id,'pic');
2400 $imgtype = $alttype if($alttype);
2401 }
2402  
2403 #TODO: use height/width from Pcz0/PcZ0 records
2404 my $filename = uc($imgtype) . "_${hexid}.${imgtype}";
2405 $self->{offsetelements}->{$offset} =
2406 '<img src="' . $filename . '" width="' . $width . '" height="' . $height
2407 . '" alt="' . $filename . '" />';
2408  
2409 debug(2,"DEBUG: tag = '",$self->{offsetelements}->{$offset},"'");
2410 if($EBook::Tools::debug > 2)
2411 {
2412 printf(" offset=%d restype=%s imgid=%04X constF1=0x%04X constF2=0x%04X width=%d height=%d const0=0x%04X, constB=0x%04X",
2413 $offset, $self->{imrn}->{$offset}->{restype},
2414 $self->{imrn}->{$offset}->{id},
2415 $self->{imrn}->{$offset}->{constF1},
2416 $self->{imrn}->{$offset}->{constF2},
2417 $self->{imrn}->{$offset}->{width},
2418 $self->{imrn}->{$offset}->{height},
2419 $self->{imrn}->{$offset}->{const0},
2420 $self->{imrn}->{$offset}->{constB},
2421 $self->{imrn}->{$offset}->{unknown16},
2422 $self->{imrn}->{$offset}->{unknown32});
2423  
2424 if($self->{imrn}->{$offset}->{const2})
2425 {
2426 printf(" const2=0x%04X",
2427 $self->{imrn}->{$offset}->{const2});
2428 }
2429 printf("\n");
2430 }
2431 }
2432  
2433 $idxdata = substr($self->{resources}->{'ImRn'}->{data},$tocoffset,$idxsize);
2434 if($self->{device} == DEVICE_EBW1150)
2435 {
2436 #Standard 1150 (14-byte) Index Header
2437 @list = unpack("vVVV",$idxdata);
2438 }
2439 else
2440 {
2441 #Standard 1200 (12-byte) Index Header
2442 @list = unpack("nNNn",$idxdata);
2443 }
2444 $idx1id = $list[0];
2445 $idx1size = $list[1];
2446 $idx1offset = $list[2];
2447 $idx1const0 = $list[3];
2448  
2449 $total = scalar keys %{$self->{imrn}};
2450 if($total != $imrncount)
2451 {
2452 carp($subname,"()\n",
2453 " resource specified ",$imrncount," ImRn entries, but found ",
2454 $total,"!\n");
2455 }
2456  
2457 return $total;
2458 }
2459  
2460  
2461 =head2 C<parse_text()>
2462  
2463 Parses the C<' '> (DATA.FRK) resource loaded into
2464 C<< $self->{resources} >>, if present, extracting the text into
2465 C<< $self->{text} >>, uncompressing it if necessary. LZSS uncompression
2466 will use the C<< $self->{lzsslengthbits} >> and
2467 C<< $self->{lzssoffsetbits} >> attributes if present, and default to 3
2468 length bits and 14 offset bits otherwise.
2469  
2470 HTML headers and footers are then applied, and control codes replaced
2471 with appropriate tags.
2472  
2473 Returns the length of the raw uncompressed text before any HTML
2474 modification was done, or undef if no text resource was found or the
2475 text was encrypted.
2476  
2477 =cut
2478  
2479 sub parse_text :method
2480 {
2481 my $self = shift;
2482 my $subname = (caller(0))[3];
2483 croak($subname . "() called as a procedure!\n") unless(ref $self);
2484 debug(2,"DEBUG[",$subname,"]");
2485  
2486 return unless($self->{resources}->{' '});
2487  
2488 $self->parse_resource_cm();
2489 my $lengthbits = $self->{lzsslengthbits} || 3;
2490 my $offsetbits = $self->{lzssoffsetbits} || 14;
2491 my $lzss = EBook::Tools::LZSS->new(lengthbits => $lengthbits,
2492 offsetbits => $offsetbits,
2493 windowstart => 1);
2494 my $textref;
2495 my $textlength;
2496  
2497 if($self->{encryption})
2498 {
2499 warn($subname,"(): encrypted text not supported!\n");
2500 return;
2501 }
2502  
2503 if($self->{compression})
2504 {
2505 $textref = $lzss->uncompress(\$self->{resources}->{' '}->{data});
2506 }
2507 else
2508 {
2509 $textref = \$self->{resources}->{' '}->{data};
2510 }
2511 $textlength = length($$textref);
2512  
2513 if(!$textlength)
2514 {
2515 carp($subname,"(): no text extracted from DATA.FRK resource!\n");
2516 return;
2517 }
2518  
2519 $self->{text} = <<'END';
2520 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2521 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2522  
2523 <html xmlns="http://www.w3.org/1999/xhtml">
2524 <head>
2525 <meta http-equiv="CONTENT-TYPE" content="text/html; charset=windows-1252" />
2526 END
2527  
2528 $self->{text} .= " <title>$self->{title}</title>\n";
2529 $self->{text} .= "</head>\n<body>\n";
2530  
2531 my $pos = 0;
2532 my %ccharmap = (
2533 0x0A => "\n" . '<br style="page-break-before: always" />', # supported!
2534 0x0B => "\n<p>",
2535 0x0D => "<br />\n",
2536 0x0E => '', # Start of <table>, not yet supported
2537 0x13 => '', # End of table cell </td>, not yet supported
2538 0x14 => "\n<hr />\n",
2539 0x8E => "&eacute;",
2540 0xA0 => "&nbsp;",
2541 0xA5 => "&bull;",
2542 0xA8 => "&reg;",
2543 0xA9 => "&copy;",
2544 0xAA => "&trade;",
2545 0xAE => "&AElig;",
2546 0xC7 => "&laquo;",
2547 0xC8 => "&raquo;",
2548 0xC9 => "&hellip;",
2549 0xD0 => "&ndash;",
2550 0xD1 => "&mdash;",
2551 0xD2 => "&ldquo;",
2552 0xD3 => "&rdquo;",
2553 0xD4 => "&lsquo;",
2554 0xD5 => "&rsquo;",
2555 0xE1 => "&middot;",
2556 );
2557  
2558 while($pos < $textlength)
2559 {
2560 my $char = substr($$textref,$pos,1);
2561 my $ord = ord($char);
2562  
2563 if($ord == 0x0F) # Image
2564 {
2565 $self->{text} .= $self->{offsetelements}->{$pos};
2566 }
2567 elsif(defined $ccharmap{$ord})
2568 {
2569 $self->{text} .= $ccharmap{$ord};
2570 }
2571 else
2572 {
2573 $self->{text} .= $char;
2574 }
2575 $pos++;
2576 }
2577 $self->{text} .= "\n</body>\n</html>";
2578 $self->{text} =~ s/\x15 .*? \x15//gx; # Kill header - comment out?
2579 $self->{text} =~ s/\x16 .*? \x16//gx; # Kill footer
2580 return $textlength;
2581 }
2582  
2583  
2584 =head2 C<parse_imp_toc_v1($tocdata)>
2585  
2586 Takes as a single argument a string containing the table of contents
2587 data, and parses it into object attributes following the version 1
2588 format (10 bytes per entry).
2589  
2590 =head3 Format
2591  
2592 =over
2593  
2594 =item * Offset 0x00 [4 bytes, text]
2595  
2596 Resource name. Stored in hash key C<name>. In the case of the
2597 'DATA.FRK' text resource, this will be four spaces (C<' '>).
2598  
2599 =item * Offset 0x04 [2 bytes, big-endian unsigned short int]
2600  
2601 Unknown, but always zero or one. Stored in hash key C<unknown1>.
2602  
2603 =item * Offset 0x08 [4 bytes, big-endian unsigned long int]
2604  
2605 Size of the resource data in bytes. Stored in hash key C<size>.
2606  
2607 =back
2608  
2609 =cut
2610  
2611 sub parse_imp_toc_v1 :method
2612 {
2613 my ($self,$tocdata) = @_;
2614 my $subname = (caller(0))[3];
2615 croak($subname . "() called as a procedure!\n") unless(ref $self);
2616 debug(2,"DEBUG[",$subname,"]");
2617  
2618 my $length = length($tocdata);
2619 my $lengthexpected = 10 * $self->{filecount};
2620 my $tocentrydata;
2621 my $offset = 0;
2622  
2623 if($self->{version} != 1)
2624 {
2625 carp($subname,"(): attempting to parse a version 1 TOC,",
2626 " but the file appears to be version ",$self->{version},"!\n");
2627 }
2628  
2629 if($length != $lengthexpected)
2630 {
2631 carp($subname,"(): expected ",$lengthexpected," bytes, but received ",
2632 $length," -- aborting!\n");
2633 return;
2634 }
2635  
2636 $self->{toc} = ();
2637 foreach my $index (0 .. $self->{filecount} - 1)
2638 {
2639 my %tocentry;
2640 my @list;
2641 $tocentrydata = substr($tocdata,$offset,10);
2642 @list = unpack('a[4]nN',$tocentrydata);
2643  
2644 $tocentry{name} = $list[0];
2645 $tocentry{unknown1} = $list[1];
2646 $tocentry{size} = $list[2];
2647  
2648 debug(3,"DEBUG: found toc entry '",$tocentry{name},
2649 "', type '",$tocentry{type},"' [",$tocentry{size}," bytes]");
2650 push(@{$self->{toc}}, \%tocentry);
2651 $offset += 10;
2652 }
2653  
2654 return 1;
2655 }
2656  
2657  
2658 =head2 C<parse_imp_toc_v2($tocdata)>
2659  
2660 Takes as a single argument a string containing the table of contents
2661 data, and parses it into object attributes following the version 2
2662 format (20 bytes per entry).
2663  
2664 =head3 Format
2665  
2666 =over
2667  
2668 =item * Offset 0x00 [4 bytes, text]
2669  
2670 Resource name. Stored in C<name>. In the case of the 'DATA.FRK' text
2671 resource, this will be four spaces (C<' '>).
2672  
2673 =item * Offset 0x04 [4 bytes, big-endian unsigned long int]
2674  
2675 Unknown, but always zero. Stored in C<unknown1>.
2676  
2677 =item * Offset 0x08 [4 bytes, big-endian unsigned long int]
2678  
2679 Size of the resource data in bytes. Stored in C<size>.
2680  
2681 =item * Offset 0x0C [4 bytes, text]
2682  
2683 Resource type. Stored in C<type>, and used as the key for the stored
2684 resource hash.
2685  
2686 =item * Offset 0x10 [4 bytes, big-endian unsigned long int]
2687  
2688 Unknown, but always either zero or one. Stored in C<unknown2>.
2689  
2690 =back
2691  
2692 =cut
2693  
2694 sub parse_imp_toc_v2 :method
2695 {
2696 my ($self,$tocdata) = @_;
2697 my $subname = (caller(0))[3];
2698 croak($subname . "() called as a procedure!\n") unless(ref $self);
2699 debug(2,"DEBUG[",$subname,"]");
2700  
2701 my $length = length($tocdata);
2702 my $lengthexpected = 20 * $self->{filecount};
2703 my $template;
2704 my $tocentrydata;
2705 my $offset = 0;
2706  
2707 if($self->{version} != 2)
2708 {
2709 carp($subname,"(): attempting to parse a version 2 TOC,",
2710 " but the file appears to be version ",$self->{version},"!\n");
2711 }
2712  
2713 if($length != $lengthexpected)
2714 {
2715 carp($subname,"(): expected ",$lengthexpected," bytes, but received ",
2716 $length," -- aborting!\n");
2717 return;
2718 }
2719  
2720 $self->{toc} = ();
2721 foreach my $index (0 .. $self->{filecount} - 1)
2722 {
2723 my %tocentry;
2724 my @list;
2725 $tocentrydata = substr($tocdata,$offset,20);
2726 @list = unpack('a[4]NNa[4]N',$tocentrydata);
2727  
2728 $tocentry{name} = $list[0];
2729 $tocentry{unknown1} = $list[1];
2730 $tocentry{size} = $list[2];
2731 $tocentry{type} = $list[3];
2732 $tocentry{unknown2} = $list[4];
2733  
2734 debug(3,"DEBUG: found toc entry '",$tocentry{name},
2735 "', type '",$tocentry{type},"' [",$tocentry{size}," bytes,",
2736 " unk1=",$tocentry{unknown1}," unk2=",$tocentry{unknown2},"]");
2737 push(@{$self->{toc}}, \%tocentry);
2738 $offset += 20;
2739 }
2740  
2741 return 1;
2742 }
2743  
2744  
2745 =head2 C<set_book_properties(%args)>
2746  
2747 Sets the specified book properties. Returns 1 on success, or undef if
2748 no properties were specified.
2749  
2750 =head3 Arguments
2751  
2752 =over
2753  
2754 =item * C<identifier>
2755  
2756 The book identifier, as might be provided as an OPF C<< <dc:identifier> >>
2757 element.
2758  
2759 =item * C<category>
2760  
2761 The main book category, as might be provided as an OPF C<< <dc:subject> >>
2762 element.
2763  
2764 =item * C<subcategory>
2765  
2766 The subcategory, generally a set of search arguments for the ETI
2767 website.
2768  
2769 =item * C<title>
2770  
2771 The book title, as might be provided as an OPF C<< <dc:title> >>
2772 element.
2773  
2774 =item * C<lastname>
2775  
2776 The primary author's last name, but see the entry for C<firstname>
2777 before deciding how to handle name storage.
2778  
2779 =item * C<middlename>
2780  
2781 The primary author's middle name, but see the entry for C<firstname>
2782 before deciding how to handle name storage.
2783  
2784 =item * C<firstname>
2785  
2786 The primary author's first name, but this field is also used by a
2787 great many .imp books to store the entire name in "First Last" format.
2788 If this field is to be used this way, C<lastname> and C<middlename>
2789 must be blank.
2790  
2791 =back
2792  
2793 =head3 Example
2794  
2795 $imp->set_book_properties(title => 'My Best Book',
2796 category => 'Fiction',
2797 firstname => 'John Q. Public');
2798  
2799 =cut
2800  
2801 sub set_book_properties :method
2802 {
2803 my ($self,%args) = @_;
2804 my $subname = (caller(0))[3];
2805 croak($subname . "() called as a procedure!\n") unless(ref $self);
2806 debug(2,"DEBUG[",$subname,"]");
2807  
2808 my %valid_args = (
2809 'identifier' => 1,
2810 'category' => 1,
2811 'subcategory' => 1,
2812 'title' => 1,
2813 'lastname' => 1,
2814 'middlename' => 1,
2815 'firstname' => 1,
2816 );
2817 if(!%args)
2818 {
2819 carp($subname,"():\n",
2820 " at least one property must be specified!\n");
2821 return;
2822 }
2823 foreach my $arg (keys %args)
2824 {
2825 croak($subname,"(): invalid argument '",$arg,"'")
2826 if(!$valid_args{$arg});
2827 }
2828  
2829 $self->{identifier} = $args{identifier} if(defined $args{identifier});
2830 $self->{category} = $args{category} if(defined $args{category});
2831 $self->{subcategory} = $args{subcategory} if(defined $args{subcategory});
2832 $self->{title} = $args{title} if(defined $args{title});
2833 $self->{lastname} = $args{lastname} if(defined $args{lastname});
2834 $self->{middlename} = $args{middlename} if(defined $args{middlename});
2835 $self->{firstname} = $args{firstname} if(defined $args{firstname});
2836  
2837 return 1;
2838 }
2839  
2840  
2841 ################################
2842 ########## PROCEDURES ##########
2843 ################################
2844  
2845 =head1 PROCEDURES
2846  
2847 All procedures are exportable, but none are exported by default.
2848  
2849  
2850 =head2 C<detect_resource_type(\$data)>
2851  
2852 Takes as a sole argument a reference to the data component of a
2853 resource. Returns a 4-byte string containing the resource type if
2854 detected successfully, or undef otherwise.
2855  
2856 Detection will not work on the C<DATA.FRK> (C<' '>) resource. That
2857 one must be detected separately by name/type.
2858  
2859 =cut
2860  
2861 sub detect_resource_type
2862 {
2863 my ($dataref) = @_;
2864 my $subname = (caller(0))[3];
2865 debug(3,"DEBUG[",$subname,"]");
2866  
2867 if(!$dataref)
2868 {
2869 carp($subname,"(): no resource data provided!\n");
2870 return;
2871 }
2872 if(ref $dataref ne 'SCALAR')
2873 {
2874 carp($subname,"(): argument is not a scalar reference!\n");
2875 return;
2876 }
2877  
2878 my $id = substr($$dataref,2,4);
2879 if($id =~ m/^[\w! ]{4}$/)
2880 {
2881 return $id;
2882 }
2883 carp($subname,"(): resource not recognized!\n");
2884 return;
2885 }
2886  
2887  
2888 =head2 C<parse_imp_resource_v1()>
2889  
2890 Takes as a sole argument a string containing the data (including the
2891 10-byte header) of a version 1 IMP resource.
2892  
2893 Returns a hashref containing that data separated into the following
2894 keys:
2895  
2896 =over
2897  
2898 =item * C<name>
2899  
2900 The four-letter name of the resource.
2901  
2902 =item * C<type>
2903  
2904 The four-letter type of the resource. This is detected from the data,
2905 and is not part of the v1 header.
2906  
2907 =item * C<unknown1>
2908  
2909 A 16-bit unsigned int of unknown purpose. Expected values are 0 or 1.
2910  
2911 Use with caution. This key may be renamed later if more information
2912 is found.
2913  
2914 =item * C<size>
2915  
2916 The expected size in bytes of the actual resource data. A warning
2917 will be carped if this does not match the actual size of the data
2918 following the header.
2919  
2920 =item * C<data>
2921  
2922 The actual resource data.
2923  
2924 =back
2925  
2926 =cut
2927  
2928 sub parse_imp_resource_v1
2929 {
2930 my ($data) = @_;
2931 my $subname = (caller(0))[3];
2932 debug(3,"DEBUG[",$subname,"]");
2933  
2934 my @list; # Temporary list
2935 my %resource; # Hash containing resource data and metadata
2936 my $size; # Actual size of resource data
2937  
2938 @list = unpack('a[4]nN',$data);
2939 $resource{name} = $list[0];
2940 $resource{unknown1} = $list[1];
2941 $resource{size} = $list[2];
2942 $resource{data} = substr($data,10);
2943 if($resource{name} eq ' ')
2944 {
2945 $resource{type} = ' ';
2946 }
2947 else
2948 {
2949 $resource{type} = detect_resource_type(\$resource{data});
2950 }
2951  
2952 $size = length($resource{data});
2953 if($size != $resource{size})
2954 {
2955 carp($subname,"(): resource '",$resource{name},"' has ",
2956 $size," bytes (expected ",$resource{size},")!\n");
2957 }
2958  
2959 debug(2,"DEBUG: found resource '",$resource{name},
2960 "', type '",$resource{type},"' [",$resource{size}," bytes]");
2961  
2962 return \%resource;
2963 }
2964  
2965  
2966 =head2 C<parse_imp_resource_v2()>
2967  
2968 Takes as a sole argument a string containing the data (including the
2969 20-byte header) of a version 2 IMP resource.
2970  
2971 Returns a hashref containing that data separated into the following
2972 keys:
2973  
2974 =over
2975  
2976 =item * C<name>
2977  
2978 The four-letter name of the resource.
2979  
2980 =item * C<unknown1>
2981  
2982 A 32-bit unsigned int of unknown purpose. Expected values are 0 or 1.
2983  
2984 Use with caution. This key may be renamed later if more information
2985 is found.
2986  
2987 =item * C<size>
2988  
2989 The expected size in bytes of the actual resource data. A warning
2990 will be carped if this does not match the actual size of the data
2991 following the header.
2992  
2993 =item * C<type>
2994  
2995 The four-letter type of the resource.
2996  
2997 =item * C<unknown2>
2998  
2999 A 32-bit unsigned int of unknown purpose. Expected values are 0 or 1.
3000  
3001 Use with caution. This key may be renamed later if more information
3002 is found.
3003  
3004 =item * C<data>
3005  
3006 The actual resource data.
3007  
3008 =back
3009  
3010 =cut
3011  
3012 sub parse_imp_resource_v2
3013 {
3014 my ($data) = @_;
3015 my $subname = (caller(0))[3];
3016 debug(3,"DEBUG[",$subname,"]");
3017  
3018 my @list; # Temporary list
3019 my %resource; # Hash containing resource data and metadata
3020 my $size; # Actual size of resource data
3021  
3022 @list = unpack('a[4]NNa[4]N',$data);
3023 $resource{name} = $list[0];
3024 $resource{unknown1} = $list[1];
3025 $resource{size} = $list[2];
3026 $resource{type} = $list[3];
3027 $resource{unknown2} = $list[4];
3028 $resource{data} = substr($data,20);
3029  
3030 $size = length($resource{data});
3031 if($size != $resource{size})
3032 {
3033 carp($subname,"(): resource '",$resource{name},"' has ",
3034 $size," bytes (expected ",$resource{size},")!\n");
3035 }
3036  
3037 debug(2,"DEBUG: found resource '",$resource{name},
3038 "', type '",$resource{type},"' [",$resource{size}," bytes,",
3039 " unk1=",$resource{unknown1}," unk2=",$resource{unknown2},"]");
3040  
3041 return \%resource;
3042 }
3043  
3044  
3045 ########## END CODE ##########
3046  
3047 =head1 BUGS AND LIMITATIONS
3048  
3049 =over
3050  
3051 =item * Not finished. Do not try to use yet.
3052  
3053 =item * MacPaint PICT images are not well-supported. If present in
3054 the book, they will be saved, but a warning will be carped about
3055 invalid image data.
3056  
3057 =item * Support for v1 files is completely untested and implemented
3058 with some guesswork. Bug reports welcome.
3059  
3060 =back
3061  
3062 =head1 AUTHOR
3063  
3064 Zed Pobre <zed@debian.org>
3065  
3066 =head1 THANKS
3067  
3068 Thanks are due to Nick Rapallo <nrapallo@yahoo.ca> for invaluable
3069 assistance in understanding the .IMP format and testing this code.
3070  
3071 Thanks are also due to Jeffrey Kraus-yao <krausyaoj@ameritech.net> for
3072 his work reverse-engineering the .IMP format to begin with, and the
3073 documentation at L<http://krausyaoj.tripod.com/reb1200.htm>.
3074  
3075 =head1 LICENSE AND COPYRIGHT
3076  
3077 Copyright 2008 Zed Pobre
3078  
3079 Licensed to the public under the terms of the GNU GPL, version 2.
3080  
3081 =cut
3082  
3083 1;
3084 __END__
« Tools/MSReader.pm ↑ Summary Tools/LZSS.pm »