/[Frey]/trunk/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 /trunk/lib/Frey/Web.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.26