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

  ViewVC Help
Powered by ViewVC 1.1.26