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

  ViewVC Help
Powered by ViewVC 1.1.26