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

  ViewVC Help
Powered by ViewVC 1.1.26