correct gnuplot columns if timefmt has spaces
[MojoFacets.git] / lib / MojoFacets / Gnuplot.pm
1 package MojoFacets::Gnuplot;
2
3 use warnings;
4 use strict;
5
6 use base 'Mojolicious::Controller';
7
8 use Data::Dump qw(dump);
9 use Digest::MD5 qw(md5_hex);
10 use Text::Unaccent::PurePerl;
11
12 sub index {
13         my $self = shift;
14
15         my $columns = $self->session('columns') || return $self->redirect_to('/data/columns');
16         my $path    = $self->session('path')    || return $self->redirect_to('/data/load');
17         my $with    = $self->param('with') || 'points';
18
19         my $hide_columns;
20         if ( $self->param('gnuplot_hide') ) {
21                 $hide_columns->{$_}++ foreach $self->param('gnuplot_hide');
22                 warn "## hide_columns ", dump $hide_columns;
23         }
24
25 #       my $name = join('.', 'items', map { my $n = unac_string($_); $n =~ s/\W+/_/g; $n } @$columns );
26         my $name = MojoFacets::Data::__export_path_name( $path, 'items', @$columns );
27
28         warn "# name $name\n";
29
30         my $url = "/export/$path/$name";
31         my $dir = $self->app->home->rel_file('public');
32
33         if ( -e "$dir/$url" ) {
34
35                 my $timefmt = $self->param('timefmt');
36
37                 my $spaces = $timefmt;
38                 $spaces =~ s/\S//g;
39                 $spaces = length( $spaces );
40
41                 my @plot;
42                 foreach ( 1 .. $#$columns ) {
43                         my $title = $columns->[$_];
44                         my $n = $_ + 1 + $spaces;
45                         push @plot, qq|"$dir/$url" using 1:$n title "$title" with $with| unless $hide_columns->{ $title };
46                 }
47
48                 my $g = qq|
49
50 set terminal png
51 set output '$dir/$url.png'
52
53                 |;
54
55                 if ( $timefmt ) {
56                         $g .= qq|
57
58 set xdata time
59 set timefmt "$timefmt"
60 set format x "$timefmt"
61
62                         |;
63                 }
64
65 #set xrange [ "2009-01-01":"2010-01-01" ]
66 #set yrange [ 0 : ]
67
68                 $g .= "\n\nplot " . join(',', @plot) . "\n";
69
70 warn "gnuplot $g";
71
72                 open(my $gnuplot, '|-', 'gnuplot') || die "gnuplot $!";
73                 print $gnuplot $g;
74                 close $gnuplot;
75
76                 if ( -e "$dir/$url.png" ) {
77                         warn "redirect $url.png";
78                         return $self->redirect_to( "$url.png" );
79                 } else {
80                         $self->render_text( "no $dir/$url.png" );
81                 }
82         } else {
83                 $self->render_text("no graph for $url");
84         }
85 }
86
87 1;