Source

Fiction-XML / perl / modules / XML-Grammar-Fiction / lib / XML / Grammar / FictionBase / TagsTree2XML.pm

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package XML::Grammar::FictionBase::TagsTree2XML;

use MooX 'late';

our $VERSION = '0.14.3';

use XML::Writer;
use HTML::Entities ();

sub _get_xml_xml_ns
{
    return "http://www.w3.org/XML/1998/namespace";
}

sub _get_xlink_xml_ns
{
    return "http://www.w3.org/1999/xlink";
}

=head1 NAME

XML::Grammar::FictionBase::TagsTree2XML - base class for the tags-tree
to XML converters.

=head1 VERSION

Version 0.14.3

=cut

has '_parser_class' =>
(
    is => "ro",
    isa => "Str",
    init_arg => "parser_class",
    default => "XML::Grammar::Fiction::FromProto::Parser::QnD",
);

has "_parser" => (
    'isa' => "XML::Grammar::Fiction::FromProto::Parser",
    'is' => "rw",
    lazy => 1,
    default => sub {
        my $self = shift;
        return $self->_parser_class->new();
    },
);

sub _get_initial_writer
{
    my $self = shift;

    my $writer = XML::Writer->new(
        OUTPUT => $self->_buffer(),
        ENCODING => "utf-8",
        NAMESPACES => 1,
        PREFIX_MAP =>
        {
            $self->_get_default_xml_ns() => "",
            $self->_get_xml_xml_ns() => 'xml',
            $self->_get_xlink_xml_ns() => 'xlink',
        },
    );

    $writer->xmlDecl("utf-8");

    return $writer;
}

has "_writer" => (
    'isa' => "Maybe[XML::Writer]",
    'is' => "rw",
    lazy => 1,
    default => sub { return shift->_get_initial_writer(); },
);

sub _get_initial_buffer {
    my $buffer = '';
    return \$buffer;
}

has '_buffer' => (
    is => "rw",
    lazy => 1,
    default => sub { return shift->_get_initial_buffer; },
);

sub _reset_buffer
{
    my $self = shift;

    $self->_buffer($self->_get_initial_buffer());
    $self->_writer($self->_get_initial_writer());

    return;
}

sub _flush_buffer
{
    my $self = shift;

    my $ret = $self->_buffer();
    $self->_reset_buffer();

    return $ret;
}

my %passthrough_elem =
(
    b => sub { return shift->_bold_tag_name(); },
    i => sub { return shift->_italics_tag_name(); },
);

sub _calc_passthrough_cb
{
    my ($self, $name) = @_;

    if (exists($passthrough_elem{$name}))
    {
        return $passthrough_elem{$name};
    }
    else
    {
        return undef();
    }
}

sub _calc_passthrough_name
{
    my ($self, $name, $elem) = @_;

    my $cb = $self->_calc_passthrough_cb($name);

    if (ref($cb) eq 'CODE')
    {
        return $cb->($self, $name, $elem,);
    }
    else
    {
        return $cb;
    }
}

sub _write_elem
{
    my ($self, $args) = @_;

    my $elem = $args->{elem};

    if (ref($elem) eq "")
    {
        $self->_writer->characters($elem);
    }
    else
    {
        return $self->_write_elem_obj($args);
    }
}

sub _write_Element_Paragraph
{
    my ($self, $elem) = @_;

    return $self->_output_tag_with_childs(
        {
            start => [$self->_paragraph_tag()],
            elem => $elem,
        },
    );
}

sub _write_Element_Element
{
    my ($self, $elem) = @_;

    return $self->_write_Element_elem($elem);
}

sub _write_Element_Comment
{
    my ($self, $elem) = @_;

    $self->_writer->comment($elem->text());
}

sub _calc_write_elem_obj_classes
{
    return [qw(Text Paragraph Element Comment)];
}

sub _output_tag_with_childs
{
    my ($self, $args) = @_;

    return
        $self->_output_tag({
            %$args,
            'in' => sub {
                return $self->_write_elem_childs( $args->{elem} );
            },
        });
}

sub _write_elem_childs
{
    my ($self, $elem) = @_;

    foreach my $child (@{$elem->_get_childs()})
    {
        $self->_write_elem({ elem => $child,},);
    }

    return;
}

sub _write_elem_obj
{
    my ($self, $args) = @_;

    my $elem = $args->{elem};

    foreach my $class (@{$self->_calc_write_elem_obj_classes()})
    {
        if ($elem->_short_isa($class))
        {
            my $meth = "_write_Element_$class";
            $self->$meth($elem);
            return;
        }
    }

    Carp::confess("Class of element not detected - " . ref($elem) . "!");
}

sub _write_Element_elem
{
    my ($self, $elem) = @_;

    my $name = $elem->name();

    if ($elem->_short_isa("InnerDesc"))
    {
        $self->_output_tag_with_childs(
            {
                start => ["inlinedesc"],
                elem => $elem,
            }
        );
        return;
    }
    elsif (defined(my $out_name = $self->_calc_passthrough_name($name, $elem)))
    {
        return $self->_output_tag_with_childs(
            {
                start => [$out_name],
                elem => $elem,
            }
        );
    }
    else
    {
        my $method = "_handle_elem_of_name_$name";

        $self->$method($elem);

        return;
    }
}

sub _handle_elem_of_name_s
{
    my ($self, $elem) = @_;

    $self->_write_scene({scene => $elem});
}

sub _handle_elem_of_name_br
{
    my ($self, $elem) = @_;

    $self->_writer->emptyTag("br");

    return;
}

sub _output_tag
{
    my ($self, $args) = @_;

    my @start = @{$args->{start}};
    $self->_writer->startTag([$self->_get_default_xml_ns(),$start[0]], @start[1..$#start]);

    $args->{in}->($self, $args);

    $self->_writer->endTag();
}

sub _convert_while_handling_errors
{
    my ($self, $args) = @_;

    eval {
        my $output_xml = $self->convert(
            $args->{convert_args},
        );

        open my $out, ">", $args->{output_filename};
        binmode $out, ":utf8";
        print {$out} $output_xml;
        close($out);
    };

    # Error handling.

    my $e;
    if ($e = Exception::Class->caught("XML::Grammar::Fiction::Err::Parse::TagsMismatch"))
    {
        warn $e->error(), "\n";
        warn "Open: ", $e->opening_tag->name(),
            " at line ", $e->opening_tag->line(), "\n"
            ;
        warn "Close: ",
            $e->closing_tag->name(), " at line ",
            $e->closing_tag->line(), "\n";

        exit(-1);
    }
    elsif ($e = Exception::Class->caught("XML::Grammar::Fiction::Err::Parse::LineError"))
    {
        warn $e->error(), "\n";
        warn "At line ", $e->line(), "\n";
        exit(-1);
    }
    elsif ($e = Exception::Class->caught("XML::Grammar::Fiction::Err::Parse::TagNotClosedAtEOF"))
    {
        warn $e->error(), "\n";
        warn "Open: ", $e->opening_tag->name(),
            " at line ", $e->opening_tag->line(), "\n"
            ;

        exit(-1);
    }
    elsif ($e = Exception::Class->caught())
    {
        if (ref($e))
        {
            $e->rethrow();
        }
        else
        {
            die $e;
        }
    }

    return;
}

sub _read_file
{
    my ($self, $filename) = @_;

    open my $in, "<", $filename or
        Carp::confess("Could not open the file \"$filename\" for slurping.");
    binmode $in, ":utf8";
    my $contents;
    {
        local $/;
        $contents = <$in>;
    }
    close($in);

    return $contents;
}

sub _calc_tree
{
    my ($self, $args) = @_;

    my $filename = $args->{source}->{file} or
        confess "Wrong filename given.";

    return $self->_parser->process_text($self->_read_file($filename));
}

sub _write_scene
{
    my ($self, $args) = @_;

    my $scene = $args->{scene};

    my $tag = $scene->name;

    if (($tag eq "s") || ($tag eq "scene"))
    {
        $self->_write_scene_main($scene);
    }
    else
    {
        confess "Improper scene tag - should be '<s>' or '<scene>'!";
    }

    return;
}

=head2 $self->convert({ source => { file => $path_to_file } })

Converts the file $path_to_file to XML and returns it. Throws an exception
on failure.

=cut

sub convert
{
    my ($self, $args) = @_;

    my $tree = $self->_calc_tree($args);
    if (!defined($tree))
    {
        Carp::confess("Parsing failed.");
    }

    $self->_convert_write_content($tree);

    return ${$self->_flush_buffer()};
}

=head2 meta()

Internal - (to settle pod-coverage.).

=cut

1;