/[Frey]/branches/zimbardo/lib/Frey/Web.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /branches/zimbardo/lib/Frey/Web.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 859 - (show annotations)
Tue Dec 16 14:26:23 2008 UTC (15 years, 3 months ago) by dpavlin
Original Path: trunk/lib/Frey/Web.pm
File size: 17218 byte(s)
relax html regex (again!), include content if it's html-like
1 package Frey::Web;
2 use Moose::Role;
3
4 with 'Frey::Session';
5
6 #use Continuity::Widget::DomNode;
7 use Data::Dump qw/dump/;
8 use Carp qw/confess cluck carp/;
9 use File::Slurp;
10 use Text::Tabs; # expand, unexpand
11
12 use lib 'lib';
13
14 use Frey::Types;
15
16 use Frey::Bookmarklet;
17 use Frey::Class::Browser;
18 use Frey::INC;
19
20 use Frey::SVK;
21
22 our @head;
23 sub head { @head }
24
25 has 'request_url' => (
26 is => 'rw',
27 isa => 'Uri', coerce => 1,
28 required => 1,
29 default => sub {
30 carp "undefined request_url";
31 '/';
32 },
33 );
34
35 has 'title' => (
36 is => 'rw',
37 isa => 'Str',
38 lazy => 1,
39 default => sub {
40 my ($self) = @_;
41 ref($self);
42 },
43 );
44
45 has 'content_type' => (
46 is => 'rw',
47 isa => 'Str',
48 default => 'text/html',
49 documentation => 'Content-type header',
50 );
51
52 has 'dump_max_bytes' => (
53 is => 'rw',
54 isa => 'Int',
55 default => 4096,
56 documentation => 'maximum dump size sent to browser before truncation',
57 );
58
59 has 'inline_smaller_than' => (
60 is => 'rw',
61 isa => 'Int',
62 default => 10240,
63 documentation => 'inline JavaScript and CSS to reduce round-trips',
64 );
65
66 has 'html_dump_width' => (
67 documentation => 'crop longer lines in dumps',
68 is => 'rw',
69 isa => 'Int',
70 # required => 1, # FIXME we can't have required fields with defaults because Frey::Action isn't smart enough and asks for them
71 default => 250,
72 );
73
74 my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
75 my $escape_re = join '|' => keys %escape;
76
77 sub html_escape {
78 my ( $self, $html ) = @_;
79 $html =~ s/($escape_re)/$escape{$1}/g;
80 return $html;
81 }
82
83 sub html_dump {
84 my ( $self, $dump ) = @_;
85 $dump = dump( $dump ) if ref($dump);
86 my $width = $self->html_dump_width;
87 $dump =~ s{(\n[^\n]{$width})([^\n]+?)([^\n]{5})}{\n$1...$3}gs;
88 $dump = $self->html_escape( $dump );
89 $dump =~ s{\Q...\E}{&hellip;}gs;
90 # $dump =~ $self->html_links( $dump ); # FIXME include this
91 return "<code>$dump</code>";
92 }
93
94 sub popup { my $self = shift; $self->popup_dropdown('popup', @_); }
95 sub dropdown { my $self = shift; $self->popup_dropdown('dropdown', @_); }
96
97 our $re_html = qr{<(?:!--|(\w+)|[^>]+)/?>}s; # relaxed html check for one semi-valid tag
98
99 sub popup_dropdown {
100 my ( $self, $type, $name, $content, $full ) = @_;
101
102 $content = $self->html_dump($content) if ref $content;
103
104 $content = qq|<span>$content</span>| unless $content =~ m{^\s*<(span|a|code).+?/\1>\s*};
105
106 $content =~ s{<span>(<code>[^<]+</code>)</span>}{$1} && $self->TODO("code wrapped in span");
107
108 warn "## $type [$name] = ", length( $content ), " bytes"; # if $self->debug; # FIXME
109
110 if ( $name =~ m{::} && $name !~ $re_html ) {
111 return qq|<a class="frey-$type" target="$name" href="/$name">$name $content</a>\n|;
112 } elsif ( $name =~ s{^\s*(<a)\s+}{$1 class="frey-$type"} ) {
113 return qq|$name $content\n|;
114 } else {
115 return qq|<span class="frey-$type">$name $content</span>\n|;
116 }
117 }
118
119 sub _inline_path_size {
120 my ( $self, $path ) = @_;
121 -s $path < $self->inline_smaller_than && -s $path;
122 }
123
124 sub _head_html {
125 my $self = shift;
126 my $out = '';
127 foreach my $path ( @head ) {
128 $path =~ s!^/!!;
129 my $size = $self->_inline_path_size( $path );
130 if ( $path =~ m/\.js$/ ) {
131 $out .= $size ?
132 qq|<script type="text/javascript">\n/* inline $path $size bytes */\n\n| . read_file($path) . qq|\n</script>| :
133 qq|<script type="text/javascript" src="/$path"></script>|;
134 } elsif ( $path =~ m/\.css$/ ) {
135 $out .= $size ?
136 qq|<style type="text/css">\n/* inline $path $size bytes */\n\n| . read_file( $path ) . qq|\n</style>| :
137 qq|<link type="text/css" rel="stylesheet" href="/$path" media="screen">|;
138 } elsif ( $path =~ m{<.+>}s ) {
139 $out .= $path;
140 } else {
141 confess "don't know how to render $path";
142 }
143 $out .= "\n";
144 }
145 return $out;
146 }
147
148 =head2 add_head
149
150 $o->add_head( 'path/to/external.js' );
151
152 my $size = $o->add_head( 'path/to/external.css' );
153
154 $o->add_head( '<!-- html content -->' );
155
156 =cut
157
158 sub add_head {
159 my ( $self, $path ) = @_;
160 return if ! defined $path || $path eq '';
161 $path =~ s!^/!!;
162
163 if ( $path =~ $re_html ) {
164 push @head, $path;
165 } elsif ( -e $path ) {
166 if ( $path =~ m/\.(?:js|css)$/ ) {
167 push @head, $path;
168 } else {
169 confess "can't add_head( $path ) it's not js or css";
170 }
171 return -s $path;
172 } else {
173 confess "can't find $path: $!";
174 }
175
176 }
177
178 sub _add_css_js {
179 my ( $self, $what, $content ) = @_;
180
181 my $tag = $what eq 'css' ? 'style' : 'script';
182 my $type = $what eq 'css' ? 'text/css' : 'text/javascript';
183 my $head;
184
185 my ( $package, $path, $line ) = caller(1);
186
187 if ( $content =~ m{\.(js|css)} ) {
188 $content = "/$content" if -e $content;
189 if ( $content =~ $re_html ) {
190 $head = qq|
191 $content
192 <!-- $type via $package at $path line $line -->
193 |;
194 } elsif ( $what eq 'js' ) {
195 $head = qq|
196 <$tag type="$type" src="$content">
197 /* $what via $package at $path line $line */
198 </$tag>
199 |;
200 } else {
201 $head = qq|
202 <link rel="stylesheet" type="$type" href="$content">
203 <!-- $what via $package at $path line $line -->
204 |;
205 }
206 } else {
207 $head = qq|
208 <$tag type="$type">
209 /* via $package at $path line $line */
210 $content
211 </$tag>
212 |;
213 };
214 $self->add_head( $head );
215 }
216
217 sub add_css {
218 my ($self,$css) = @_;
219 $self->_add_css_js( 'css', $css );
220 }
221
222 sub add_js {
223 my ($self,$js) = @_;
224 $self->_add_css_js( 'js', $js );
225 }
226
227 our $reload_counter = 0;
228
229
230 =head2 page
231
232 $self->page(
233 title => 'page title',
234 head => '<!-- optional head markup -->',
235 body => '<b>Page Body</b>',
236 );
237
238 =cut
239
240 our @status;
241 sub status { @status };
242
243 our $icon_html;
244
245 sub page {
246 my $self = shift;
247 my $a = {@_};
248
249 warn "## page ",dump($a);
250
251 $reload_counter++;
252
253 my $status_line = '';
254
255 foreach my $part ( @status ) {
256 foreach my $name ( keys %$part ) {
257 $status_line .= $self->popup( $name, $part->{$name} );
258 }
259 }
260
261 my $url = $self->request_url;
262 $url =~ s{\?reload=\d+}{};
263
264 my $body = $a->{body};
265 if ( ! $body ) {
266 my $run = $a->{run} || 'as_markup';
267 warn "# no body, invoke $self->$run on ", ref($self);
268 $body = $self->$run;
269 }
270 if ( $self->content_type !~ m{html} ) {
271 warn "# return only $self body ", $self->content_type;
272 return $body
273 } elsif ( ! defined $body ) {
274 warn "# no body";
275 $body = '<!-- no body -->';
276 }
277
278 $status_line .= $self->warnings_html;
279
280 my ($exit,$description) = ('exit','stop server');
281 ($exit,$description) = ('restart','restart server')
282 if $ENV{FREY_RESTART}; # tune labels on exit link
283
284 my $right =
285 qq|
286 <span class="right">
287 <a title="reload $url" href="/reload$url">reload</a>
288 <a title="$description" href="/exit$url" target="exit">$exit</a>
289 </span>
290 |;
291
292 my $svk = Frey::SVK->new;
293 my $info = $svk->info;
294 my $revision = $svk->info->{Revision} || '';
295 $revision = $1 if $info->{'Mirrored From'} =~ m{Rev\.\s+(\d+)};
296
297 $self->add_icon unless $icon_html;
298
299 my $html = join("\n",
300 qq|<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"><html><head>|,
301 $self->_head_html,
302 '<title>' . ( $self->title || $a->{title} || ref($self) ) . '</title>',
303 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
304 ( $icon_html || '<!-- no icon -->' ),
305 ( $a->{head} || '' ),
306 qq|
307 </head><body>
308 $body
309 <div class="frey-status-line">
310 <a href="/">Frey</a> $Frey::VERSION $revision
311 $status_line
312 $right
313 </div>
314 </body></html>
315 |,
316 );
317
318 warn "## >>> page ",length($html), " bytes\n" if $self->debug;
319
320 return $html;
321 }
322
323 =head2 editor
324
325 Create HTML editor link with optional line and title
326
327 my $html = $self->editor( $class, $line, $title );
328
329 =cut
330
331 sub editor {
332 my ( $self, $class, $line, $title ) = @_;
333 confess "need class" unless $class;
334 if ( ! defined $title ) {
335 $title = "edit $class";
336 $title .= " line $line" if $line;
337 }
338 $line ||= 1;
339 qq|<a target="editor" href="/editor+$class+$line"| .
340 ( $title ? qq| title="$title"| : '' ) .
341 qq|>$class</a>|;
342 }
343
344 =head2 html_links
345
346 Create HTML links to editor for perl error message
347
348 my $html = $self->html_links( $error )
349
350 =cut
351
352 sub html_links {
353 my ( $self, $error ) = @_;
354
355 $error = $self->strip_full_path( $error );
356
357 # $error =~ s[(bless\({\s+.+?\s+},\s+)("[^"]+")(\) at)][<span class="frey-dropdown">$1<code>$2</code>$3</span>]gs; # FIXME insert bless hiding back
358
359 # perl's backtrace
360 $error =~ s{at\s+(\S+)\s+line\s+(\d+)}
361 {at <a target="editor" href="/editor+$1+$2" title="vi $1 +$2">$1</a> line $2}gsm;
362
363 $error =~ s{(via (?:package)\s+"?)([\w:]+)("?)}
364 {$1<a target="$2" href="/$2" title="introspect $2">$2</a>$3}gsm
365 || # or anything that looks like "Class::Name"
366 $error =~ s{"(\w+(?:::\w+)+)"}
367 {"<a target="$1" href="/$1" title="introspect $1">$1</a>"}gsm;
368
369 # method error messages
370 # FIXME replace with link to Frey::Introspect data
371 $error =~ s{(method ")(\w+)(" via)}
372 {$1<a target="$2" href="/Frey::Shell::Grep/as_markup?pattern=$2" title="grep $2">$2</a>$3}gsm;
373
374 # link paths to editor
375 $error =~ s{((?:lib|t)/[\S]+)\s+(\d+\s+bytes)}
376 {<a target="editor" href="/editor+$1+1" title="vi $1 [$2]">$1</a>}gsm;
377
378 $error =~ s{(class ")([\w:]+)(")}
379 {$1<a target="$2" href="/$2" title="introspect $2">$2</a>$3}gsm;
380
381 return $error;
382 }
383
384 sub html_self {
385 my $self = shift;
386 my $html = $self;
387 $html =~ s{([\w:]+)=}{<a target="$1" href="/$1" title="introspect $1">$1</a>=}gsm;
388 return $html;
389 }
390
391 =head2 error
392
393 This method will return error to browser and backtrace unless
394 error message ends with LF C<\n> just like L<warn>
395
396 =cut
397
398 sub error {
399 my $self = shift;
400 my $error = join(" ", @_);
401
402 my $fatal = '';
403 my $backtrace = '';
404
405 if ( $error !~ m{\n$} ) {
406 if ( my @backtrace = $self->backtrace ) {
407 $backtrace =
408 "\n" . $self->html_self . "->error backtrace\n\t"
409 . $self->html_links( join( "\n\t", @backtrace ) )
410 ;
411 $fatal = qq| frey-fatal|;
412 }
413 }
414
415 warn "ERROR: $error\n";
416 $self->add_icon('error');
417 $error = $self->html_links( $error );
418 return qq|<pre class="frey-error$fatal">$error $backtrace</pre>| ;
419 }
420
421 =head1 Status line
422
423 =head2 add_status
424
425 $self->add_status( { name => { some => 'data' } } );
426
427 $self->add_status( "append to last status popup" );
428
429 =cut
430
431 sub add_status {
432 my ( $self, $data ) = @_;
433 push @status, { 'X' => [ $self->backtrace ] };
434 if ( ref($data) ) {
435 push @status, $data;
436 } else {
437 if ( defined $status[ $#status ] ) {
438 $status[ $#status ]->{ '+' } = $data;
439 } else {
440 push @status, { '+' => $data };
441 }
442 }
443 }
444
445 =head2 clean_status
446
447 Called at beginning of each request
448
449 $self->clean_status;
450
451 =cut
452
453 sub clean_status {
454 my ($self) = shift;
455 @head = ( 'static/frey.css' );
456 @status = (
457 { 'ClassBrowser' => Frey::Class::Browser->new( usage_sort => 1, usage_on_top => 0 )->as_markup },
458 { 'Bookmarklets' => Frey::Bookmarklet->new->as_markup },
459 { 'INC' => Frey::INC->new->as_markup },
460 );
461 $icon_html = '';
462 }
463
464 =head2 status_parts
465
466 Dump all status line parts
467
468 $self->status_parts
469
470 =cut
471
472 sub status_parts {
473 warn "## status parts ", dump( map { keys %$_ } @status );
474 }
475
476 =for debug
477
478 sub DEMOLISH {
479 my ( $self ) = @_;
480 warn "## $self DEMOLISH status ", $#status + 1, " elements ", dump( map { keys %$_ } @status ) if @status;
481 }
482
483 =cut
484
485 =head2 add_icon
486
487 Frey::Foo->add_icon; # /static/icons/Frey/Foo.png
488 Frey::Foo->add_icon('warning'); # /static/icons/Frey/Foo/warning.png
489
490 =cut
491
492 sub icon_path {
493 my ($self,$class,$variant) = @_;
494
495 sub icon_exists {
496 my $class = shift;
497 $class =~ s{::}{/}g;
498 $class .= "/$variant" if $variant;
499 my $icon_path = 'static/icons/' . $class . '.png';
500 return $icon_path if -e $icon_path;
501 return;
502 }
503
504 my $path = icon_exists( $class );
505 if ( ! $path ) {
506 my $super_class = $class;
507 while ( $super_class =~ s{::[^:]+$}{} && ! $path ) {
508 $path = icon_exists( $super_class ) unless $super_class eq 'Frey'; # don't default on Frey icon
509 }
510 }
511
512 if ( ! $path ) {
513 $self->TODO( "add icon for $class" . ( $variant ? " variant $variant" : '' ) );
514 return undef;
515 }
516
517 warn "# $class from $self icon_path $path" if $self->debug;
518 return $path;
519 }
520
521 sub add_icon {
522 my ($self,$variant) = @_;
523
524 my $class = $self->class if $self->can('class');
525 #$class ||= $self->title;
526 $class ||= ref($self);
527 my $icon_path = $self->icon_path( $class, $variant ) || return;
528
529 $icon_html .= qq|<link rel="icon" type="image/png" href="/$icon_path">|;
530 warn "# using icon $icon_path";
531
532 =for later
533
534 # FIXME http://en.wikipedia.org/wiki/Favicon suggest just rel="icon" but that doesn't seem to work!
535 my $ico_path = $icon_path;
536 $ico_path =~ s{png$}{ico};
537 if ( ! -e $ico_path ) {
538 system "convert $icon_path $ico_path";
539 warn "# convert $icon_path $ico_path : $@";
540 }
541 $icon_html .= qq|<link rel="shortcut icon" type="image/x-icon" href="/$ico_path">| if -e $ico_path;
542
543 =cut
544
545 }
546
547 my $warn_colors = {
548 '#' => '#444',
549 '##' => '#888',
550 };
551
552 my $multiline_markers = {
553 '(' => ')',
554 '{' => '}',
555 '[' => ']',
556 '"' => '"',
557 };
558
559 =for later
560
561 my $multiline_re = '[\\' . join('\\', keys %$multiline_markers ) . ']';
562 warn "## multiline markers ", dump( $multiline_markers ), " -> $multiline_re";
563
564 =cut
565
566 sub log_path {
567 $Frey::Bootstrap::log_path || die "no log_path?";
568 }
569
570 our $pwd = `pwd`;
571 chomp $pwd;
572
573 sub strip_full_path {
574 my ($self, $msg) = @_;
575 # Mojo seems to expand warn messages to full path which is annoying
576 $msg =~ s{/[^/]+/\.\./}{/}gs;
577 $msg =~ s{$pwd/*}{}gs;
578 return $msg;
579 }
580
581 our $last_log_pos = 0;
582 our $last_log_line = 0;
583
584 sub warnings_html {
585 my ($self,$level) = shift;
586 $level ||= $self->debug,
587 my $path = $self->log_path;
588
589 my $max = 30;
590 my $pos = 0;
591 my @warnings = ( '' x $max ); # XXX circualar buffer for 50 lines
592 my $line = $last_log_line;
593 my $multiline_end;
594
595 # XXX do we really want to do this every time?
596 my $css = qq|/* short css classes for levels */\n|;
597 my $level_to_class;
598 foreach ( keys %$warn_colors ) {
599 my $l = length($_);
600 my $class = 'l' . $l;
601 $css .= qq|.$class { color: $warn_colors->{$_} }\n|;
602 $level_to_class->{ $_ } = $class;
603 }
604 $self->add_css( $css );
605
606 open(my $log, '<', $path) || die "can't open $path: $!";
607 seek($log, $last_log_pos, 0) || warn "can't seek: $!";
608 while(<$log>) {
609 chomp;
610 $line++;
611
612 next if m{^\s+(Mojo|Class::MOP|Moose)::};
613
614 my $style = '';
615
616 =for filter
617
618 if ( $multiline_end ) {
619 if ( m{^\Q$multiline_end\E} || m{^\s.+\Q$multiline_end\E;$} ) {
620 # warn "## $line end of $multiline_end in '$_'\n";
621 undef $multiline_end;
622 } else {
623 # warn "## $line skipped\n";
624 }
625 } elsif ( m{^(#*)\s+} ) {
626 my $l = $1 ? length($1) : 0;
627 if ( $l > $level ) {
628 undef $multiline_end;
629 $multiline_end = $multiline_markers->{$1} if m{($multiline_re)$};
630 # warn "## $line start $1 .. $multiline_end level $l > $level for '$_'\n" if $multiline_end;
631 next;
632 }
633
634 =cut
635 if ( m{^(#*)} ) {
636
637 my $level = $1;
638 my $msg = $self->strip_full_path( $_ );
639
640 my $spacer = ' ';
641 my $real_msg = expand( $msg );
642 if ( length($real_msg) > $self->html_dump_width ) {
643
644 $real_msg = substr( $msg, 0, $self->html_dump_width );
645 $msg = unexpand( $real_msg );
646 $spacer = '&hellip;'
647 }
648
649 $msg = $self->html_escape( $msg );
650
651 if ( my $class = $level_to_class->{ $level } ) {
652 $msg = qq|<span class="$class">$msg</span>|;
653 }
654
655 #$msg .= $spacer . qq|<a target="editor" href="/editor+$path+$line" style="float: right;">$line</a>\n|;
656 $msg = qq|<a target="editor" href="/editor+$path+$line" style="float: right;">$line</a>$msg|
657 . ( $spacer ? $spacer : '' )
658 . "\n"; # XXX <pre> needs this
659
660 $warnings[ $pos++ % $max ] = $msg;
661 }
662 }
663 $last_log_pos = tell($log);
664 $last_log_line = $line;
665 warn "log has $line lines tell position $last_log_pos";
666 close($log) || die "can't close $path: $!";
667
668 my $size = -s $path;
669
670 my $warnings = join("",
671 map { $warnings[ ( $pos + $_ ) % $max ] || '' } 0 .. ( $max - 1 )
672 );
673
674 my $s = length($warnings);
675
676 return
677 # need to wrap editor link into span so we can have links in warnings
678 qq|<span class="frey-popup"><a target="editor" href="/editor+$path+$line" title="$path \| $size -> $s bytes \| $line -> $pos lines \| level $level">warn</a><code>|
679 . $self->html_links( $warnings )
680 . qq|</code></span>|
681 ;
682 }
683
684
685 =head2 backtrace
686
687 Show backtrace with links to editor
688
689 my @backtrace = $self->backtrace;
690
691 =cut
692
693 sub backtrace {
694 my ($self) = @_;
695
696 my @backtrace;
697 foreach ( 1 .. 5 ) { # 0 = backtrace
698 my (
699 $package,$path,$line
700 # subroutine hasargs
701 # wantarray evaltext is_require
702 # hints bitmask hinthash
703 ) = caller($_) or last;
704
705 push @backtrace,
706 qq|via "$package" at $path line $line|;
707 }
708 #warn "# backtrace: ", dump( @backtrace ) if @backtrace;
709 return @backtrace;
710 }
711
712 =head2 checkbox
713
714 Generate checkbox html markup from some attribute
715
716 my $html = $self->checkbox('attribute_name', $value);
717
718 =cut
719
720 sub checkbox {
721 my ($self,$name,$value) = @_;
722 my $checked = '';
723 my $all_checkboxes = eval { $self->$name };
724 warn "ERROR tried to get checkbox value for '$name' which is unknown: $@" if $@;
725 $all_checkboxes = [ $all_checkboxes ] unless ref($all_checkboxes) eq 'ARRAY'; # sigh, too chatty
726 $checked = ' checked' if grep { defined $_ && $_ eq $value } @$all_checkboxes;
727 warn "# checkbox $name $value $checked\t", $self->dump( $self->$name );
728 qq|<input name="$name" value="$value" type="checkbox"$checked>|;
729 }
730
731 =head2 strip
732
733 Strip whitespace around content
734
735 my $stripped = strip(' no more whitespace around this ');
736
737 =cut
738
739 sub strip {
740 my $t = shift;
741 $t =~ s{^\s+}{}gs;
742 $t =~ s{>\s+<}{><}gs;
743 $t =~ s{\s+$}{}gs;
744 return $t;
745 }
746
747 1;

  ViewVC Help
Powered by ViewVC 1.1.26