ae8d5f385a5d9d640872cab89caf4be1941c83a0
[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                         $title =~ s/_/ /g;
45                         my $n = $_ + 1 + $spaces;
46                         push @plot, qq|"$dir/$url" using 1:$n title "$title" with $with| unless $hide_columns->{ $title };
47                 }
48
49                 my $g = qq|
50
51 set terminal png
52 set output '$dir/$url.png'
53
54                 |;
55
56                 if ( $timefmt ) {
57                         $g .= qq|
58
59 set xdata time
60 set timefmt "$timefmt"
61 set format x "$timefmt"
62
63                         |;
64                 }
65
66 #set xrange [ "2009-01-01":"2010-01-01" ]
67 #set yrange [ 0 : ]
68
69                 $g .= "\n\nplot " . join(',', @plot) . "\n";
70
71 warn "gnuplot $g";
72
73                 open(my $gnuplot, '|-', 'gnuplot') || die "gnuplot $!";
74                 print $gnuplot $g;
75                 close $gnuplot;
76
77                 if ( -e "$dir/$url.png" ) {
78                         warn "redirect $url.png";
79                         return $self->redirect_to( "$url.png" );
80                 } else {
81                         $self->render_text( "no $dir/$url.png" );
82                 }
83         } else {
84                 $self->render_text("no graph for $url");
85         }
86 }
87
88 1;