]> git.vpit.fr Git - perl/modules/LaTeX-TikZ.git/blob - lib/LaTeX/TikZ/Formatter.pm
Rename LT::Set::Mutable to ::Container
[perl/modules/LaTeX-TikZ.git] / lib / LaTeX / TikZ / Formatter.pm
1 package LaTeX::TikZ::Formatter;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 LaTeX::TikZ::Formatter - LaTeX::TikZ formatter object.
9
10 =head1 VERSION
11
12 Version 0.02
13
14 =cut
15
16 our $VERSION = '0.02';
17
18 =head1 DESCRIPTION
19
20 A formatter object turns a L<LaTeX::TikZ::Set> tree into the actual TikZ code, depending on some parameters such as the scale, the unit or the origin.
21
22 =cut
23
24 use Sub::Name ();
25
26 use LaTeX::TikZ::Point;
27
28 use LaTeX::TikZ::Interface;
29
30 use LaTeX::TikZ::Tools;
31
32 use Any::Moose;
33 use Any::Moose 'Util::TypeConstraints';
34
35 =head1 ATTRIBUTES
36
37 =head2 C<unit>
38
39 The unit in which lengths are printed.
40 Valid units are C<cm> for centimeters and C<pt> for points.
41
42 Defaults to C<cm>.
43
44 =cut
45
46 has 'unit' => (
47  is      => 'ro',
48  isa     => enum([ qw<cm pt> ]),
49  default => 'cm',
50 );
51
52 =head2 C<format>
53
54 The format used to print the numbers.
55
56 Defaults to C<%s>.
57
58 =cut
59
60 has 'format' => (
61  is      => 'ro',
62  isa     => 'Str',
63  default => '%s',
64 );
65
66 =head2 C<scale>
67
68 The scale of the drawing.
69
70 Defaults to C<1>.
71
72 =cut
73
74 has 'scale' => (
75  is      => 'rw',
76  isa     => 'Num',
77  default => 1,
78 );
79
80 =head2 C<width>
81
82 The width of the drawing area.
83
84 Defaults to C<undef> for none.
85
86 =cut
87
88 has 'width' => (
89  is  => 'rw',
90  isa => 'Maybe[Num]',
91 );
92
93 =head2 C<height>
94
95 The height of the drawing area.
96
97 Defaults to C<undef> for none.
98
99 =cut
100
101 has 'height' => (
102  is  => 'rw',
103  isa => 'Maybe[Num]',
104 );
105
106 =head2 C<origin>
107
108 A point coerced into a L<LaTeX::TikZ::Point> object that represents the logical origin of the printed area.
109 If L</width> and L</height> are set, the canvas will be equivalent to a rectangle whose lower left corner at C<-$origin> and of given width and length.
110
111 Defaults to C<(0, 0)>, meaning that the drawing area goes from C<(0, 0)> to C<($width, $height)>.
112
113 =cut
114
115 has 'origin' => (
116  is     => 'rw',
117  isa    => 'LaTeX::TikZ::Point::Autocoerce',
118  coerce => 1,
119 );
120
121 =head1 METHODS
122
123 =head2 C<id>
124
125 An unique identifier of the formatter object.
126
127 =cut
128
129 sub id {
130  my $tikz = shift;
131
132  my $origin = $tikz->origin;
133  if (defined $origin) {
134   my ($x, $y) = map $origin->$_, qw<x y>;
135   $origin = "($x;$y)";
136  } else {
137   $origin = "(0;0)";
138  }
139
140  join $;, map {
141   defined() ? "$_" : '(undef)';
142  } map($tikz->$_, qw<unit format scale width height>), $origin;
143 }
144
145 =head2 C<render @sets>
146
147 Processes all the L<LaTeX::TikZ::Set> objects given in C<@sets> to produce the actual TikZ code to insert in the LaTeX file.
148 First, all the mods applied to the sets and their subsets are collected, and a declaration is emitted if needed for each of them by calling L<LaTeX::TikZ::Mod/declare>.
149 Then, the image code is generated for each set.
150
151 This method returns a list of array references :
152
153 =over 4
154
155 =item *
156
157 The first one contains the header lines to include between the C<\documentclass> and the C<\begin{document}>.
158
159 =item *
160
161 The second one contains the mod declaration lines to put inside the document, between C<\begin{document}> and C<\end{document}>.
162
163 =item *
164
165 Finally, there's one array reference for each given TikZ set, which contain the lines for the actual TikZ pictures.
166
167 =back
168
169 The lines returned by L</render> don't end with a line feed.
170
171     my ($header, $declarations, $set1_body, $set2_body) = $formatter->render($set1, $set2);
172
173     open my $tex, '>', 'test.tex' or die "open('>test.tex'): $!";
174
175     print $tex "$_\n" for (
176      "\\documentclass[12pt]{article}",
177      @$header,
178      "\\begin{document}",
179       "\\pagestyle{empty}",
180       @$declarations,
181       "First set :"
182       "\\begin{center}",
183        @$set1_body,
184       "\\end{center}",
185       "Second set :"
186       "\\begin{center}",
187        @$set2_body,
188       "\\end{center}",
189      "\\end{document}",
190     );
191
192 =cut
193
194 my $find_mods = do {
195  our %seen;
196
197  my $find_mods_rec;
198  $find_mods_rec = do {
199   no warnings 'recursion';
200
201   Sub::Name::subname('find_mods_rec' => sub {
202    my ($set, $layers, $others) = @_;
203
204    for ($set->mods) {
205     my $tag = $_->tag;
206     next if $seen{$tag}++;
207
208     if ($_->isa('LaTeX::TikZ::Mod::Layer')) {
209      push @$layers, $_;
210     } else {
211      push @$others, $_;
212     }
213    }
214
215    my @subsets = $set->does('LaTeX::TikZ::Set::Container')
216                  ? $set->kids
217                  : ();
218
219    $find_mods_rec->($_, $layers, $others) for @subsets;
220   });
221  };
222
223  Sub::Name::subname('find_mods' => sub {
224   local %seen = ();
225
226   $find_mods_rec->(@_);
227  });
228 };
229
230 my $translate;
231
232 sub render {
233  my ($tikz, @sets) = @_;
234
235  unless ($translate) {
236   require LaTeX::TikZ::Functor;
237   $translate = LaTeX::TikZ::Functor->new(
238    rules => [
239     'LaTeX::TikZ::Set::Point' => sub {
240      my ($functor, $set, $v) = @_;
241
242      $set->new(
243       point => [
244        $set->x + $v->x,
245        $set->y + $v->y,
246       ],
247       label => $set->label,
248       pos   => $set->pos,
249      );
250     },
251    ],
252   );
253  }
254
255  my $origin = $tikz->origin;
256  if (defined $origin) {
257   @sets = map $_->$translate($origin), @sets;
258  }
259
260  my (@layers, @other_mods);
261  my $seq = LaTeX::TikZ::Set::Sequence->new(kids => \@sets);
262  $find_mods->($seq, \@layers, \@other_mods);
263
264  my $w = $tikz->width;
265  my $h = $tikz->height;
266  my $canvas = '';
267  if (defined $w and defined $h) {
268   require LaTeX::TikZ::Set::Rectangle;
269   for (@sets) {
270    $_->clip(LaTeX::TikZ::Set::Rectangle->new(
271     from   => 0,
272     width  => $w,
273     height => $h,
274    ));
275   }
276   $_ = $tikz->len($_) for $w, $h;
277   $canvas = ",papersize={$w,$h},body={$w,$h}";
278  }
279
280  my @header = (
281   "\\usepackage[pdftex,hcentering,vcentering$canvas]{geometry}",
282   "\\usepackage{tikz}",
283   "\\usetikzlibrary{patterns}",
284  );
285
286  my @decls;
287  push @decls, LaTeX::TikZ::Mod::Layer->declare(@layers) if  @layers;
288  push @decls, $_->declare($tikz)                        for @other_mods;
289
290  my @bodies = map [
291   "\\begin{tikzpicture}",
292   @{ $_->draw($tikz) },
293   "\\end{tikzpicture}",
294  ], @sets;
295
296  return \@header, \@decls, @bodies;
297 }
298
299 =head2 C<len $len>
300
301 Format the given length according to the formatter options.
302
303 =cut
304
305 sub len {
306  my ($tikz, $len) = @_;
307
308  $len = 0 if LaTeX::TikZ::Tools::numeq($len, 0);
309
310  sprintf $tikz->format . $tikz->unit, $len * $tikz->scale;
311 }
312
313 =head2 C<angle $theta>
314
315 Format the given angle (in radians) according to the formatter options.
316
317 =cut
318
319 sub angle {
320  my ($tikz, $a) = @_;
321
322  $a = ($a * 180) / CORE::atan2(0, -1);
323  $a += 360 if LaTeX::TikZ::Tools::numcmp($a, 0) < 0;
324
325  require POSIX;
326  sprintf $tikz->format, POSIX::ceil($a);
327 }
328
329 =head2 C<label $name, $pos>
330
331 Returns the TikZ code for a point labeled C<$name> at position C<$pos> according to the formatter options.
332
333 =cut
334
335 sub label {
336  my ($tikz, $name, $pos) = @_;
337
338  my $scale = sprintf '%0.2f', $tikz->scale / 5;
339
340  "node[scale=$scale,$pos] {$name}";
341 }
342
343 =head2 C<thickness>
344
345 Format the given line thickness according to the formatter options.
346
347 =cut
348
349 sub thickness {
350  my ($tikz, $width) = @_;
351
352  # width=1 is 0.4 points for a scale of 2.5
353  0.8 * $width * ($tikz->scale / 5);
354 }
355
356 LaTeX::TikZ::Interface->register(
357  formatter => sub {
358   shift;
359
360   __PACKAGE__->new(@_);
361  },
362 );
363
364 __PACKAGE__->meta->make_immutable;
365
366 =head1 SEE ALSO
367
368 L<LaTeX::TikZ>.
369
370 =head1 AUTHOR
371
372 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
373
374 You can contact me by mail or on C<irc.perl.org> (vincent).
375
376 =head1 BUGS
377
378 Please report any bugs or feature requests to C<bug-latex-tikz at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=LaTeX-TikZ>.
379 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
380
381 =head1 SUPPORT
382
383 You can find documentation for this module with the perldoc command.
384
385     perldoc LaTeX::TikZ
386
387 =head1 COPYRIGHT & LICENSE
388
389 Copyright 2010 Vincent Pit, all rights reserved.
390
391 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
392
393 =cut
394
395 1; # End of LaTeX::TikZ::Formatter