--- trunk/lib/Frey/Web.pm 2008/11/19 16:53:13 457 +++ trunk/lib/Frey/Web.pm 2009/01/10 18:53:15 986 @@ -1,36 +1,34 @@ package Frey::Web; use Moose::Role; -use Frey::Types; +with 'Frey::Session'; -use Continuity::Widget::DomNode; use Data::Dump qw/dump/; -use Carp qw/confess/; +use Carp qw/confess cluck carp/; use File::Slurp; +use Text::Tabs; # expand, unexpand + +use lib 'lib'; + +use Frey::Types; use Frey::Bookmarklet; -use Frey::ClassBrowser; +use Frey::Class::Browser; +use Frey::INC; -has 'head' => ( - is => 'rw', - isa => 'ArrayRef[Str]', - default => sub { [ 'static/frey.css' ] }, -); +use Frey::SVK; -has 'status' => ( - is => 'rw', - isa => 'ArrayRef[HashRef[Str]]', - lazy => 1, - default => sub { [ - { 'Bookmarklets' => Frey::Bookmarklet->new->as_markup }, - { 'ClassBrowser' => Frey::ClassBrowser->new( usage_on_top => 0 )->as_markup }, - ] }, -); +our @head; +sub head { @head } has 'request_url' => ( is => 'rw', isa => 'Uri', coerce => 1, - default => '/', + required => 1, + default => sub { + carp "undefined request_url"; + '/'; + }, ); has 'title' => ( @@ -47,43 +45,113 @@ is => 'rw', isa => 'Str', default => 'text/html', + documentation => 'Content-type header', ); -=head2 inline_smaller_than - -Inline JavaScript and CSS smaller than this size into page reducing -round-trips to server. - -=cut +has 'dump_max_bytes' => ( + is => 'rw', + isa => 'Int', + default => 4096, + documentation => 'maximum dump size sent to browser before truncation', +); has 'inline_smaller_than' => ( is => 'rw', isa => 'Int', default => 10240, + documentation => 'inline JavaScript and CSS to reduce round-trips', +); + +has 'html_dump_width' => ( + documentation => 'crop longer lines in dumps', + is => 'rw', + isa => 'Int', +# required => 1, # FIXME we can't have required fields with defaults because Frey::Action isn't smart enough and asks for them + default => 250, +); + +has 'wrap_in_page' => ( + documentation => 'wrap full html page with status bar around content', + is => 'rw', + isa => 'Bool', + default => 1, ); -sub dom2html { -# warn "## dom2html ",dump( @_ ); - return Continuity::Widget::DomNode->create( @_ )->to_string; +my %escape = ('<'=>'<', '>'=>'>', '&'=>'&', '"'=>'"'); +my $escape_re = join '|' => keys %escape; + +sub html_escape { + my ( $self, $html ) = @_; + return '' unless defined $html; + $html =~ s/($escape_re)/$escape{$1}/g; + return $html; } -sub _inline_path { +# from Mojo::ByteStream +sub url_escape { + my ( $self, $url, $pattern ) = @_; + $pattern ||= 'A-Za-z0-9\-\.\_\~'; + $url =~ s/([^$pattern])/sprintf('%%%02X',ord($1))/ge; + return $url; +} + +sub html_dump { + my ( $self, $dump ) = @_; + $dump = dump( $dump ) if ref($dump); + my $width = $self->html_dump_width; + $dump =~ s{(\n[^\n]{$width})([^\n]+?)([^\n]{5})}{\n$1...$3}gs; + $dump = $self->html_escape( $dump ); + $dump =~ s{\Q...\E}{…}gs; +# $dump =~ $self->html_links( $dump ); # FIXME include this + return "$dump"; +} + +sub popup { my $self = shift; $self->popup_dropdown('popup', @_); } +sub dropdown { my $self = shift; $self->popup_dropdown('dropdown', @_); } + +our $re_html = qr{<(?:!--|(\w+)|[^>]+)/?>}s; # relaxed html check for one semi-valid tag + +sub popup_dropdown { + my ( $self, $type, $name, $content, $full ) = @_; + + $content = $self->html_dump($content) if ref $content; + + $content = qq|$content| unless $content =~ m{^\s*<(span|a|code).+?/\1>\s*}; + + $content =~ s{([^<]+)}{$1} && $self->TODO("code wrapped in span"); + + warn "## $type [$name] = ", length( $content ), " bytes"; # if $self->debug; # FIXME + + if ( $name =~ m{::} && $name !~ $re_html ) { + return qq|$name $content\n|; + } elsif ( $name =~ s{^\s*($name $content\n|; + } +} + +sub _inline { my ( $self, $path ) = @_; - -s $path < $self->inline_smaller_than; + return unless defined $path; + warn "# _inline $path"; + -e $path && -s $path < $self->inline_smaller_than && -s $path; } sub _head_html { my $self = shift; my $out = ''; - foreach my $path ( @{ $self->head } ) { + foreach my $path ( @head ) { $path =~ s!^/!!; if ( $path =~ m/\.js$/ ) { - $out .= $self->_inline_path( $path ) ? - qq|| : + my $size; + $out .= $size = _inline( $path ) ? + qq|| : qq||; } elsif ( $path =~ m/\.css$/ ) { - $out .= $self->_inline_path( $path ) ? - qq|| : + my $size; + $out .= $size = _inline( $path ) ? + qq|| : qq||; } elsif ( $path =~ m{<.+>}s ) { $out .= $path; @@ -110,11 +178,11 @@ return if ! defined $path || $path eq ''; $path =~ s!^/!!; - if ( $path =~ m{<.*>}s ) { - push @{ $self->head }, $path; + if ( $path =~ $re_html ) { + push @head, $path; } elsif ( -e $path ) { if ( $path =~ m/\.(?:js|css)$/ ) { - push @{ $self->head }, $path; + push @head, $path; } else { confess "can't add_head( $path ) it's not js or css"; } @@ -125,12 +193,61 @@ } +sub _add_css_js { + my ( $self, $what, $content ) = @_; + + my $tag = $what eq 'css' ? 'style' : 'script'; + my $type = $what eq 'css' ? 'text/css' : 'text/javascript'; + my $head; + + my ( $package, $path, $line ) = caller(1); + + $content = "/$content" if $content !~ m{[\n\r]} && -e $content; + if ( $content =~ $re_html ) { + $head = qq| + $content + + |; + } elsif ( $content =~ m{^(/\w+|https?://)} && $content !~ m{[\n\r]} ) { + if ( $what eq 'js' ) { + $head = qq| + <$tag type="$type" src="$content"> + /* $what via $package at $path line $line */ + + |; + } else { + $head = qq| + + + |; + } + } else { + $head = qq| + <$tag type="$type"> + /* via $package at $path line $line */ + $content + + |; + }; + $self->add_head( $head ); +} + +sub add_css { + my ($self,$css) = @_; + $self->_add_css_js( 'css', $css ); +} + +sub add_js { + my ($self,$js) = @_; + $self->_add_css_js( 'js', $js ); +} + our $reload_counter = 0; -=head2 page +=head2 html_page - $self->page( + $self->html_page( title => 'page title', head => '', body => 'Page Body', @@ -138,53 +255,91 @@ =cut -sub page { +our @status; +sub status { @status }; + +our $icon_html; + +sub html_page { my $self = shift; my $a = {@_}; $reload_counter++; my $status_line = ''; - foreach my $part ( @{ $self->status } ) { - if ( ref($part) ne 'HASH' ) { - warn "part not hash ",dump( $part ) ; - #$self->status( $part ); - next; - } + + foreach my $part ( @status ) { foreach my $name ( keys %$part ) { - my $content = $part->{$name}; - if ( ref($content) ) { - $content = '' . dump($content) . ''; - my $l = length($content); - $content = qq|$l bytes| if $l > 1024; - } else { - $content = qq|$content|; - } - warn "### part [$name] = ", length( $content ), " bytes" if $self->debug; - $status_line .= qq|$name $content\n|; + $status_line .= $self->popup( $name, $part->{$name} ); } } my $url = $self->request_url; $url =~ s{\?reload=\d+}{}; - my $body = $a->{body} || $self->as_markup; - return $body if $self->content_type !~ m{html}; - $body ||= ''; + my $body = $a->{body}; + if ( ! $body ) { + my $run = $a->{run} || 'as_markup'; + warn "# no body, invoke $self->$run on ", ref($self); + $body = $self->$run; + } + if ( $self->content_type !~ m{html} || ! $self->wrap_in_page ) { + warn "# return only $self body ", $self->content_type; + return $body + } elsif ( ! defined $body ) { + warn "# no body"; + $body = ''; + } + + $status_line .= $self->warnings_html; + + my ($exit,$description) = ('exit','stop server'); + ($exit,$description) = ('restart','restart server') + if $ENV{FREY_RESTART}; # tune labels on exit link + + my $right = + qq| + + reload + $exit + + |; + + my $svk = Frey::SVK->new; + my $info = $svk->info; + my $revision = $svk->info->{Revision} || ''; + $revision = $1 if $info->{'Mirrored From'} =~ m{Rev\.\s+(\d+)}; + + $self->add_icon unless $icon_html; + + my $title = undef + || $a->{title} + || $self->title + || ref($self) + ; + +# $title =~ s{(\w)\w+::}{$1:}g; # XXX compress names of classes + + $self->add_css(qq| + body { + padding-bottom: 3em; /* don't overlap status line */ + } + |); my $html = join("\n", qq||, $self->_head_html, - '' . ( $self->title || $a->{title} || ref($self) ) . '', + qq|$title|, '', + ( $icon_html || '' ), ( $a->{head} || '' ), qq| $body
- Frey $Frey::VERSION - $url + Frey $Frey::VERSION $revision $status_line + $right
|, @@ -195,15 +350,428 @@ return $html; } +=head2 editor + +Create HTML editor link with optional line and title + + my $html = $self->editor( $class, $line, $title ); + +=cut + +sub editor { + my ( $self, $class, $line, $title ) = @_; + confess "need class" unless $class; + if ( ! defined $title ) { + $title = "edit $class"; + $title .= " line $line" if $line; + } + $line ||= 1; + qq|$class|; +} + +=head2 html_links + +Create HTML links to editor for perl error message + + my $html = $self->html_links( $error ) + +=cut + +sub html_links { + my ( $self, $error ) = @_; + + $error = $self->strip_full_path( $error ); + +# $error =~ s[(bless\({\s+.+?\s+},\s+)("[^"]+")(\) at)][$1$2$3]gs; # FIXME insert bless hiding back + + # perl's backtrace + $error =~ s{at\s+(\S+)\s+line\s+(\d+)} + {at $1 line $2}gsm; + + $error =~ s{(via (?:package)\s+"?)([\w:]+)("?)} + {$1$2$3}gsm + || # or anything that looks like "Class::Name" + $error =~ s{"(\w+(?:::\w+)+)"} + {"$1"}gsm; + + # method error messages + # FIXME replace with link to Frey::Introspect data + $error =~ s{(method ")(\w+)(" via)} + {$1$2$3}gsm; + + # link paths to editor + $error =~ s{((?:lib|t)/[\S]+)\s+(\d+\s+bytes)} + {$1}gsm; + + $error =~ s{(class ")([\w:]+)(")} + {$1$2$3}gsm; + + return $error; +} + +sub html_self { + my $self = shift; + my $html = $self; + $html =~ s{([\w:]+)=}{$1=}gsm; + return $html; +} + +=head2 error + +This method will return error to browser and backtrace unless +error message ends with LF C<\n> just like L + +=cut + sub error { my $self = shift; my $error = join(" ", @_); - my ($package, $filename, $line) = caller; - $error .= " at $filename line $line" if $error !~ m{ at }; - warn "WARN: $error\n"; - $error =~ s{at\s+(\S+)\s+line\s+(\d+)}{at $1 line $2}gsm; - $error =~ s{(via package ")([\w:]+)(")}{$1$2$3}gsm; - return qq|
$error
|; + + my $fatal = ''; + my $backtrace = ''; + + if ( $error !~ m{\n$} ) { + if ( my @backtrace = $self->backtrace ) { + $backtrace = + "\n" . $self->html_self . "->error backtrace\n\t" + . $self->html_links( join( "\n\t", @backtrace ) ) + ; + $fatal = qq| frey-fatal|; + } + } + + warn "ERROR: $error\n"; + $self->add_icon('error'); + $error = $self->html_links( $error ); + return qq|
$error $backtrace
| ; +} + +=head1 Status line + +=head2 add_status + + $self->add_status( { name => { some => 'data' } } ); + + $self->add_status( "append to last status popup" ); + +=cut + +sub add_status { + my ( $self, $data ) = @_; + die "no data" unless $data; + if ( ref $data ) { + push @status, $data; + } else { + if ( defined $status[ $#status ] ) { + $status[ $#status ]->{ '+' } = $data; + } else { + push @status, { '+' => $data }; + } + } +} + +=head2 clean_status + +Called at beginning of each request + + $self->clean_status; + +=cut + +sub clean_status { + my ($self) = shift; + @head = ( 'static/frey.css' ); + @status = ( + { 'ClassBrowser' => Frey::Class::Browser->new( usage_sort => 1, usage_on_top => 0 )->as_markup }, + { 'Bookmarklets' => Frey::Bookmarklet->new->as_markup }, + { 'INC' => Frey::INC->new->as_markup }, + ); + $icon_html = ''; +} + +=head2 status_parts + +Dump all status line parts + + $self->status_parts + +=cut + +sub status_parts { + warn "## status parts ", dump( map { keys %$_ } @status ); +} + +=for debug + +sub DEMOLISH { + my ( $self ) = @_; + warn "## $self DEMOLISH status ", $#status + 1, " elements ", dump( map { keys %$_ } @status ) if @status; +} + +=cut + +=head2 add_icon + + Frey::Foo->add_icon; # /static/icons/Frey/Foo.png + Frey::Foo->add_icon('warning'); # /static/icons/Frey/Foo/warning.png + +=cut + +sub icon_path { + my ($self,$class,$variant) = @_; + + sub icon_exists { + my $class = shift; + $class =~ s{::}{/}g; + $class .= "/$variant" if $variant; + my $icon_path = 'static/icons/' . $class . '.png'; + return $icon_path if -e $icon_path; + return; + } + + my $path = icon_exists( $class ); + if ( ! $path ) { + my $super_class = $class; + while ( $super_class =~ s{::[^:]+$}{} && ! $path ) { + $path = icon_exists( $super_class ) unless $super_class eq 'Frey'; # don't default on Frey icon + } + } + + if ( ! $path ) { + $self->TODO( "add icon for $class" . ( $variant ? " variant $variant" : '' ) ); + return undef; + } + + warn "# $class from $self icon_path $path" if $self->debug; + return $path; +} + +sub add_icon { + my ($self,$variant) = @_; + + my $class = $self->class if $self->can('class'); + #$class ||= $self->title; + $class ||= ref($self); + my $icon_path = $self->icon_path( $class, $variant ) || return; + + $icon_html .= qq||; + warn "# using icon $icon_path"; + +=for later + + # FIXME http://en.wikipedia.org/wiki/Favicon suggest just rel="icon" but that doesn't seem to work! + my $ico_path = $icon_path; + $ico_path =~ s{png$}{ico}; + if ( ! -e $ico_path ) { + system "convert $icon_path $ico_path"; + warn "# convert $icon_path $ico_path : $@"; + } + $icon_html .= qq|| if -e $ico_path; + +=cut + +} + +my $warn_colors = { + '#' => '#444', + '##' => '#888', +}; + +my $multiline_markers = { + '(' => ')', + '{' => '}', + '[' => ']', + '"' => '"', +}; + +=for later + +my $multiline_re = '[\\' . join('\\', keys %$multiline_markers ) . ']'; +warn "## multiline markers ", dump( $multiline_markers ), " -> $multiline_re"; + +=cut + +sub log_path { + $Frey::Bootstrap::log_path || die "no log_path?"; +} + +our $pwd = `pwd`; +chomp $pwd; + +sub strip_full_path { + my ($self, $msg) = @_; + # Mojo seems to expand warn messages to full path which is annoying + $msg =~ s{/[^/]+/\.\./}{/}gs; + $msg =~ s{$pwd/*}{}gs; + return $msg; +} + +our $last_log_pos = 0; +our $last_log_line = 0; + +sub warnings_html { + my ($self,$level) = shift; + $level ||= $self->debug, + my $path = $self->log_path; + + my $max = 30; + my $pos = 0; + my @warnings = ( '' x $max ); # XXX circualar buffer for 50 lines + my $line = $last_log_line; + my $multiline_end; + + # XXX do we really want to do this every time? + my $css = qq|/* short css classes for levels */\n|; + my $level_to_class; + foreach ( keys %$warn_colors ) { + my $l = length($_); + my $class = 'l' . $l; + $css .= qq|.$class { color: $warn_colors->{$_} }\n|; + $level_to_class->{ $_ } = $class; + } + $self->add_css( $css ); + + open(my $log, '<', $path) || die "can't open $path: $!"; + seek($log, $last_log_pos, 0) || warn "can't seek: $!"; + while(<$log>) { + chomp; + $line++; + + next if m{^\s+(Mojo|Class::MOP|Moose)::}; + + my $style = ''; + +=for filter + + if ( $multiline_end ) { + if ( m{^\Q$multiline_end\E} || m{^\s.+\Q$multiline_end\E;$} ) { +# warn "## $line end of $multiline_end in '$_'\n"; + undef $multiline_end; + } else { +# warn "## $line skipped\n"; + } + } elsif ( m{^(#*)\s+} ) { + my $l = $1 ? length($1) : 0; + if ( $l > $level ) { + undef $multiline_end; + $multiline_end = $multiline_markers->{$1} if m{($multiline_re)$}; +# warn "## $line start $1 .. $multiline_end level $l > $level for '$_'\n" if $multiline_end; + next; + } + +=cut + if ( m{^(#*)} ) { + + my $level = $1; + my $msg = $self->strip_full_path( $_ ); + + my $spacer = ' '; + my $real_msg = expand( $msg ); + if ( length($real_msg) > $self->html_dump_width ) { + + $real_msg = substr( $msg, 0, $self->html_dump_width ); + $msg = unexpand( $real_msg ); + $spacer = '…' + } + + $msg = $self->html_escape( $msg ); + + if ( my $class = $level_to_class->{ $level } ) { + $msg = qq|$msg|; + } + + #$msg .= $spacer . qq|$line\n|; + $msg = qq|$line$msg| + . ( $spacer ? $spacer : '' ) + . "\n"; # XXX
 needs this
+
+			$warnings[ $pos++ % $max ] = $msg;
+		}
+	}
+	$last_log_pos = tell($log);
+	$last_log_line = $line;
+	warn "log has $line lines tell position $last_log_pos";
+	close($log) || die "can't close $path: $!";
+
+	my $size = -s $path;
+
+	my $warnings = join("",
+		map { $warnings[ ( $pos + $_ ) % $max ] || '' } 0 .. ( $max - 1 )
+	);
+
+	my $s = length($warnings);
+
+	return
+		# need to wrap editor link into span so we can have links in warnings
+		  qq|warn|
+		. $self->html_links( $warnings )
+		. qq||
+		;
+}
+
+
+=head2 backtrace
+
+Show backtrace with links to editor
+
+  my @backtrace = $self->backtrace;
+
+=cut
+
+sub backtrace {
+	my ($self) = @_;
+
+	my @backtrace;
+	foreach ( 1 .. 5 ) { # 0 = backtrace
+		my (
+			$package,$path,$line
+			# subroutine hasargs
+			# wantarray evaltext is_require
+			# hints bitmask hinthash
+		) = caller($_) or last;
+
+		push @backtrace,
+			qq|via "$package" at $path line $line|;
+	}
+	#warn "# backtrace: ", dump( @backtrace ) if @backtrace;
+	return @backtrace;
+}
+
+=head2 checkbox
+
+Generate checkbox html markup from some attribute
+
+  my $html = $self->checkbox('attribute_name', $value);
+
+=cut
+
+sub checkbox {
+	my ($self,$name,$value) = @_;
+	my $checked = '';
+	my $all_checkboxes = eval { $self->$name };
+	warn "ERROR tried to get checkbox value for '$name' which is unknown: $@" if $@;
+	$all_checkboxes = [ $all_checkboxes ] unless ref($all_checkboxes) eq 'ARRAY'; # sigh, too chatty
+	$checked = ' checked' if grep { defined $_ && $_ eq $value } @$all_checkboxes;
+	warn "# checkbox $name $value $checked\t", $self->dump( $self->$name );
+	qq||;
+}
+
+=head2 strip
+
+Strip whitespace around content
+
+  my $stripped = strip('  no more whitespace around this   ');
+
+=cut
+
+sub strip {
+	my $t = shift;
+	$t =~ s{^\s+}{}gs;
+	$t =~ s{>\s+<}{><}gs;
+	$t =~ s{\s+$}{}gs;
+	return $t;
 }
 
 1;