/[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 857 - (show annotations)
Tue Dec 16 14:10:09 2008 UTC (15 years, 4 months ago) by dpavlin
Original Path: trunk/lib/Frey/Web.pm
File size: 17094 byte(s)
display size of lined files
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+).+?/\1|[^>]+/?)>}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 ( $what eq 'js' ) {
190 $head = qq|
191 <$tag type="$type" src="$content">
192 /* via $package at $path line $line */
193 </$tag>
194 |;
195 } else {
196 $head = qq|
197 <link rel="stylesheet" type="$type" href="$content">
198 <!-- via $package at $path line $line -->
199 |;
200 }
201 } else {
202 $head = qq|
203 <$tag type="$type">
204 /* via $package at $path line $line */
205 $content
206 </$tag>
207 |;
208 };
209 $self->add_head( $head );
210 }
211
212 sub add_css {
213 my ($self,$css) = @_;
214 $self->_add_css_js( 'css', $css );
215 }
216
217 sub add_js {
218 my ($self,$js) = @_;
219 $self->_add_css_js( 'js', $js );
220 }
221
222 our $reload_counter = 0;
223
224
225 =head2 page
226
227 $self->page(
228 title => 'page title',
229 head => '<!-- optional head markup -->',
230 body => '<b>Page Body</b>',
231 );
232
233 =cut
234
235 our @status;
236 sub status { @status };
237
238 our $icon_html;
239
240 sub page {
241 my $self = shift;
242 my $a = {@_};
243
244 warn "## page ",dump($a);
245
246 $reload_counter++;
247
248 my $status_line = '';
249
250 foreach my $part ( @status ) {
251 foreach my $name ( keys %$part ) {
252 $status_line .= $self->popup( $name, $part->{$name} );
253 }
254 }
255
256 my $url = $self->request_url;
257 $url =~ s{\?reload=\d+}{};
258
259 my $body = $a->{body};
260 if ( ! $body ) {
261 my $run = $a->{run} || 'as_markup';
262 warn "# no body, invoke $self->$run on ", ref($self);
263 $body = $self->$run;
264 }
265 if ( $self->content_type !~ m{html} ) {
266 warn "# return only $self body ", $self->content_type;
267 return $body
268 } elsif ( ! defined $body ) {
269 warn "# no body";
270 $body = '<!-- no body -->';
271 }
272
273 $status_line .= $self->warnings_html;
274
275 my ($exit,$description) = ('exit','stop server');
276 ($exit,$description) = ('restart','restart server')
277 if $ENV{FREY_RESTART}; # tune labels on exit link
278
279 my $right =
280 qq|
281 <span class="right">
282 <a title="reload $url" href="/reload$url">reload</a>
283 <a title="$description" href="/exit$url" target="exit">$exit</a>
284 </span>
285 |;
286
287 my $svk = Frey::SVK->new;
288 my $info = $svk->info;
289 my $revision = $svk->info->{Revision} || '';
290 $revision = $1 if $info->{'Mirrored From'} =~ m{Rev\.\s+(\d+)};
291
292 $self->add_icon unless $icon_html;
293
294 my $html = join("\n",
295 qq|<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"><html><head>|,
296 $self->_head_html,
297 '<title>' . ( $self->title || $a->{title} || ref($self) ) . '</title>',
298 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
299 ( $icon_html || '<!-- no icon -->' ),
300 ( $a->{head} || '' ),
301 qq|
302 </head><body>
303 $body
304 <div class="frey-status-line">
305 <a href="/">Frey</a> $Frey::VERSION $revision
306 $status_line
307 $right
308 </div>
309 </body></html>
310 |,
311 );
312
313 warn "## >>> page ",length($html), " bytes\n" if $self->debug;
314
315 return $html;
316 }
317
318 =head2 editor
319
320 Create HTML editor link with optional line and title
321
322 my $html = $self->editor( $class, $line, $title );
323
324 =cut
325
326 sub editor {
327 my ( $self, $class, $line, $title ) = @_;
328 confess "need class" unless $class;
329 if ( ! defined $title ) {
330 $title = "edit $class";
331 $title .= " line $line" if $line;
332 }
333 $line ||= 1;
334 qq|<a target="editor" href="/editor+$class+$line"| .
335 ( $title ? qq| title="$title"| : '' ) .
336 qq|>$class</a>|;
337 }
338
339 =head2 html_links
340
341 Create HTML links to editor for perl error message
342
343 my $html = $self->html_links( $error )
344
345 =cut
346
347 sub html_links {
348 my ( $self, $error ) = @_;
349
350 $error = $self->strip_full_path( $error );
351
352 # $error =~ s[(bless\({\s+.+?\s+},\s+)("[^"]+")(\) at)][<span class="frey-dropdown">$1<code>$2</code>$3</span>]gs; # FIXME insert bless hiding back
353
354 # perl's backtrace
355 $error =~ s{at\s+(\S+)\s+line\s+(\d+)}
356 {at <a target="editor" href="/editor+$1+$2" title="vi $1 +$2">$1</a> line $2}gsm;
357
358 $error =~ s{(via (?:package)\s+"?)([\w:]+)("?)}
359 {$1<a target="$2" href="/$2" title="introspect $2">$2</a>$3}gsm
360 || # or anything that looks like "Class::Name"
361 $error =~ s{"(\w+(?:::\w+)+)"}
362 {"<a target="$1" href="/$1" title="introspect $1">$1</a>"}gsm;
363
364 # method error messages
365 # FIXME replace with link to Frey::Introspect data
366 $error =~ s{(method ")(\w+)(" via)}
367 {$1<a target="$2" href="/Frey::Shell::Grep/as_markup?pattern=$2" title="grep $2">$2</a>$3}gsm;
368
369 # link paths to editor
370 $error =~ s{((?:lib|t)/[\S]+)\s+(\d+\s+bytes)}
371 {<a target="editor" href="/editor+$1+1" title="vi $1 [$2]">$1</a>}gsm;
372
373 $error =~ s{(class ")([\w:]+)(")}
374 {$1<a target="$2" href="/$2" title="introspect $2">$2</a>$3}gsm;
375
376 return $error;
377 }
378
379 sub html_self {
380 my $self = shift;
381 my $html = $self;
382 $html =~ s{([\w:]+)=}{<a target="$1" href="/$1" title="introspect $1">$1</a>=}gsm;
383 return $html;
384 }
385
386 =head2 error
387
388 This method will return error to browser and backtrace unless
389 error message ends with LF C<\n> just like L<warn>
390
391 =cut
392
393 sub error {
394 my $self = shift;
395 my $error = join(" ", @_);
396
397 my $fatal = '';
398 my $backtrace = '';
399
400 if ( $error !~ m{\n$} ) {
401 if ( my @backtrace = $self->backtrace ) {
402 $backtrace =
403 "\n" . $self->html_self . "->error backtrace\n\t"
404 . $self->html_links( join( "\n\t", @backtrace ) )
405 ;
406 $fatal = qq| frey-fatal|;
407 }
408 }
409
410 warn "ERROR: $error\n";
411 $self->add_icon('error');
412 $error = $self->html_links( $error );
413 return qq|<pre class="frey-error$fatal">$error $backtrace</pre>| ;
414 }
415
416 =head1 Status line
417
418 =head2 add_status
419
420 $self->add_status( { name => { some => 'data' } } );
421
422 $self->add_status( "append to last status popup" );
423
424 =cut
425
426 sub add_status {
427 my ( $self, $data ) = @_;
428 push @status, { 'X' => [ $self->backtrace ] };
429 if ( ref($data) ) {
430 push @status, $data;
431 } else {
432 if ( defined $status[ $#status ] ) {
433 $status[ $#status ]->{ '+' } = $data;
434 } else {
435 push @status, { '+' => $data };
436 }
437 }
438 }
439
440 =head2 clean_status
441
442 Called at beginning of each request
443
444 $self->clean_status;
445
446 =cut
447
448 sub clean_status {
449 my ($self) = shift;
450 @head = ( 'static/frey.css' );
451 @status = (
452 { 'ClassBrowser' => Frey::Class::Browser->new( usage_sort => 1, usage_on_top => 0 )->as_markup },
453 { 'Bookmarklets' => Frey::Bookmarklet->new->as_markup },
454 { 'INC' => Frey::INC->new->as_markup },
455 );
456 $icon_html = '';
457 }
458
459 =head2 status_parts
460
461 Dump all status line parts
462
463 $self->status_parts
464
465 =cut
466
467 sub status_parts {
468 warn "## status parts ", dump( map { keys %$_ } @status );
469 }
470
471 =for debug
472
473 sub DEMOLISH {
474 my ( $self ) = @_;
475 warn "## $self DEMOLISH status ", $#status + 1, " elements ", dump( map { keys %$_ } @status ) if @status;
476 }
477
478 =cut
479
480 =head2 add_icon
481
482 Frey::Foo->add_icon; # /static/icons/Frey/Foo.png
483 Frey::Foo->add_icon('warning'); # /static/icons/Frey/Foo/warning.png
484
485 =cut
486
487 sub icon_path {
488 my ($self,$class,$variant) = @_;
489
490 sub icon_exists {
491 my $class = shift;
492 $class =~ s{::}{/}g;
493 $class .= "/$variant" if $variant;
494 my $icon_path = 'static/icons/' . $class . '.png';
495 return $icon_path if -e $icon_path;
496 return;
497 }
498
499 my $path = icon_exists( $class );
500 if ( ! $path ) {
501 my $super_class = $class;
502 while ( $super_class =~ s{::[^:]+$}{} && ! $path ) {
503 $path = icon_exists( $super_class ) unless $super_class eq 'Frey'; # don't default on Frey icon
504 }
505 }
506
507 if ( ! $path ) {
508 $self->TODO( "add icon for $class" . ( $variant ? " variant $variant" : '' ) );
509 return undef;
510 }
511
512 warn "# $class from $self icon_path $path" if $self->debug;
513 return $path;
514 }
515
516 sub add_icon {
517 my ($self,$variant) = @_;
518
519 my $class = $self->class if $self->can('class');
520 #$class ||= $self->title;
521 $class ||= ref($self);
522 my $icon_path = $self->icon_path( $class, $variant ) || return;
523
524 $icon_html .= qq|<link rel="icon" type="image/png" href="/$icon_path">|;
525 warn "# using icon $icon_path";
526
527 =for later
528
529 # FIXME http://en.wikipedia.org/wiki/Favicon suggest just rel="icon" but that doesn't seem to work!
530 my $ico_path = $icon_path;
531 $ico_path =~ s{png$}{ico};
532 if ( ! -e $ico_path ) {
533 system "convert $icon_path $ico_path";
534 warn "# convert $icon_path $ico_path : $@";
535 }
536 $icon_html .= qq|<link rel="shortcut icon" type="image/x-icon" href="/$ico_path">| if -e $ico_path;
537
538 =cut
539
540 }
541
542 my $warn_colors = {
543 '#' => '#444',
544 '##' => '#888',
545 };
546
547 my $multiline_markers = {
548 '(' => ')',
549 '{' => '}',
550 '[' => ']',
551 '"' => '"',
552 };
553
554 =for later
555
556 my $multiline_re = '[\\' . join('\\', keys %$multiline_markers ) . ']';
557 warn "## multiline markers ", dump( $multiline_markers ), " -> $multiline_re";
558
559 =cut
560
561 sub log_path {
562 $Frey::Bootstrap::log_path || die "no log_path?";
563 }
564
565 our $pwd = `pwd`;
566 chomp $pwd;
567
568 sub strip_full_path {
569 my ($self, $msg) = @_;
570 # Mojo seems to expand warn messages to full path which is annoying
571 $msg =~ s{/[^/]+/\.\./}{/}gs;
572 $msg =~ s{$pwd/*}{}gs;
573 return $msg;
574 }
575
576 our $last_log_pos = 0;
577 our $last_log_line = 0;
578
579 sub warnings_html {
580 my ($self,$level) = shift;
581 $level ||= $self->debug,
582 my $path = $self->log_path;
583
584 my $max = 30;
585 my $pos = 0;
586 my @warnings = ( '' x $max ); # XXX circualar buffer for 50 lines
587 my $line = $last_log_line;
588 my $multiline_end;
589
590 # XXX do we really want to do this every time?
591 my $css = qq|/* short css classes for levels */\n|;
592 my $level_to_class;
593 foreach ( keys %$warn_colors ) {
594 my $l = length($_);
595 my $class = 'l' . $l;
596 $css .= qq|.$class { color: $warn_colors->{$_} }\n|;
597 $level_to_class->{ $_ } = $class;
598 }
599 $self->add_css( $css );
600
601 open(my $log, '<', $path) || die "can't open $path: $!";
602 seek($log, $last_log_pos, 0) || warn "can't seek: $!";
603 while(<$log>) {
604 chomp;
605 $line++;
606
607 next if m{^\s+(Mojo|Class::MOP|Moose)::};
608
609 my $style = '';
610
611 =for filter
612
613 if ( $multiline_end ) {
614 if ( m{^\Q$multiline_end\E} || m{^\s.+\Q$multiline_end\E;$} ) {
615 # warn "## $line end of $multiline_end in '$_'\n";
616 undef $multiline_end;
617 } else {
618 # warn "## $line skipped\n";
619 }
620 } elsif ( m{^(#*)\s+} ) {
621 my $l = $1 ? length($1) : 0;
622 if ( $l > $level ) {
623 undef $multiline_end;
624 $multiline_end = $multiline_markers->{$1} if m{($multiline_re)$};
625 # warn "## $line start $1 .. $multiline_end level $l > $level for '$_'\n" if $multiline_end;
626 next;
627 }
628
629 =cut
630 if ( m{^(#*)} ) {
631
632 my $level = $1;
633 my $msg = $self->strip_full_path( $_ );
634
635 my $spacer = ' ';
636 my $real_msg = expand( $msg );
637 if ( length($real_msg) > $self->html_dump_width ) {
638
639 $real_msg = substr( $msg, 0, $self->html_dump_width );
640 $msg = unexpand( $real_msg );
641 $spacer = '&hellip;'
642 }
643
644 $msg = $self->html_escape( $msg );
645
646 if ( my $class = $level_to_class->{ $level } ) {
647 $msg = qq|<span class="$class">$msg</span>|;
648 }
649
650 #$msg .= $spacer . qq|<a target="editor" href="/editor+$path+$line" style="float: right;">$line</a>\n|;
651 $msg = qq|<a target="editor" href="/editor+$path+$line" style="float: right;">$line</a>$msg|
652 . ( $spacer ? $spacer : '' )
653 . "\n"; # XXX <pre> needs this
654
655 $warnings[ $pos++ % $max ] = $msg;
656 }
657 }
658 $last_log_pos = tell($log);
659 $last_log_line = $line;
660 warn "log has $line lines tell position $last_log_pos";
661 close($log) || die "can't close $path: $!";
662
663 my $size = -s $path;
664
665 my $warnings = join("",
666 map { $warnings[ ( $pos + $_ ) % $max ] || '' } 0 .. ( $max - 1 )
667 );
668
669 my $s = length($warnings);
670
671 return
672 # need to wrap editor link into span so we can have links in warnings
673 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>|
674 . $self->html_links( $warnings )
675 . qq|</code></span>|
676 ;
677 }
678
679
680 =head2 backtrace
681
682 Show backtrace with links to editor
683
684 my @backtrace = $self->backtrace;
685
686 =cut
687
688 sub backtrace {
689 my ($self) = @_;
690
691 my @backtrace;
692 foreach ( 1 .. 5 ) { # 0 = backtrace
693 my (
694 $package,$path,$line
695 # subroutine hasargs
696 # wantarray evaltext is_require
697 # hints bitmask hinthash
698 ) = caller($_) or last;
699
700 push @backtrace,
701 qq|via "$package" at $path line $line|;
702 }
703 #warn "# backtrace: ", dump( @backtrace ) if @backtrace;
704 return @backtrace;
705 }
706
707 =head2 checkbox
708
709 Generate checkbox html markup from some attribute
710
711 my $html = $self->checkbox('attribute_name', $value);
712
713 =cut
714
715 sub checkbox {
716 my ($self,$name,$value) = @_;
717 my $checked = '';
718 my $all_checkboxes = eval { $self->$name };
719 warn "ERROR tried to get checkbox value for '$name' which is unknown: $@" if $@;
720 $all_checkboxes = [ $all_checkboxes ] unless ref($all_checkboxes) eq 'ARRAY'; # sigh, too chatty
721 $checked = ' checked' if grep { defined $_ && $_ eq $value } @$all_checkboxes;
722 warn "# checkbox $name $value $checked\t", $self->dump( $self->$name );
723 qq|<input name="$name" value="$value" type="checkbox"$checked>|;
724 }
725
726 =head2 strip
727
728 Strip whitespace around content
729
730 my $stripped = strip(' no more whitespace around this ');
731
732 =cut
733
734 sub strip {
735 my $t = shift;
736 $t =~ s{^\s+}{}gs;
737 $t =~ s{>\s+<}{><}gs;
738 $t =~ s{\s+$}{}gs;
739 return $t;
740 }
741
742 1;

  ViewVC Help
Powered by ViewVC 1.1.26