]> git.vpit.fr Git - perl/modules/LaTeX-TikZ.git/blob - lib/LaTeX/TikZ/Formatter.pm
a5bda82f88ffa32c445c7f0f5157ac4389ed4e11
[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->isa('LaTeX::TikZ::Set::Sequence')
216                   || $set->isa('LaTeX::TikZ::Set::Union'))
217                    ? $set->kids
218                    : ();
219
220    $find_mods_rec->($_, $layers, $others) for @subsets;
221   });
222  };
223
224  Sub::Name::subname('find_mods' => sub {
225   local %seen = ();
226
227   $find_mods_rec->(@_);
228  });
229 };
230
231 my $translate;
232
233 sub render {
234  my ($tikz, @sets) = @_;
235
236  unless ($translate) {
237   require LaTeX::TikZ::Functor;
238   $translate = LaTeX::TikZ::Functor->new(
239    rules => [
240     'LaTeX::TikZ::Set::Point' => sub {
241      my ($functor, $set, $v) = @_;
242
243      $set->new(
244       point => [
245        $set->x + $v->x,
246        $set->y + $v->y,
247       ],
248       label => $set->label,
249       pos   => $set->pos,
250      );
251     },
252    ],
253   );
254  }
255
256  my $origin = $tikz->origin;
257  if (defined $origin) {
258   @sets = map $_->$translate($origin), @sets;
259  }
260
261  my (@layers, @other_mods);
262  my $seq = LaTeX::TikZ::Set::Sequence->new(kids => \@sets);
263  $find_mods->($seq, \@layers, \@other_mods);
264
265  my $w = $tikz->width;
266  my $h = $tikz->height;
267  my $canvas = '';
268  if (defined $w and defined $h) {
269   require LaTeX::TikZ::Set::Rectangle;
270   for (@sets) {
271    $_->clip(LaTeX::TikZ::Set::Rectangle->new(
272     from   => 0,
273     width  => $w,
274     height => $h,
275    ));
276   }
277   $_ = $tikz->len($_) for $w, $h;
278   $canvas = ",papersize={$w,$h},body={$w,$h}";
279  }
280
281  my @header = (
282   "\\usepackage[pdftex,hcentering,vcentering$canvas]{geometry}",
283   "\\usepackage{tikz}",
284   "\\usetikzlibrary{patterns}",
285  );
286
287  my @decls;
288  push @decls, LaTeX::TikZ::Mod::Layer->declare(@layers) if  @layers;
289  push @decls, $_->declare($tikz)                        for @other_mods;
290
291  my @bodies = map [
292   "\\begin{tikzpicture}",
293   @{ $_->draw($tikz) },
294   "\\end{tikzpicture}",
295  ], @sets;
296
297  return \@header, \@decls, @bodies;
298 }
299
300 =head2 C<len $len>
301
302 Format the given length according to the formatter options.
303
304 =cut
305
306 sub len {
307  my ($tikz, $len) = @_;
308
309  $len = 0 if LaTeX::TikZ::Tools::numeq($len, 0);
310
311  sprintf $tikz->format . $tikz->unit, $len * $tikz->scale;
312 }
313
314 =head2 C<angle $theta>
315
316 Format the given angle (in radians) according to the formatter options.
317
318 =cut
319
320 sub angle {
321  my ($tikz, $a) = @_;
322
323  $a = ($a * 180) / CORE::atan2(0, -1);
324  $a += 360 if LaTeX::TikZ::Tools::numcmp($a, 0) < 0;
325
326  require POSIX;
327  sprintf $tikz->format, POSIX::ceil($a);
328 }
329
330 =head2 C<label $name, $pos>
331
332 Returns the TikZ code for a point labeled C<$name> at position C<$pos> according to the formatter options.
333
334 =cut
335
336 sub label {
337  my ($tikz, $name, $pos) = @_;
338
339  my $scale = sprintf '%0.2f', $tikz->scale / 5;
340
341  "node[scale=$scale,$pos] {$name}";
342 }
343
344 =head2 C<thickness>
345
346 Format the given line thickness according to the formatter options.
347
348 =cut
349
350 sub thickness {
351  my ($tikz, $width) = @_;
352
353  # width=1 is 0.4 points for a scale of 2.5
354  0.8 * $width * ($tikz->scale / 5);
355 }
356
357 LaTeX::TikZ::Interface->register(
358  formatter => sub {
359   shift;
360
361   __PACKAGE__->new(@_);
362  },
363 );
364
365 __PACKAGE__->meta->make_immutable;
366
367 =head1 SEE ALSO
368
369 L<LaTeX::TikZ>.
370
371 =head1 AUTHOR
372
373 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
374
375 You can contact me by mail or on C<irc.perl.org> (vincent).
376
377 =head1 BUGS
378
379 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>.
380 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
381
382 =head1 SUPPORT
383
384 You can find documentation for this module with the perldoc command.
385
386     perldoc LaTeX::TikZ
387
388 =head1 COPYRIGHT & LICENSE
389
390 Copyright 2010 Vincent Pit, all rights reserved.
391
392 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
393
394 =cut
395
396 1; # End of LaTeX::TikZ::Formatter