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

  ViewVC Help
Powered by ViewVC 1.1.26