ODF/MailMerge.pm untested

filter: Statementstmt 0.0% 0 / 585 Branchbran 0.0% 0 / 332 Conditioncond 0.0% 0 / 137 MC/DCmcdc 0.0% 0 / 86 Subroutinesub 0.0% 0 / 65 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 1229 CC 194 SCAR 64.6
CC
194
Cov
0%
_rt_replicate
2352.0
_rt_dosubst
870.0
_process_group
600.0
CRAP 642.2
1 #!/usr/bin/env perl License: Public Domain or CC0
2 # See https://creativecommons.org/publicdomain/zero/1.0/
3 # The author, Jim Avera (jim.avera at gmail) has waived all copyright and
4 # related or neighboring rights. Attribution is requested but is not required.
5  
6 use 5.018; # for unicode_strings, lexical_subs
7 use strict; use warnings FATAL => 'all';
8 no warnings "experimental::lexical_subs";
9 use feature qw(state say lexical_subs fc);
10 use feature qw(unicode_strings unicode_eval evalbytes);
11 use feature 'unicode_strings';
12 use utf8;
13  
14 package ODF::MailMerge;
15  
16 # Allow "use <thismodule> <someversion>;" in development sandbox to not bomb
17 # ...but don't let CPAN or test harnes scanners see this as defining $VERSION
18 { no strict 'refs'; ${__PACKAGE__."::VER"."SION"} = 999.999; }
19  
20 our $VERSION = '1.011'; # VERSION from Dist::Zilla::Plugin::OurPkgVersion
21 our $DATE = '2026-01-11'; # DATE from Dist::Zilla::Plugin::OurDate
22  
23 use Carp;
24 our @CARP_NOT = ("ODF::lpOD_Helper", "ODF::lpOD");
25  
26 use Scalar::Util qw/refaddr blessed/;
27 use List::Util qw/first any none all max min sum0/;
28 use List::MoreUtils qw/before after uniq/;
29 use Data::Dumper::Interp 6.004
30 qw/visnew ivis dvis dvisq ivisq vis visq avis avisq addrvis u/;
31 use Spreadsheet::Edit::Log 1000.005 'oops', ':btw' ;
32 use Clone ();
33  
34 use ODF::lpOD;
35 use ODF::lpOD_Helper 6.006 qw/:DEFAULT
36 PARA_FILTER
37 Hr_SUBST
38 Hr_MASK
39 arraytostring hashtostring/;
40  
41 #use constant MM_SUBST => Hr_SUBST;
42 use constant MM_SUBST => 0x42FF;
43  
44 use constant ROW_FILTER => "table:table-row";
45 use constant CELL_FILTER => "table:table-cell";
46 use constant FRAME_FILTER => "draw:frame";
47 use constant SECTION_FILTER => "text:section";
48 use constant TABLE_FILTER => "table:table";
49 use constant ROW_SECTION_FILTER => Hor_cond(ROW_FILTER, SECTION_FILTER);
50 use constant TABLE_SECTIOIN_ROW_FILTER => Hor_cond(ROW_FILTER, FRAME_FILTER, SECTION_FILTER);
51 use constant FRAME_SECTION_FILTER => Hor_cond(FRAME_FILTER, SECTION_FILTER);
52 use constant ROW_PARA_FILTER => Hor_cond(PARA_FILTER, ROW_FILTER);
53 use constant ROW_BODYROOT_FILTER => "table:table-row|office:text";
54 use constant TABLE_SECTION_FRAME_FILTER =>
55 Hor_cond(TABLE_FILTER,SECTION_FILTER,FRAME_FILTER);
56  
57 use Exporter 'import';
58 our @EXPORT = qw/replace_tokens MM_SUBST/;
59 our @EXPORT_OK = qw/odfmm_example_path $token_re parse_token/;
60 our %EXPORT_TAGS = ('all' => [@EXPORT, @EXPORT_OK]);
61  
62 our $debug;
63  
64 use File::ShareDir qw/dist_dir/; # module_dir
65 use Path::Tiny 0.146 qw/path/;
66 sub odfmm_example_path() {
67 my $p = path(__FILE__)->parent->parent->parent->child('share','examples');
68 unless ($p->exists) {
69 $p = path(dist_dir('ODF-MailMerge'))->child('examples');
70 }
71 unless ($p->exists) {
72 die "Can not locate share/examples\ndied";
73 }
74 $p->canonpath
75 }
76  
77 =for Pod::Coverage odfmm_example_path parse_token
78  
79 =cut
80  
81 # Recognize anything probably intended as a {token} expression
82 our $token_re = qr/\{ [\ \t]*+
83 (?<tokname> (?: [^:\{\}\\\s]++ |
84 \\[^\n] |
85 [\ \t]+(?=[^:\{\}\s])
86 )*
87 )
88 [\ \t]*+
89 (?<mods> (?: : (?:[^:\{\}\\]+|\\.)* )* )
90 \}/xs;
91  
92 sub parse_token($) {
93 my $t = shift;
94 $t =~ /^${token_re}$/ or oops dvis '$t';
95 my ($tokname, $mods) = ($+{tokname}, $+{mods});
96  
97 #$tokname =~ s/^[ \t]*//; $tokname =~ s/[ \t]*$//;
98 $tokname =~ s/\\(.)/$1/sg; # un-escape
99  
100 croak "Invalid token ",vis($t)," -- token NAME may not contain tab or newline"
101 if $tokname =~ /[\t\n]/;
102  
103 # Split :mod1:mod2:... discarding the initial :s
104 my @mods;
105 while ($mods =~ /\G:((?:[^:\\]+|\\.)*)/gsc) {
106 croak ivis "Extraneous ':' in \$t (mods=\$mods)"
107 if $1 eq ""; # empty tokname
108 push @mods, $1;
109 }
110 oops vis(pos($mods)) unless !defined(pos($mods)) || pos($mods)==length($mods);
111  
112 my (@std_mods, @custom_mods);
113 foreach (@mods) {
114 s/\\(.)/$1/sg; # un-escape
115 if ((my $equal_ix = index($_,'=')) >= 0) {
116 croak "Invalid token ",vis($t),
117 " -- newline or tab is allowed only in :modifier after '='"
118 if substr($_,0,$equal_ix) =~ /[\t\n]/;
119 }
120 btw visq($_) if $debug;
121 if (/^(?: nb|unfold|breakmulti
122 |die|del(?:empty|row|para|=.*)
123 |rep(?:_first|_notfirst|_mid|_last|=.*)
124 |rmsb # remove shared border between replicates
125 |span[rd]
126 |reptag=.*
127 )$/xs) {
128 push @std_mods, $_;
129 } else {
130 push @custom_mods, $_;
131 }
132 }
133 return ($tokname, \@std_mods, \@custom_mods);
134 }
135 sub _to_content_list(_) {
136 my $val = shift;
137 # Convert hash value which is a single value or [content spac]
138 # to a [list of [content spec]s].
139 #
140 # A [content spec] is a list of "text strings" and [style descriptor]
141 # sub-arrays which apply to the immediately-following text string
142 # (see ODF::lpOD_Helper for details).
143 #
144 if (ref $val) {
145 croak ivis 'Value contains an illegal ref type (not ARRAY): $val'
146 if any{ref($_) && ref($_) ne "ARRAY"} $val, eval{@$val};
147  
148 if (none{ref} @$val) {
149 # [all...non-refs] must be ["str"] or ["str1", "str2"]
150 $val = [ map{ [$_] } @$val ]; # --> [ ["str1"], ["str2] ]
151 }
152 elsif (all{ref} @$val) {
153 # [ [...], [...], [...] ]
154 # Must be list of [content subarrays] -- OK AS IS
155 croak ivisq 'Invalid replacement value $val'
156 unless all{ any{!ref} @$_ } @$val; # [content] must incl a "str"
157 }
158 else { # [ mixed refs and "strings" ] -- must be a single [content] spec
159 croak ivisq 'Invalid [content spec] replacement value $val'
160 if any{ ref && any{ref} @$_ } @$val;
161 $val = [ $val ];
162 }
163 }
164 elsif (defined $val) {
165 $val = [ [$val] ]; # "single string" --> [ ["string"] ]
166 }
167 $val
168 }
169  
170 sub _para_to_rop($) {
171 my $elt = shift // oops;
172 # If $elt is encapsulated in a frame *within a table cell*, then
173 # the frame is replicated. This permits run-together replicates
174 # if the frams are anchored "as character", for example to make
175 # comma-separated lists.
176 # TODO: Also replicated sections??
177 #
178 # Otherwise, if $elt is in a table row (in the same section or frame,
179 # if applicable) then that row is replicated.
180 #
181 # If none of the above, then the containing paragraph is replicated.
182 #
183 if (my $frame = $elt->Hself_or_parent(FRAME_FILTER, CELL_FILTER)) {
184 if ($frame->Hself_or_parent(CELL_FILTER, FRAME_SECTION_FILTER)) {
185 return wantarray ? ($frame, "frame") : $frame
186 }
187 }
188 if (my $row = $elt->Hself_or_parent(ROW_FILTER, FRAME_SECTION_FILTER)) {
189 return wantarray ? ($row, "row") : $row
190 }
191 my $para = $elt->Hself_or_parent(PARA_FILTER, SECTION_FILTER) // oops;
192 return wantarray ? ($para, "paragraph") : $para
193 }
194 sub _mk_tokhash_key($$) {
195 my ($rop, $tokname) = @_;
196 oops unless defined $tokname;
197 refaddr($rop)."/$tokname";
198 }
199 sub _fmt_tokhash($) {
200 my $tokhash = shift;
201 visnew->Sortkeys(sub{
202 my $h = shift;
203 [ sort{ ref($h->{$a}) eq "HASH"
204 ? (($h->{$a}->{tokname}//$a) cmp ($h->{$b}->{tokname}//$b))
205 : ($a cmp $b)
206 } keys %$h ]
207 })->dvis('%$tokhash')
208 }
209  
210 # This encapsulates the common token processing in both dryrun and substitution
211 # passes. Usually replacement values are saved by the first pass and so
212 # this is not called on the 2nd pass, but in some cases (multiple instances
213 # of the same tokname in a single paragraph) the 2nd pass has to re-process
214 # a token from scratch.
215 #
216 # Returns () if the token should not be replaced, otherwise $content_list
217 # ($content_list is a (ref to) array of [content] specs)
218 sub _get_content_list($$$$) {
219 my ($m, $tokname, $users_hash, $custom_mods) = @_;
220 my $val = $users_hash->{$tokname} // $users_hash->{'*'};
221 return undef
222 unless defined($val);
223 my $token = $m->{match};
224 if (ref($val) eq "CODE") {
225 my $para = $m->{para};
226 (my $op, $val) = $val->($tokname, $token, $para, $custom_mods);
227 croak("Callback returned an invalid opcode: ",u($op))
228 if !defined($op) or $op != MM_SUBST && $op != 0;
229 croak("callback returned MM_SUBST without a value or vice-versa: $token")
230 if !defined($val) ^ !($op & MM_SUBST);
231 return ()
232 unless defined($val);
233 } else {
234 croak "Invalid modifer ",visq(":$_")," in token $token",
235 "\n(A callback is required to use custom modifiers)\n"
236 for @$custom_mods;
237 }
238 croak ivisq 'Value for token $token is []'
239 if ref($val) eq 'ARRAY' && @$val==0;
240 my $content_list = _to_content_list($val);
241 $content_list
242 }
243  
244 sub _get_replicate_opts($) {
245 my $std_mods = shift;
246 my ($cond_expr, $rmsb, $spandown, $spanright);
247 foreach (@$std_mods) {
248 my $cexpr;
249 if (/^rep/) {
250 if (/^rep_first$/) { $cexpr = '$i==0 && $N > 1' }
251 elsif (/^rep_notfirst$/) { $cexpr = '$i>0' }
252 elsif (/^rep_mid$/ ) { $cexpr = '$i>0 && $i<$N' }
253 elsif (/^rep_even_mid$/) { $cexpr = '$i>0 && $i<$N && int($i%2)==0' }
254 elsif (/^rep_odd_mid$/) { $cexpr = '$i>0 && $i<$N && int($i%2)==1' }
255 elsif (/^rep_last$/ ) { $cexpr = '$i==$N-1 && $N > 1' }
256 elsif (/^rep_even_last$/) { $cexpr = '$i==$N-1 && int($i%2)==0 && $N > 1' }
257 elsif (/^rep_odd_last$/) { $cexpr = '$i==$N-1 && int($i%2)==1 && $N > 1' }
258 elsif (/^rep_only$/) { $cexpr = '$N==1' }
259 elsif (/^rep=(.*)$/ ) {
260 croak "Unsafe/disallowed expression ",visq($1)," in ",visq($_)
261 if do{ local $_ = $1;
262 /[\@:\\]|\$(?![iN]\b)/a
263 or grep{ !/(?:int|i|N|[0-9]+)$/ } /(\w+)/g };
264 $cexpr = $1;
265 }
266 else { oops } #out of sync changes to std_mod definitions?
267 if (defined $cexpr) {
268 croak "Multiple instantiation conditions not allowed in ",
269 visq(join ":", @$std_mods)
270 if defined($cond_expr);
271 $cond_expr = $cexpr;
272 }
273 }
274 elsif ($_ eq "rmsb") { $rmsb = 1 }
275 elsif ($_ eq "spand") { $spandown = 1 }
276 elsif ($_ eq "spanr") { $spanright = 1 }
277 }
278 return ($cond_expr, $rmsb, $spandown, $spanright)
279 }
280  
281 sub _rt_dryrun($$$) {
282 my ($context, $users_hash, $tokhash) = @_;
283  
284 btw dvis 'dryrun $context = ',fmt_tree_brief($context) if $debug;
285 for my $m ( $context->Hsearch($token_re, multi => TRUE) ) {
286 my $token = $m->{match};
287 btw dvis '_rt_dryrun $token' if $debug;
288 my ($tokname, $std_mods, $custom_mods) = parse_token($token);
289 my $content_list
290 = _get_content_list($m, $tokname, $users_hash, $custom_mods);
291 next
292 unless defined $content_list;
293 my ($cond_expr, $rmsb, $spand, $spanr) = _get_replicate_opts($std_mods);
294 my ($rop, $rop_name) = _para_to_rop($m->{para});
295 my $tokhash_key = _mk_tokhash_key($rop, $tokname);
296 if (exists $tokhash->{$tokhash_key}) {
297 croak "The same token name may not appear multiple times in the same\n",
298 "$rop_name if the token has multiple values and/or when\n",
299 "conditional instantiation is used:\n$token\n"
300 if @$content_list > 1 or defined $cond_expr;
301 next; # 2nd instance will be parsed again in the substitution pass
302 }
303 $tokhash->{$tokhash_key} = {
304 rop => $rop,
305 tokname => $tokname,
306 content_list => $content_list,
307 token => $token, # just for debugging?
308 (defined($cond_expr) ? (cond_expr => $cond_expr) : ()),
309 ($rmsb ? (rmsb => 1) : ()),
310 ($spand ? (spandown => 1) : ()),
311 ($spanr ? (spanright => 1) : ()),
312 };
313 }#foreach token in context
314 }# _rt_dryrun
315  
316 sub _content_is_empty($) {
317 my $content = shift;
318 none { !ref && length } @$content
319 }
320  
321 sub _rm_cell_border($$$) {
322 my ($doc, $cell, $propname) = @_;
323 my $stn = $cell->get_attributes->{"table:style-name"} // oops;
324 my $st = $doc->get_style('table-cell', $stn) // oops;
325 my $props = $st->get_properties();
326 if (my $v = $props->{$propname}) {
327 return if $v eq "none";
328 }
329 elsif ($v = $props->{"fo:border"}) {
330 oops if $props->{$propname};
331 $props->{"fo:border-top"} = $props->{"fo:border-left"}
332 = $props->{"fo:border-right"} = $props->{"fo:border-bottom"}
333 = delete($props->{"fo:border"});
334 }
335 else { oops $cell->Hget_text(), " -- cell has neither fo:border or $propname"; }
336 $props->{$propname} = "none";
337 my $new_st = $doc->Hautomatic_style("table-cell", %$props);
338 $cell->set_attributes("table:style-name", $new_st->get_name);
339 }
340 sub _do_rm_border($$$) {
341 my ($doc, $para, $propname) = @_;
342 _rm_cell_border($doc, $para->get_parent_cell//oops, $propname);
343 }
344 sub _do_rmtb($$) { &_do_rm_border(@_, "fo:border-top" ) }
345 sub _do_rmbb($$) { &_do_rm_border(@_, "fo:border-bottom") }
346  
347 sub _num_empty_atorbelow($$$$) {
348 my ($table, $rx, $numrows, $cx) = @_;
349 my $num_empty = 0;
350 while ($rx + $num_empty < $numrows) {
351 my $row = $table->get_row($rx+$num_empty);
352 my $this_cell = $row->get_cell($cx);
353 if ($this_cell->Hget_text() ne "") {
354 last
355 }
356 $num_empty++;
357 }
358 $num_empty;
359 }
360 sub _do_span($@) {
361 my ($spanning_cell, $spandirs) = @_;
362 # This is called after substitutions. Span the cell over
363 # cells which are now empty (paying no attention to replicate groups!)
364 my $tag = $spanning_cell->tag;
365 if ($tag eq 'table:covered-table-cell') {
366 # This cell has already been spaneed-over. So skip it.
367 return;
368 }
369 oops unless $tag eq "table:table-cell" && $spanning_cell->first_child;
370 my $table = $spanning_cell->get_parent_table;
371 my ($numrows, $numcols) = $table->get_size;
372 my (undef, $rx, $cx) = $spanning_cell->get_position;
373 # Don't confuse 'rspan' (rows spanned) here with ':spanr' (span-right :mod)
374 my ($rspan, $cspan) = $spanning_cell->get_span;
375 oops if $rspan != 1 || $cspan != 1; #not handled
376 my $new_rspan = $rspan;
377 my $new_cspan = $cspan;
378 if ($spandirs->{down} && $rx < $numrows-1) {
379 # r0:before r1:before r2:$cell r3:"" c4:"" r5:NotEmpty (numrows==6)
380 # nrspan==1 =2 =3 (=4)
381 $new_rspan = 1 + _num_empty_atorbelow($table, $rx+1, $numrows, $cx);
382 }
383 if ($spandirs->{right} && $cx < $numcols-1) {
384 for (my $this_cx = $cx+1; $this_cx < $numcols; $this_cx++) {
385 my $vempty = _num_empty_atorbelow($table, $rx, $numrows, $this_cx);
386 # If also vertically spanning, horiz. spanning can only be done
387 # if the spanned columns are empty in all vertically-spanned rows,
388 # i.e. no non-empty cell will be covered.
389 last if $vempty < $new_rspan; # vempty >= 1 to cover 1st row etc.
390 $new_cspan++;
391 }
392 }
393 # Entirely delete paragraphs (and nested tables or sections...)
394 # from cells to be covered; otherwise the content seems to end up in the
395 # spanning cell (contrary to what ODF::lpOD docs imply about covered cells).
396 for my $this_rx ($rx .. $rx+$new_rspan-1) {
397 my $row = $table->get_row($this_rx);
398 for my $this_cx ($cx .. $cx+$new_cspan-1) {
399 next if $this_rx==$rx && $this_cx==$cx; # the surviving (spanning) cell
400 my $cell = $row->get_cell($this_cx);
401 btw dvis 'DELETING CONTENT OF $cell $this_rx $this_cx ($numcols $numrows $new_rspan $new_cspan): ',
402 visq($cell->Hget_text) if $debug;
403 foreach ($cell->children) {
404 btw " (deleting $_)" if $debug;
405 $_->delete;
406 }
407 }
408 }
409  
410 if ($new_rspan != $rspan or $new_cspan != $cspan) {
411 oops if $new_rspan <= 0 or $new_cspan <= 0;
412 $spanning_cell->set_span(rows => $new_rspan, columns => $new_cspan);
413 }
414 }
415  
416 sub _rt_dosubst($$$$$) { # returns Hreplace result list
417 my ($context, $users_hash, $tokhash, $to_deletes, $spans_todo) = @_;
418 my $doc = $context->document();
419 $context->Hreplace($token_re, sub {
420 my $m = shift;
421 my $token = $m->{match};
422 ##btw "==============================================\n",
423 ## dvis 'Hreplace cb TOP $token\ncontext=',fmt_tree($context, wi=>3),
424 ## "\n===(TOP $token)===============================\n" if $debug;
425 my ($tokname, $std_mods, $custom_mods) = parse_token($token);
426 my ($rop, $rop_name) = _para_to_rop($m->{para});
427 my $tokhash_key = _mk_tokhash_key($rop, $tokname);
428  
429 my $content_list;
430 my $info = $tokhash->{$tokhash_key};
431 if ($info) {
432 $content_list = $info->{content_list} // oops;
433 btw dvis 'XX retrieved $tokhash_key -> $info $content_list' if $debug;
434 oops dvis '$m\n$info\n' if @$content_list > 1;
435 _do_rmtb($doc, $m->{para}) if $info->{rmtb};
436 _do_rmbb($doc, $m->{para}) if $info->{rmbb};
437 } else {
438 # A token is not in %tokhash if it is the 2nd instance of the same
439 # token in a rop (in which case multi-values are not allowed).
440 $content_list
441 = _get_content_list($m, $tokname, $users_hash, $custom_mods);
442 btw dvis 'YY *no* info, $rop $tokname $token$token $users_hash $content_list' if $debug;
443 return(0)
444 unless defined $content_list;
445 croak dvisq 'An unhandled situation arose with token $token\n',
446 "Either there is a table row containing both tokens in frames and non-framed\n",
447 "tokens, or some other situation which is not supported.\n",
448 "If using frames, all tokens in a table row should be encapsulated.\n"
449 if @$content_list > 1;
450 }
451  
452 my $content = $content_list->[0];
453 foreach (@$std_mods) {
454 if ($_ eq "nb") {
455 foreach (@$content) {
456 next if ref;
457 s/ /\N{NO-BREAK SPACE}/sg;
458 }
459 }
460 elsif ($_ eq "unfold") {
461 foreach (@$content) {
462 next if ref;
463 s/\n/ /sg;
464 }
465 }
466 elsif ($_ eq "breakmulti") {
467 my $text = join("", grep{! ref} @$content);
468 if ($text =~ /\n./s) {
469 croak "Mal-formed [content] (does not end with plain string)"
470 if ref($$content[-1]);
471 $$content[-1] .= "\n";
472 }
473 }
474 elsif ($_ eq "rmsb") { } # handled in 1st pass, set {rmtb/rmbb} in $info
475 elsif (/^span[dr]$/) {
476 my $down_or_right = $_ eq 'spand' ? "down" : "right";
477 # If the rop is in a replicate group (possibly by itself), then
478 # $info->{spandown} is set in the first replicate only.
479 # Otherwise this is an odd case (2nd token in same paragraph)
480 # where there is no $info
481 if (!$info || $info->{spandown} || $info->{spanright}) {
482 # Do *not* look outside a Frame wrapper within in a cell
483 if (my $cell = $m->{para}->Hparent(CELL_FILTER, FRAME_FILTER)) {
484 my $rop = $cell->parent(ROW_FILTER);
485 # Record the rop so we can later check that it wasn't deleted
486 # before fiddling with the cell. N.B. Both :spand and :spanr
487 # may be present in the cell, not necessarily in the same {token}
488 # (although that makes no difference).
489 my $aref = $spans_todo->{refaddr $cell} //= [$rop, $cell, {}];
490 $aref->[2]->{$down_or_right} = 1;
491 }
492 }
493 }
494 elsif (/^rep/) { } # handled in 1st pass
495 elsif ($_ eq "die" || /^del/) {
496 my $elt =
497 $_ eq "die" ? $rop :
498 $_ eq "delempty" ? $rop : # semi-deprecated
499 $_ eq "delrow" ? $m->{para}->Hself_or_parent(ROW_FILTER) :
500 $_ eq "delpara" ? $m->{para}->Hself_or_parent(PARA_FILTER) :
501 /^del=(.+)$/ ? $m->{para}->Hself_or_parent($1) :
502 oops;
503 if (_content_is_empty($content)) {
504 $to_deletes->{refaddr $elt} //= [1, $elt];
505 } else {
506 # Non-empty content in this token; suppress deletion
507 # even if another token with :del* is empty
508 $to_deletes->{refaddr $elt} = [0, $elt];
509 }
510 }
511 else { oops dvis '$_ $std_mods $m' }
512 }
513  
514 ##btw "==============================================\n",
515 ## dvis 'Hreplace cb BOTTOM $token returning $content\ncontext=',fmt_tree($context, wi=>3),
516 ## "\n===(BOTTOM $token)===============================\n" if $debug;
517  
518 return (Hr_SUBST, $content);
519 }, debug => $debug);
520 }#_rt_dosubst
521  
522 sub _rt_replicate($$) {
523 my ($subtree_root, $tokhash) = @_;
524 # Find groups of adjacent rops containing alternative templates to
525 # instantiate (possibly-)multi-value tokens. Replace the group by
526 # one or more rops, sufficient for the maximal number of values of
527 # any token they contain ("" will be supplied for 'missing' values
528 # of tokens with fewer values than the maximal token in a rop).
529 #
530 # These groups may be:
531 # 1. A lone regular rop (no conditionals)
532 #
533 # 2. A regular rop followed by conditionals (does not include
534 # any *following* regular rop, which if present starts a new group).
535 #
536 # 3. A set of conditional rops not preceded by a regular rop
537  
538 # Build hash of all rops containg any tokens (that are being replaced)
539 my %rophash; # [rop, cond_expr, tokinfo_list, maxN]
540 foreach my $info (values %$tokhash) {
541 # info->{rop tokname cond_expr content_list token}
542 my $rop = $info->{rop};
543 my $ropinfo = $rophash{refaddr $rop}
544 //= {rop => $rop, tokinfos => [], maxN => 0};
545 if (defined(my $tok_cexpr = $info->{cond_expr})) {
546 if (defined(my $rop_cexpr = $ropinfo->{cond_expr})) {
547 croak "Conflicting conditionals in the same row:",
548 visq($tok_cexpr)," for {",$info->{tokname},"} vs. ",
549 visq($rop_cexpr)," for another token in ",refaddr($rop)
550 if $rop_cexpr ne $tok_cexpr;
551 } else {
552 $ropinfo->{cond_expr} = $tok_cexpr;
553 }
554 btw dvis 'C3 $tok_cexpr $info\n $ropinfo' if $debug;
555 }
556 push @{ $ropinfo->{tokinfos} }, $info;
557 $ropinfo->{maxN} = max($ropinfo->{maxN}, scalar(@{$info->{content_list}}));
558 }
559 btw dvis 'RRR1 completed %rophash' if $debug;
560  
561 my sub _process_group(@) {
562 my @group = @_;
563 my $first_rop = $group[0];
564 my $first_ropinfo = $rophash{refaddr $first_rop};
565  
566 # If the first is unconditional, give it an always-true condition
567 # but move it to the end of the search order so it will be used only
568 # if none of the conditional rops work
569 if (!defined $first_ropinfo->{cond_expr}) {
570 foreach my $tokinfo (@{ $first_ropinfo->{tokinfos} }) {
571 oops dvis '$first_rop $first_ropinfo $tokhash' if defined $tokinfo->{cond_expr};
572 }
573 $first_ropinfo->{cond_expr} = "1";
574 push @group, (shift @group) ;
575 }
576  
577 # To keep this logic simple, the appropriate template is always cloned
578 # and the copy inserted before $first_rop; at the end all templates
579 # are deleted, leaving only the clones behind.
580 my $N = $rophash{refaddr $first_rop}->{maxN};
581 btw dvis 'GGG $N @group' if $debug;
582 my $rop0;
583 for (my $i=0; $i < $N; $i++) {
584 my $templ;
585 foreach (@group) {
586 ($templ = $_), last # string eval using $i & $N
587 if eval $rophash{refaddr $_}->{cond_expr} // oops dvis '$@ $_ %rophash';
588 }
589 if (! $templ) {
590 my (undef, $rop_name) = _para_to_rop($group[0]);
591 croak "No conditionally-instantiatable $rop_name matches \$i=$i \$N=$N\n",
592 "The tokens in the group of adjacent items are:\n ",
593 join("\n ",
594 map{
595 map{ sprintf("%-25s --> %s", $_->{token},
596 ($_->{cond_expr}||"(not conditional)")) }
597 @{ $rophash{refaddr $_}->{tokinfos} }
598 } @group
599 ), "\nsubtree_root:",fmt_tree_brief($subtree_root),"\n"
600 }
601 my $new_rop;
602 if ($N == 1) {
603 # Don't clone, this template will not be used more than once
604 btw ivis 'GGG-Using $templ DIRECTLY; text=', $templ->Hget_text(),"\n" if $debug;
605 @group = grep{$_ != $templ} @group;
606 }
607 elsif ($templ == $subtree_root) {
608 # Replication not possible when top context is the (one and only) rop
609 unless ($N == 1) {
610 my $info = $rophash{refaddr $templ}{tokinfos}[0];
611 my (undef, $rop_name) = _para_to_rop($templ);
612 croak "Replication to handle the $N-value token ", $info->{token},
613 " is not possible\n",
614 "because it is in a $rop_name which *is* the top context\n"
615 }
616 } else {
617 $new_rop = $templ->clone;
618 if ($templ->tag eq "draw:frame") {
619 my $orig_name = $templ->att("draw:name") // oops;
620 $new_rop->set_att("draw:name" => $orig_name."_odMM$i");
621 }
622 $first_rop->insert_element($new_rop, position => PREV_SIBLING);
623 btw ivis 'GGG-Insert $new_rop (cloned from $templ) as PREV_SIB of $first_rop ', visq($new_rop->Hget_text()) if $debug;
624 }
625 foreach my $tokinfo (@{ $rophash{refaddr $templ}->{tokinfos} }) {
626 my $tokname = $tokinfo->{tokname} // oops;
627 my $info = $tokhash->{ _mk_tokhash_key($templ, $tokname) } // oops;
628 if ($new_rop) {
629 # clone the info data (for each tokname) to go with $new_rop
630 my $new_key = _mk_tokhash_key($new_rop, $tokname);
631 oops if exists $tokhash->{$new_key};
632 my $new_info = $tokhash->{$new_key} = {
633 # Supply "" for tokens with fewer values than the max in the rop
634 content_list => [ $info->{content_list}->[$i] // [""] ],
635 #rop => $new_rop,
636 #cond_expr => $info->{cond_expr}, # just for debugging??
637 };
638 foreach (qw/tokname token rmsb spandown spanright/) {
639 $new_info->{$_} = $info->{$_} if exists $info->{$_};
640 }
641 $info = $new_info;
642 btw dvis 'G G-1 $i $N Created $new_key $tokhash->{$new_key}\n $info' if $debug;
643 }
644 # Else: $new_rop is undef if the template itself is being used
645 $rop0 //= ($new_rop // $templ);
646 if (delete $info->{rmsb}) {
647 if ($N > 1) {
648 $info->{rmbb} = 1 if $i < $N-1; # remove bottom border
649 $info->{rmtb} = 1 if $i > 0; # remove top border
650 }
651 }
652 delete $info->{spandown} if $i > 0;
653 }
654 btw dvis 'G G-2 $i $new_rop' if $debug;
655 }# foreach $i
656 foreach my $rop (@group) {
657 btw ivis 'G G-Delete unused $rop' if $debug;
658 $rop->delete;
659 ### FOR DEBUG (not necessary)
660 foreach my $tokname(map{$_->{tokname}}
661 @{ $rophash{refaddr $rop}{tokinfos} }) {
662 my $key = _mk_tokhash_key($rop, $tokname);
663 btw dvis 'Deleting OBSOLETE tokhash $key ...' if $debug;
664 delete $tokhash->{$key};
665 }
666 }
667 }#_process_group()
668  
669 # Find groups of alternative conditional rops and expand/collapse each one
670 my %seen;
671 foreach my $ropaddr (keys %rophash) {
672 next if $seen{$ropaddr}++;
673 my $ropinfo = $rophash{$ropaddr};
674 my $rop = $ropinfo->{rop};
675  
676 my @group = ($rop);
677 btw dvis 'FFF1 $rop %$ropinfo' if $debug;
678 if ($ropinfo->{cond_expr}) {
679 # Search preceding adjacents to find the first in the group
680 my $elt = $rop;
681 while ($elt = $elt->prev_sibling) {
682 my $addr = refaddr $elt;
683 my $ropinfoP = $rophash{$addr};
684 unless (defined $ropinfoP) {
685 btw dvis 'FFF--Reject prev sib $elt -- not in rophash' if $debug;
686 last
687 }
688 if ($seen{$addr}++) {
689 btw dvis 'FFF--Reject prev sib $elt -- already seen' if $debug;
690 last
691 }
692 push @group, $elt; # accept this
693 if (! defined $ropinfoP->{cond_expr}) {
694 btw dvis 'FFF--Accept prev sib $elt ; NOT CONDITIONAL' if $debug;
695 last # stop *on* a non-conditional
696 }
697 btw dvis 'FFF--Accept prev sib $elt ($ropinfoP->{cond_expr})' if $debug;
698 }
699 }
700 @group = reverse @group; # move first rop to group[0]
701 # Search following adjacents to find the last in the group
702 my $elt = $rop;
703 while ($elt = $elt->next_sibling) {
704 my $addr = refaddr $elt;
705 my $ropinfoN = $rophash{$addr};
706 unless (defined $ropinfoN) {
707 btw dvis 'FFF++Reject next sib $elt -- not in rophash' if $debug;
708 last
709 }
710 if (! defined $ropinfoN->{cond_expr}) {
711 btw dvis 'FFF++Reject next sib $elt -- not conditional' if $debug;
712 last # stop *on* a non-conditional
713 }
714 if ($seen{$addr}++) {
715 btw dvis 'FFF++Reject next sib $elt -- already seen' if $debug;
716 last
717 }
718 btw dvis 'FFF++Accept next sib $elt ($ropinfoN->{cond_expr})' if $debug;
719 push @group, $elt;
720 }
721 # N.B. An isolated non-conditional rop is its own "group",
722 # which will be replicated if it contains multi-valued tokens
723  
724 _process_group(@group);
725 }
726 foreach my $ropaddr (keys %rophash) {
727 oops dvis 'missed $ropaddr' unless $seen{$ropaddr};
728 btw dvis 'seen: $ropaddr' if $debug;
729 }
730 }#rt_replicate
731  
732 sub replace_tokens($$@) {
733 my ($context, $hash, %opts) = @_;
734 local $debug = $debug || $opts{debug};
735 oops unless blessed($context);
736  
737 unless (caller eq 'ODF::MailMerge::Engine' or !$context->{parent}) {
738 $context->document->Hclean_for_cloning(debug => $opts{debug});
739 }
740  
741 # 1. Do a "dry-run" (search-only) pass to locate all tokens
742 # and save information about them in %tokhash including
743 # values and std_modifiers.
744 # Conditional-instantiation :modifiers (only) are evaluated
745 # and the resulting cond_expr, if any, saved.
746 my %tokhash;
747  
748 _rt_dryrun($context, $hash, \%tokhash);
749 btw 'AFTER DRY-RUN: ',_fmt_tokhash(\%tokhash) if $debug;
750  
751 # 2. Scan %tokhash to identify template groups (either a lone regular
752 # rop which contains multi-value tokens, or adjacent rops containing
753 # tokens bearing instantiation conditions pluse possibly one regular rop).
754 #
755 # Replicate/reduce as needed, leaving exactly one rop for each value
756 # of all multi-value tokens in the rop (defaulting to "" if one token
757 # has fewer values than another). Adjusts %tokhash entries to match.
758 #
759 # Replace the list of all values with the one specific value in
760 # the %tokhash entry
761 _rt_replicate($context, \%tokhash);
762 btw 'AFTER REPLICATE: ',_fmt_tokhash(\%tokhash),
763 "\n context=", fmt_tree($context, wi => 2) if $debug;
764  
765 # 3. Do Hreplace. In the callback:
766 # If rop is not in %tokinfo:
767 # (Re)parse the token
768 # else
769 # Fetch saved values & std_modifiers
770 # (croak if multiple values at this point)
771 #
772 # Apply std_mods to the value
773 # return (MM_SUBST, [content])
774 my (%to_deletes, %spans_todo);
775 my @rr = _rt_dosubst($context, $hash, \%tokhash, \%to_deletes, \%spans_todo);
776 btw "AFTER SUBSTITUTIONS: context=", fmt_tree($context, wi => 2) if $debug;
777  
778 # 4. Delete rops which contained token(s) with :del* modifiers where
779 # all such tokens were replaced by emptyness ("")
780 foreach (values %to_deletes) {
781 my ($to_delete, $elt) = @$_;
782 if ($to_delete) {
783 btw ivis 'DELETING due to :del* : $elt ',vis($elt->Hget_text) if $debug;
784 $elt->delete;
785 # leave %to_deletes entry for span check below
786 } else {
787 btw ivis 'KEEPING $elt because some tokens are not empty' if $debug;
788 delete $to_deletes{$_};
789 }
790 }
791  
792 # 5. Span cells containing tokens with :spand if cells below are empty
793 foreach (values %spans_todo) {
794 my ($rop, $cell, $spandirs) = @$_;
795 next if exists $to_deletes{$rop}; # was deleted above
796 _do_span($cell, $spandirs);
797 }
798 # ??? should replace count be reduced by the number of tokens in
799 # objects removed via $to_delete ???
800 return scalar(@rr)
801 }
802  
803 package ODF::MailMerge::Engine;
804  
805 use constant TABLE_SECTION_FRAME_FILTER => ODF::MailMerge::TABLE_SECTION_FRAME_FILTER;
806 use constant TABLE_FILTER => ODF::MailMerge::TABLE_FILTER;
807 use constant MM_SUBST => ODF::MailMerge::MM_SUBST;
808  
809 use ODF::lpOD;
810 use ODF::lpOD_Helper;
811 use Data::Dumper::Interp;
812 use Spreadsheet::Edit::Log 1000.005 'oops', ':btw' ;
813 use Carp;
814 our @CARP_NOT = ("ODF::MailMerge", "ODF::lpOD_Helper", "ODF::lpOD");
815  
816 sub new {
817 my $class = shift;
818 my %opts = @_;
819  
820 my $proto_elt = delete($opts{proto_elt});
821 if ($proto_elt) {
822 croak "proto_elt must be an element ref, not ",vis($proto_elt)
823 unless ref $proto_elt;
824 } else {
825 my $proto_tag = delete($opts{proto_tag})
826 // croak "Neither proto_tag or proto_elt was specified";
827 my $context = delete($opts{context}) // croak "Missing context";
828 (my @r = $context->Hreplace($proto_tag, [""], %opts))
829 || croak ivis 'proto_tag $proto_tag not found';
830 $proto_elt = $r[0]->{para}->parent(TABLE_SECTION_FRAME_FILTER)
831 // croak ivis 'proto_tag $proto_tag is not located in a proto container';
832 }
833 foreach (keys %opts) {
834 next if /^debug$/;
835 croak "Unhandled option ",vis($_);
836 }
837  
838 unless ($proto_elt->passes(TABLE_FILTER)) {
839 my $tag = u( eval{ $proto_elt->tag } );
840 croak ivis 'Tables are the only supported prototype element (not $tag)'
841 }
842 my $doc = $proto_elt->document;
843 $doc->Hclean_for_cloning(debug => $opts{debug});
844  
845 bless {
846 proto_table => $proto_elt,
847 doc => $doc,
848 #prev => undef,
849 },$class
850 }
851  
852 my $__FILE__ = __FILE__;
853 my $__PACKAGE__ = __PACKAGE__;
854  
855 sub add_record {
856 my ($self, $hash, %opts) = @_;
857 local $debug = $debug || $opts{debug};
858  
859 my $proto_table = $self->{proto_table};
860  
861 # # NO. First of all, removing bottom borders leaves border-less entries at
862 # # the bottom of pages before page breaks. Also spanned cells show the
863 # # border of the spanning cell, so the (now commented-out) code would need
864 # # to remove the spanning cell's border in columns which ended with a span.
865 # #
866 # # See https://bugs.documentfoundation.org/show_bug.cgi?id=157127
867 # # The best advice currently is to use very-thin borders (or none at all) to
868 # # minimize the uglyness of doubled borders.
869 # #
870 # if (my $prev_table = $self->{prev}) {
871 # my ($numrows, $numcols) = $prev_table->get_size;
872 # my $lastrow = $prev_table->get_row($numrows-1);
873 # for my $cx (0..$numcols-1) {
874 # my $cell = $lastrow->get_cell($cx);
875 # ODF::MailMerge::_rm_cell_border($self->{doc}, $cell, "fo:border-bottom");
876 # }
877 # }
878  
879 my $table = $proto_table->clone;
880 $table->set_name($proto_table->Hgen_table_name());
881 $proto_table->insert_element($table, position => PREV_SIBLING);
882 #$self->{prev} = $table;
883  
884 # Ordinarily replace_tokens() simply ignores {token}s which are
885 # not being replaced. However during Mail Merge every token should
886 # have some value. This wrapper callback enforces that.
887 my sub wrapper_cb {
888 my ($tokname, $token, $para, $custom_mods) = @_;
889 my $return_op = MM_SUBST;
890 my $key = exists($hash->{$tokname}) ? $tokname :
891 exists($hash->{'*'}) ? '*' :
892 croak "Unhandled token ", vis($token),
893 " (the hash has no entry for '$tokname' or '*'";
894 my $val = $hash->{$key} //
895 croak "Unhandled token ", vis($token),
896 " (the hash entry for '$key' contains undef)";
897 if (ref($val) eq 'CODE') {
898 ($return_op, $val) = $val->(@_);
899 croak "Unhandled token ", vis($token),
900 ivis '; the callback in hash{$key} returned ($return_op,$val)\n'
901 unless ($return_op & MM_SUBST)==0 || defined $val;
902 } else {
903 croak "Invalid token modifier ",visq(":$_") foreach @$custom_mods;
904 }
905 # FIXME: Why is _to_content_list needed here?
906 return ($return_op, ODF::MailMerge::_to_content_list($val))
907 }
908 #ODF::MailMerge::replace_tokens($table, {'*' => \&wrapper_cb}, %opts);
909 my $r = eval {
910 ODF::MailMerge::replace_tokens($table, {'*' => \&wrapper_cb}, %opts)
911 };
912 if ($@) { # filter out our internal stuff to make easier to read
913 { local $_;
914 $@ =~ s/^[^\n]* called \Kat \Q${__FILE__}\E line .*?(?=\s*\Q${__PACKAGE__}\E::add_record)/from [MM internals]/msg
915 unless $opts{debug};
916 }
917 die "$@\n";
918 }
919 $r
920 }#add_record
921  
922 sub finish {
923 my ($self, %opts) = @_;
924 delete($self->{proto_table})->delete();
925 }
926  
927 1;
928 __END__