package Kwiki::CachedDisplay;
use Kwiki::Plugin -Base;
our $VERSION = '0.06';

const class_id => 'cached_display';

sub register {
    my $reg = shift;
    $reg->add(hook => 'display:display', pre  => 'check_cached');
}

sub check_cached {
    my $hook = pop;
    my $display = $self;
    $self = $display->hub->cached_display;
    my $page = $self->pages->current;
    return unless $page->exists;
    return if (defined $self->config->can('cached_display_ignore') and
	       grep {$page->id} @{$self->config->cached_display_ignore});
    my $html = io->catfile($self->plugin_directory,$page->id)->utf8;
    my $content;

    my $depup = 0;
    if (defined $self->config->can('cached_display_dependencies')){
	for (@{$self->config->cached_display_dependencies}){
	    my $deppage = $self->pages->new_page($_);
	    $depup = 1 if $deppage->modified_time > $html->mtime;
	}
    }

    if($depup or
       !$html->exists or
       ($page->modified_time > $html->mtime)) {
        my $code = $hook->code;
        $content = $code->($display);
        $html->print($content);
    }
    $content ||= $html->all;
    $hook->cancel;
    return $content;
}

__END__

=head1 NAME

  Kwiki::CachedDisplay - Speed-up Kwiki page display by caching

=head1 SYNOPSIS

  kwiki -add Kwiki::CachedDisplay

=head1 DESCRIPTION

This module use pre-generated page upon rendering, so that each
successive page-rendering takes no time in parsing and
template-processing. After you install this plugin, new pages will
automatically have pre-generated HTML copies on disk.  HTML copies for
old pages will be generated by next time anyone visit them.

If somehow you want to remove the generated HTML pages, they are under
C<plugin/cached_display> directory.

If there are some pages that you never want it to be cached, edit
your C<config.yaml> and add a new list called C<cached_display_ignore>.
For example:

    cached_display_ignore:
    - SandBox
    - HomePage

That would simply not cache SandBox and HomePage.

If you want to flush the cache if on the condition that one specific page in
the setup has changed, you can define the names of these special pages in

    cached_display_dependencies:
    - KwikiNavBar

This would mean that the cache would be invalidated whenever the KwikiNavBar
page is changed.

=head1 METHODS

=over

=item register

Kwiki Plugin registration routine.

=item check_cached

A pre hook routine of the display method in your display class (In most cases,
it is Kwiki::Display::display.) It checked whether the cache of the requested
page are out-of-dated or not, and regenerate it on necessary.

=back

=head1 COPYRIGHT

Copyright 2005 by Kang-min Liu <gugod@gugod.org>.

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

See <http://www.perl.com/perl/misc/Artistic.html>

=cut

