repo
string
commit
string
message
string
diff
string
briang/MooseX-PrivateSetters
c55122727d1aecd1a552e9a8aa99e7e0884a1010
Bump version to 0.02
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index a17882d..76be9dc 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,107 +1,107 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.01'; +our $VERSION = '0.02'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<<_set_>>. If you define an attribute with a leading underscore, then the set method will start with C<<_set_>>. If you explicitly set a C<<reader>> or C<<writer>> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<<use>>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method with the same name as the attribute itself =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<<is>> clause, making new options available. For example, has baz => ( is => 'rpwp', # is private reader, is private writer gets you C<<_get_baz()>> and C<<_set_baz>>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<<get_size>> and C<<set_size>>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<<set_>>. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index ef758a6..25927ab 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.01'; +our $VERSION = '0.02'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
f07f160a8d9225425f31423b2bdaea96374266c9
Code reformatting
diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 62b0512..ef758a6 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,80 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; our $VERSION = '0.01'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && - ! ( exists $options->{reader} || exists $options->{writer} ) ) - { - if ( $options->{is} eq 'ro' ) - { + ! ( exists $options->{reader} || exists $options->{writer} ) ) { + if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; - delete $options->{is}; } - elsif ( $options->{is} eq 'rw' ) - { + elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/t/basic.t b/t/basic.t index e30125c..2913745 100644 --- a/t/basic.t +++ b/t/basic.t @@ -1,96 +1,96 @@ use strict; use warnings; #use FindBin; #use lib "$FindBin::Bin/../lib"; #use Data::Dump 'pp'; use Test::More tests => 23; { package Standard; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } -ok( Standard->can('thing'), 'Standard->thing() exists' ); -ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); -ok( Standard->can('_private'), 'Standard->_private() exists' ); +ok( Standard->can('thing'), 'Standard->thing() exists' ); +ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); +ok( Standard->can('_private'), 'Standard->_private() exists' ); ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); { package PS; use Moose; use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } -ok( PS->can('thing'), 'PS->thing() exists' ); -ok( PS->can('_set_thing'), 'PS->set_thing() exists' ); -ok( PS->can('_private'), 'PS->_private() exists' ); +ok( PS->can('thing'), 'PS->thing() exists' ); +ok( PS->can('_set_thing'), 'PS->set_thing() exists' ); +ok( PS->can('_private'), 'PS->_private() exists' ); ok( PS->can('_set_private'), 'PS->_set_private() exists' ); { package PS2; # load order does matter use Moose; use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } -ok( PS2->can('thing'), 'PS2->thing() exists' ); -ok( PS2->can('_set_thing'), 'PS2->set_thing() exists' ); -ok( PS2->can('_private'), 'PS2->_private() exists' ); +ok( PS2->can('thing'), 'PS2->thing() exists' ); +ok( PS2->can('_set_thing'), 'PS2->set_thing() exists' ); +ok( PS2->can('_private'), 'PS2->_private() exists' ); ok( PS2->can('_set_private'), 'PS2->_set_private() exists' ); { package PS3; use Moose; use MooseX::PrivateSetters; - has 'ro' => ( is => 'ro' ); - has 'thing' => ( is => 'rw', reader => 'get_thing' ); + has 'ro' => ( is => 'ro' ); + has 'thing' => ( is => 'rw', reader => 'get_thing' ); has 'thing2' => ( is => 'rw', writer => 'set_it' ); } -ok( PS3->can('ro'), 'PS3->ro exists' ); -ok( ! PS3->can('set_ro'), 'PS3->set_ro does not exist' ); -ok( PS3->can('thing'), 'PS3->thing exists' ); -ok( ! PS3->can('set_thing'), 'PS3->set_thing does not exist' ); -ok( PS3->can('thing2'), 'PS3->thing2 exists' ); +ok( PS3->can('ro'), 'PS3->ro exists' ); +ok( ! PS3->can('set_ro'), 'PS3->set_ro does not exist' ); +ok( PS3->can('thing'), 'PS3->thing exists' ); +ok( ! PS3->can('set_thing'), 'PS3->set_thing does not exist' ); +ok( PS3->can('thing2'), 'PS3->thing2 exists' ); ok( ! PS3->can('set_thing2'), 'PS3->set_thing2 does not exist' ); -ok( PS3->can('set_it'), 'PS3->set_it does exist' ); +ok( PS3->can('set_it'), 'PS3->set_it does exist' ); { package PS4; use Moose; use MooseX::PrivateSetters; has bare => ( is => 'bare' ); } -ok( ! PS4->can('bare'), 'PS4->bare does not exist' ); +ok( ! PS4->can('bare'), 'PS4->bare does not exist' ); ok( ! PS4->can('set_bare'), 'PS4->set_bare does not exist' ); { package PS5; use Moose; use MooseX::PrivateSetters; has '__private' => ( is => 'rw' ); } ok( PS5->can('__private'), 'PS5->__private exists' ); ok( PS5->can('_set__private'), 'PS5->_set__private exists' );
briang/MooseX-PrivateSetters
61b04f2d78b40c88aa749e6c2a4f993859feb9ec
Improve documentation
diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 300c5c1..62b0512 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,80 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; our $VERSION = '0.01'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with -an explicit 'set'. Getters are left unchanged. This role copes with -attributes intended to be private (ie, starts with an underscore), -with no double-underscore in the setter. +an explicit '_set_attr' method. Getters are left unchanged. This role +copes with attributes intended to be private (ie, starts with an +underscore), with no double-underscore in the setter. For example: - | Code | Reader | Writer | - |--------------------------+--------+------------| - | has 'baz' => (is 'rw'); | baz() | _set_baz() | - | has 'baz' => (is 'ro'); | baz() | | - | has '_baz' => (is 'rw'); | _baz() | _set_baz() | + | Code | Reader | Writer | + |---------------------------+--------+-------------| + | has 'baz' => (is 'rw'); | baz() | _set_baz() | + | has 'baz' => (is 'ro'); | baz() | | + | has '_baz' => (is 'rw'); | _baz() | _set_baz() | + | has '__baz' => (is 'rw'); | _baz() | _set__baz() | + +You probably don't want to use this module. You probably should be +looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
e1bb0237710c1dffbebf326bda78b3a414b50619
Modernise by using class_metaroles in Moose::Exporter->setup_import_methods
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 5cf4028..a17882d 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,80 +1,107 @@ package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.01'; -use Moose 0.84 (); +use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; -# The main reason to use this is to ensure that we get the right value -# in $p{for_class} later. -Moose::Exporter->setup_import_methods(); - -sub init_meta -{ - shift; - my %p = @_; - - Moose->init_meta(%p); - - return - Moose::Util::MetaRole::apply_metaclass_roles - ( for_class => $p{for_class}, - attribute_metaclass_roles => - ['MooseX::PrivateSetters::Role::Attribute'], - ); -} +Moose::Exporter->setup_import_methods( + class_metaroles => { + attribute => ['MooseX::PrivateSetters::Role::Attribute'], + }, +); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS - use MooseX::PrivateSetters; use Moose; + use MooseX::PrivateSetters; # make some attributes + has 'foo' => ( is => 'rw' ); + + ... + + sub bar { + $self = shift; + $self->_set_foo(1) unless $self->foo + } + =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name -as the accessor, while set methods are prefixed with "_set_". +as the accessor, while set methods are prefixed with C<<_set_>>. If you define an attribute with a leading underscore, then the set -method will start with "_set_". +method will start with C<<_set_>>. + +If you explicitly set a C<<reader>> or C<<writer>> name when creating +an attribute, then that attribute's naming scheme is left unchanged. + +Load order of this module is important. It must be C<<use>>d after +L<Moose>. + +=head1 SEE ALSO + +There are a number of similar modules on the CPAN. + +=head2 L<Moose> + +The original. A single mutator method with the same name as the +attribute itself + +=head2 L<MooseX::Accessors::ReadWritePrivate> + +Changes the parsing of the C<<is>> clause, making new options +available. For example, + + has baz => ( is => 'rpwp', # is private reader, is private writer + +gets you C<<_get_baz()>> and C<<_set_baz>>. + +=head2 L<MooseX::FollowPBP> + +Names accessors in the style recommended by I<Perl Best Practices>: +C<<get_size>> and C<<set_size>>. + +=head2 L<MooseX::SemiAffordanceAccsessor> -If you explicitly set a "reader" or "writer" name when creating an -attribute, then that attribute's naming scheme is left unchanged. +Has separate methods for getting and setting. The getter has the same +name as the attribute, and the setter is prefixed with C<<set_>>. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface -at L<http://rt.cpan.org>. I will be notified, and then you'll +at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index cf33692..300c5c1 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; our $VERSION = '0.01'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS - Moose::Util::MetaRole::apply_metaclass_roles - ( for_class => $p{for_class}, - attribute_metaclass_roles => - ['MooseX::PrivateSetters::Role::Attribute'], - ); + Moose::Exporter->setup_import_methods( + class_metaroles => { + attribute => ['MooseX::PrivateSetters::Role::Attribute'], + }, + ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit 'set'. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |--------------------------+--------+------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/t/basic.t b/t/basic.t index e68a6d2..e30125c 100644 --- a/t/basic.t +++ b/t/basic.t @@ -1,96 +1,96 @@ use strict; use warnings; #use FindBin; #use lib "$FindBin::Bin/../lib"; #use Data::Dump 'pp'; use Test::More tests => 23; { package Standard; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( Standard->can('thing'), 'Standard->thing() exists' ); ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); ok( Standard->can('_private'), 'Standard->_private() exists' ); ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); { package PS; - use MooseX::PrivateSetters; use Moose; + use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( PS->can('thing'), 'PS->thing() exists' ); ok( PS->can('_set_thing'), 'PS->set_thing() exists' ); ok( PS->can('_private'), 'PS->_private() exists' ); ok( PS->can('_set_private'), 'PS->_set_private() exists' ); { package PS2; - # Make sure load order doesn't matter + # load order does matter use Moose; use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( PS2->can('thing'), 'PS2->thing() exists' ); ok( PS2->can('_set_thing'), 'PS2->set_thing() exists' ); ok( PS2->can('_private'), 'PS2->_private() exists' ); ok( PS2->can('_set_private'), 'PS2->_set_private() exists' ); { package PS3; use Moose; use MooseX::PrivateSetters; has 'ro' => ( is => 'ro' ); has 'thing' => ( is => 'rw', reader => 'get_thing' ); has 'thing2' => ( is => 'rw', writer => 'set_it' ); } ok( PS3->can('ro'), 'PS3->ro exists' ); ok( ! PS3->can('set_ro'), 'PS3->set_ro does not exist' ); ok( PS3->can('thing'), 'PS3->thing exists' ); ok( ! PS3->can('set_thing'), 'PS3->set_thing does not exist' ); ok( PS3->can('thing2'), 'PS3->thing2 exists' ); ok( ! PS3->can('set_thing2'), 'PS3->set_thing2 does not exist' ); ok( PS3->can('set_it'), 'PS3->set_it does exist' ); { package PS4; use Moose; use MooseX::PrivateSetters; has bare => ( is => 'bare' ); } ok( ! PS4->can('bare'), 'PS4->bare does not exist' ); ok( ! PS4->can('set_bare'), 'PS4->set_bare does not exist' ); { package PS5; use Moose; use MooseX::PrivateSetters; has '__private' => ( is => 'rw' ); } ok( PS5->can('__private'), 'PS5->__private exists' ); ok( PS5->can('_set__private'), 'PS5->_set__private exists' );
briang/MooseX-PrivateSetters
f7f0057effc3cbe362e46c6e2cc076b0f443b5cb
Add tests for attributes starting with double underscore
diff --git a/t/basic.t b/t/basic.t index ed2167b..e68a6d2 100644 --- a/t/basic.t +++ b/t/basic.t @@ -1,84 +1,96 @@ use strict; use warnings; #use FindBin; #use lib "$FindBin::Bin/../lib"; #use Data::Dump 'pp'; -use Test::More tests => 21; +use Test::More tests => 23; { package Standard; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( Standard->can('thing'), 'Standard->thing() exists' ); ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); ok( Standard->can('_private'), 'Standard->_private() exists' ); ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); { package PS; use MooseX::PrivateSetters; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( PS->can('thing'), 'PS->thing() exists' ); ok( PS->can('_set_thing'), 'PS->set_thing() exists' ); ok( PS->can('_private'), 'PS->_private() exists' ); ok( PS->can('_set_private'), 'PS->_set_private() exists' ); { package PS2; # Make sure load order doesn't matter use Moose; use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } ok( PS2->can('thing'), 'PS2->thing() exists' ); ok( PS2->can('_set_thing'), 'PS2->set_thing() exists' ); ok( PS2->can('_private'), 'PS2->_private() exists' ); ok( PS2->can('_set_private'), 'PS2->_set_private() exists' ); { package PS3; use Moose; use MooseX::PrivateSetters; has 'ro' => ( is => 'ro' ); has 'thing' => ( is => 'rw', reader => 'get_thing' ); has 'thing2' => ( is => 'rw', writer => 'set_it' ); } ok( PS3->can('ro'), 'PS3->ro exists' ); ok( ! PS3->can('set_ro'), 'PS3->set_ro does not exist' ); ok( PS3->can('thing'), 'PS3->thing exists' ); ok( ! PS3->can('set_thing'), 'PS3->set_thing does not exist' ); ok( PS3->can('thing2'), 'PS3->thing2 exists' ); ok( ! PS3->can('set_thing2'), 'PS3->set_thing2 does not exist' ); ok( PS3->can('set_it'), 'PS3->set_it does exist' ); { package PS4; use Moose; use MooseX::PrivateSetters; has bare => ( is => 'bare' ); } ok( ! PS4->can('bare'), 'PS4->bare does not exist' ); ok( ! PS4->can('set_bare'), 'PS4->set_bare does not exist' ); + +{ + package PS5; + + use Moose; + use MooseX::PrivateSetters; + + has '__private' => ( is => 'rw' ); +} + +ok( PS5->can('__private'), 'PS5->__private exists' ); +ok( PS5->can('_set__private'), 'PS5->_set__private exists' );
briang/MooseX-PrivateSetters
4aa74bf8b0b65d1dae6b8f9cc628b3705ebda127
Bump Moose prereq to 0.94, add repository
diff --git a/Build.PL b/Build.PL index 6b6d49c..68bc550 100644 --- a/Build.PL +++ b/Build.PL @@ -1,21 +1,23 @@ use strict; use warnings; require 5.00601; use Module::Build; -my $builder = Module::Build->new - ( module_name => 'MooseX::PrivateSetters', - license => 'perl', - requires => { 'Moose' => '0.84', - }, - build_requires => { 'Test::More' => '0', - }, - configure_requires => { 'Module::Build' => '0', - }, - create_makefile_pl => 'traditional', - create_readme => 1, - ); +my $builder = Module::Build->new( + build_requires => { 'Test::More' => '0', }, + configure_requires => { 'Module::Build' => '0', }, + create_makefile_pl => 'traditional', + create_readme => 1, + license => 'perl', + meta_merge => { + resources => { + repository => 'http://github.com/briang/MooseX-PrivateSetters' + } + }, + module_name => 'MooseX::PrivateSetters', + requires => { 'Moose' => '0.94', }, +); $builder->create_build_script();
briang/MooseX-PrivateSetters
7674154b0739bb2b1263426cfba48f1ca7ca5ed5
add TODO.org
diff --git a/TODO.org b/TODO.org new file mode 100644 index 0000000..07ae6cb --- /dev/null +++ b/TODO.org @@ -0,0 +1,10 @@ +* Documentation +*** RATIONALE + - sick of writing reader=>'...', writer=>'...' +*** SEE ALSO + - Moose + - Similar MooseX extensions +* Code + - Modernise as per SemiAffordanceAccsessor etc + - Study MooseX::Accessors::ReadWritePrivate and perhaps implement + (steal) his ideas
briang/MooseX-PrivateSetters
8a91d95dc7cdc2335a24ec1d1785200cd2540c2a
add .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*~
briang/MooseX-PrivateSetters
b95922de136411fa0b95daf43d9c260a1f74e7b8
lib/MooseX/PrivateSetters/Role/Attribute.pm: Add $VERSION
diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 7aeab9e..cf33692 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,74 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; +our $VERSION = '0.01'; + use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Util::MetaRole::apply_metaclass_roles ( for_class => $p{for_class}, attribute_metaclass_roles => ['MooseX::PrivateSetters::Role::Attribute'], ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit 'set'. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |--------------------------+--------+------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
d85c929e79cf0a99a8b8b1f0408d973427d28c53
Added an INSTALL file
diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..cc95a06 --- /dev/null +++ b/INSTALL @@ -0,0 +1,25 @@ +INSTALLATION +============ + +This distribution may be installed via one of the following methods: + +1 Using Module::Build (distributed with Perl since perl-5.9.4): + + perl Build.PL + perl Build + perl Build test + perl Build install + + This is cross platform as long as you have a recent enough perl. + +2 Using ExtUtils::MakeMaker (distributed with Perl since perl-5): + + perl Makefile.PL + make + make test + make install + + If you are on a Windows machine you should use 'nmake' or 'dmake' + rather than 'make'. Or, so I'm told + +If you are unsure, go with the first option.
briang/MooseX-PrivateSetters
1ec2df557d9a35c8456a34e8e0a9960a1dbcd043
Remove all references to SemiAffordance::Accessors from lib/MooseX/PrivateSetters.pm
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 631c8f3..5cf4028 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,84 +1,80 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.05'; +our $VERSION = '0.01'; use Moose 0.84 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; # The main reason to use this is to ensure that we get the right value # in $p{for_class} later. Moose::Exporter->setup_import_methods(); sub init_meta { shift; my %p = @_; Moose->init_meta(%p); return Moose::Util::MetaRole::apply_metaclass_roles ( for_class => $p{for_class}, attribute_metaclass_roles => ['MooseX::PrivateSetters::Role::Attribute'], ); } 1; __END__ =pod =head1 NAME -MooseX::PrivateSetters - Name your accessors foo() and set_foo() +MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS use MooseX::PrivateSetters; use Moose; # make some attributes =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name -as the accessor, while set methods are prefixed with "set_". +as the accessor, while set methods are prefixed with "_set_". If you define an attribute with a leading underscore, then the set method will start with "_set_". If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. -The name "semi-affordance" comes from David Wheeler's Class::Meta -module. - =head1 AUTHOR -Dave Rolsky, C<< <[email protected]> >> +brian greenfield, C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to -C<[email protected]>, or through -the web interface at L<http://rt.cpan.org>. I will be notified, and -then you'll automatically be notified of progress on your bug as I -make changes. +C<[email protected]>, or through the web interface +at L<http://rt.cpan.org>. I will be notified, and then you'll +automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE -Copyright 2007-2008 Dave Rolsky, All Rights Reserved. +Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
briang/MooseX-PrivateSetters
643d9ef05ab5bc851d6054df3a2654d7af9a1419
Fix Changes
diff --git a/Changes b/Changes index e7bb9ae..fc91e7c 100644 --- a/Changes +++ b/Changes @@ -1,31 +1,5 @@ -0.05 2009-07-15 +0.01 2010-07-15 -- Now requires Moose 0.84 to prevent test failures. + Initial release - -0.04 2009-07-09 - -- This module unconditionally deleted the "is" parameter, which meant - it broke any use of "is => 'bare'". Reported by Jerome Quelin. Fixed - by Jesse Luehrs. RT #47711. - - -0.03 2008-08-30 - -- Renamed to MooseX::SemiAffordanceAccessor because it no longer - requires the Moose::Policy module. Instead it uses - Moose::Util::MetaRole. - - -0.02 2007-11-15 - -- Require 5.6.1 in the Build.PL. - -- Added missing Moose & Moose::Policy prereqs. - -- No code changes. - - -0.01 2007-11-14 - -- First version, released on an unsuspecting world. + - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05
briang/MooseX-PrivateSetters
d153c150e26803dc14869342238d59ce0254f310
Fix Build.PL
diff --git a/Build.PL b/Build.PL index ec80cc1..6b6d49c 100644 --- a/Build.PL +++ b/Build.PL @@ -1,20 +1,21 @@ use strict; use warnings; require 5.00601; use Module::Build; my $builder = Module::Build->new - ( module_name => 'MooseX::SemiAffordanceAccessor', + ( module_name => 'MooseX::PrivateSetters', license => 'perl', requires => { 'Moose' => '0.84', }, build_requires => { 'Test::More' => '0', }, - create_makefile_pl => 'passthrough', + configure_requires => { 'Module::Build' => '0', + }, + create_makefile_pl => 'traditional', create_readme => 1, - sign => 1, ); $builder->create_build_script();
briang/MooseX-PrivateSetters
7444a92681d092d2cdffd71a8c1614ad62b7b810
Fix tests - all tests passing
diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 14505a7..7aeab9e 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,73 +1,74 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; use Moose::Role; - -before '_process_options' => sub -{ +before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; + delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; + my $prefix = $name =~ /^_/ ? '_set' : '_set_'; + $options->{writer} = $prefix . $name; - my $prefix = 'set'; - if ( $name =~ s/^_// ) - { - $prefix = '_set'; - } - - $options->{writer} = $prefix . q{_} . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME -MooseX::PrivateSetters::Role::Attribute - Names accessors in a semi-affordance style +MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Util::MetaRole::apply_metaclass_roles ( for_class => $p{for_class}, attribute_metaclass_roles => ['MooseX::PrivateSetters::Role::Attribute'], ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> -method, and tweaks the reader and writer parameters so that they -follow the semi-affordance naming style. +method, and tweaks the writer parameters so that they are private with +an explicit 'set'. Getters are left unchanged. This role copes with +attributes intended to be private (ie, starts with an underscore), +with no double-underscore in the setter. + +For example: + + | Code | Reader | Writer | + |--------------------------+--------+------------| + | has 'baz' => (is 'rw'); | baz() | _set_baz() | + | has 'baz' => (is 'ro'); | baz() | | + | has '_baz' => (is 'rw'); | _baz() | _set_baz() | =head1 AUTHOR -Dave Rolsky, C<< <[email protected]> >> +brian greenfield, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE -Copyright 2007-2008 Dave Rolsky, All Rights Reserved. +Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. - -=cut - diff --git a/t/basic.t b/t/basic.t index 5075cab..ed2167b 100644 --- a/t/basic.t +++ b/t/basic.t @@ -1,84 +1,84 @@ use strict; use warnings; -use FindBin; use lib "$FindBin::Bin/../lib"; # XXX +#use FindBin; +#use lib "$FindBin::Bin/../lib"; +#use Data::Dump 'pp'; use Test::More tests => 21; - { package Standard; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } +ok( Standard->can('thing'), 'Standard->thing() exists' ); +ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); +ok( Standard->can('_private'), 'Standard->_private() exists' ); +ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); + { - package SAA; + package PS; use MooseX::PrivateSetters; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } +ok( PS->can('thing'), 'PS->thing() exists' ); +ok( PS->can('_set_thing'), 'PS->set_thing() exists' ); +ok( PS->can('_private'), 'PS->_private() exists' ); +ok( PS->can('_set_private'), 'PS->_set_private() exists' ); + { - package SAA2; + package PS2; # Make sure load order doesn't matter use Moose; use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } +ok( PS2->can('thing'), 'PS2->thing() exists' ); +ok( PS2->can('_set_thing'), 'PS2->set_thing() exists' ); +ok( PS2->can('_private'), 'PS2->_private() exists' ); +ok( PS2->can('_set_private'), 'PS2->_set_private() exists' ); + { - package SAA3; + package PS3; use Moose; use MooseX::PrivateSetters; has 'ro' => ( is => 'ro' ); has 'thing' => ( is => 'rw', reader => 'get_thing' ); has 'thing2' => ( is => 'rw', writer => 'set_it' ); } +ok( PS3->can('ro'), 'PS3->ro exists' ); +ok( ! PS3->can('set_ro'), 'PS3->set_ro does not exist' ); +ok( PS3->can('thing'), 'PS3->thing exists' ); +ok( ! PS3->can('set_thing'), 'PS3->set_thing does not exist' ); +ok( PS3->can('thing2'), 'PS3->thing2 exists' ); +ok( ! PS3->can('set_thing2'), 'PS3->set_thing2 does not exist' ); +ok( PS3->can('set_it'), 'PS3->set_it does exist' ); + { - package SAA4; + package PS4; use Moose; use MooseX::PrivateSetters; has bare => ( is => 'bare' ); } - -ok( Standard->can('thing'), 'Standard->thing() exists' ); -ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); -ok( Standard->can('_private'), 'Standard->_private() exists' ); -ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); - -ok( SAA->can('thing'), 'SAA->thing() exists' ); -ok( SAA->can('set_thing'), 'SAA->set_thing() exists' ); -ok( SAA->can('_private'), 'SAA->_private() exists' ); -ok( SAA->can('_set_private'), 'SAA->_set_private() exists' ); - -ok( SAA2->can('thing'), 'SAA2->thing() exists' ); -ok( SAA2->can('set_thing'), 'SAA2->set_thing() exists' ); -ok( SAA2->can('_private'), 'SAA2->_private() exists' ); -ok( SAA2->can('_set_private'), 'SAA2->_set_private() exists' ); - -ok( SAA3->can('ro'), 'SAA3->ro exists' ); -ok( ! SAA3->can('set_ro'), 'SAA3->set_ro does not exist' ); -ok( SAA3->can('thing'), 'SAA3->thing exists' ); -ok( ! SAA3->can('set_thing'), 'SAA3->set_thing does not exist' ); -ok( SAA3->can('thing2'), 'SAA3->thing2 exists' ); -ok( ! SAA3->can('set_thing2'), 'SAA3->set_thing2 does not exist' ); -ok( SAA3->can('set_it'), 'SAA3->set_it does exist' ); - -ok( ! SAA4->can('bare'), 'SAA4->bare does not exist' ); -ok( ! SAA4->can('set_bare'), 'SAA4->set_bare does not exist' ); +ok( ! PS4->can('bare'), 'PS4->bare does not exist' ); +ok( ! PS4->can('set_bare'), 'PS4->set_bare does not exist' );
briang/MooseX-PrivateSetters
98591d320be6c68e4ae038ec7d2c9f2089948612
s/SemiAffordanceAccessor/PrivateSetters/g in *.{pm,t}
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 57afd2f..631c8f3 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,84 +1,84 @@ -package MooseX::SemiAffordanceAccessor; +package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.05'; use Moose 0.84 (); use Moose::Exporter; use Moose::Util::MetaRole; -use MooseX::SemiAffordanceAccessor::Role::Attribute; +use MooseX::PrivateSetters::Role::Attribute; # The main reason to use this is to ensure that we get the right value # in $p{for_class} later. Moose::Exporter->setup_import_methods(); sub init_meta { shift; my %p = @_; Moose->init_meta(%p); return Moose::Util::MetaRole::apply_metaclass_roles ( for_class => $p{for_class}, attribute_metaclass_roles => - ['MooseX::SemiAffordanceAccessor::Role::Attribute'], + ['MooseX::PrivateSetters::Role::Attribute'], ); } 1; __END__ =pod =head1 NAME -MooseX::SemiAffordanceAccessor - Name your accessors foo() and set_foo() +MooseX::PrivateSetters - Name your accessors foo() and set_foo() =head1 SYNOPSIS - use MooseX::SemiAffordanceAccessor; + use MooseX::PrivateSetters; use Moose; # make some attributes =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with "set_". If you define an attribute with a leading underscore, then the set method will start with "_set_". If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. The name "semi-affordance" comes from David Wheeler's Class::Meta module. =head1 AUTHOR Dave Rolsky, C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2007-2008 Dave Rolsky, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 5ae19f5..14505a7 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,73 +1,73 @@ -package MooseX::SemiAffordanceAccessor::Role::Attribute; +package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = 'set'; if ( $name =~ s/^_// ) { $prefix = '_set'; } $options->{writer} = $prefix . q{_} . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME -MooseX::SemiAffordanceAccessor::Role::Attribute - Names accessors in a semi-affordance style +MooseX::PrivateSetters::Role::Attribute - Names accessors in a semi-affordance style =head1 SYNOPSIS Moose::Util::MetaRole::apply_metaclass_roles ( for_class => $p{for_class}, attribute_metaclass_roles => - ['MooseX::SemiAffordanceAccessor::Role::Attribute'], + ['MooseX::PrivateSetters::Role::Attribute'], ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the reader and writer parameters so that they follow the semi-affordance naming style. =head1 AUTHOR Dave Rolsky, C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2007-2008 Dave Rolsky, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/basic.t b/t/basic.t index 3b6532b..5075cab 100644 --- a/t/basic.t +++ b/t/basic.t @@ -1,82 +1,84 @@ use strict; use warnings; +use FindBin; use lib "$FindBin::Bin/../lib"; # XXX + use Test::More tests => 21; { package Standard; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } { package SAA; - use MooseX::SemiAffordanceAccessor; + use MooseX::PrivateSetters; use Moose; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } { package SAA2; # Make sure load order doesn't matter use Moose; - use MooseX::SemiAffordanceAccessor; + use MooseX::PrivateSetters; has 'thing' => ( is => 'rw' ); has '_private' => ( is => 'rw' ); } { package SAA3; use Moose; - use MooseX::SemiAffordanceAccessor; + use MooseX::PrivateSetters; has 'ro' => ( is => 'ro' ); has 'thing' => ( is => 'rw', reader => 'get_thing' ); has 'thing2' => ( is => 'rw', writer => 'set_it' ); } { package SAA4; use Moose; - use MooseX::SemiAffordanceAccessor; + use MooseX::PrivateSetters; has bare => ( is => 'bare' ); } ok( Standard->can('thing'), 'Standard->thing() exists' ); ok( ! Standard->can('set_thing'), 'Standard->set_thing() does not exist' ); ok( Standard->can('_private'), 'Standard->_private() exists' ); ok( ! Standard->can('_set_private'), 'Standard->_set_private() does not exist' ); ok( SAA->can('thing'), 'SAA->thing() exists' ); ok( SAA->can('set_thing'), 'SAA->set_thing() exists' ); ok( SAA->can('_private'), 'SAA->_private() exists' ); ok( SAA->can('_set_private'), 'SAA->_set_private() exists' ); ok( SAA2->can('thing'), 'SAA2->thing() exists' ); ok( SAA2->can('set_thing'), 'SAA2->set_thing() exists' ); ok( SAA2->can('_private'), 'SAA2->_private() exists' ); ok( SAA2->can('_set_private'), 'SAA2->_set_private() exists' ); ok( SAA3->can('ro'), 'SAA3->ro exists' ); ok( ! SAA3->can('set_ro'), 'SAA3->set_ro does not exist' ); ok( SAA3->can('thing'), 'SAA3->thing exists' ); ok( ! SAA3->can('set_thing'), 'SAA3->set_thing does not exist' ); ok( SAA3->can('thing2'), 'SAA3->thing2 exists' ); ok( ! SAA3->can('set_thing2'), 'SAA3->set_thing2 does not exist' ); ok( SAA3->can('set_it'), 'SAA3->set_it does exist' ); ok( ! SAA4->can('bare'), 'SAA4->bare does not exist' ); ok( ! SAA4->can('set_bare'), 'SAA4->set_bare does not exist' );
ess/Sanman
d53d18e2c744a8c6b30dc1d70f5c0331dc93ffe5
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index f3d0cea..fefc82d 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,284 +1,284 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; use Data::Dumper; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; print "Sanman::LVM::get_lv_device_path( $vg, $lv )\n"; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); print "The device path is: ", $temp[0], "\n"; return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; $infohash->{ 'lv_path' } = $self->get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_name,lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; - if($line =~ /(.*):(.*):(.*):(.*)/) { + if($line =~ /(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'name' => $1, 'uuid' => $2, 'vg' => $3, 'size' => $4 }; $attributes = $5; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; print "contents of infohash:\n", Dumper($infohash), "\n"; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
1e8b879b6282648534e72028a67d3b2bbe2e1c0c
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 2a8f0b0..f3d0cea 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,284 +1,284 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; use Data::Dumper; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; print "Sanman::LVM::get_lv_device_path( $vg, $lv )\n"; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); print "The device path is: ", $temp[0], "\n"; return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; $infohash->{ 'lv_path' } = $self->get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; - my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; + my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_name,lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { - $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; - $attributes = $4; + $infohash = { 'name' => $1, 'uuid' => $2, 'vg' => $3, 'size' => $4 }; + $attributes = $5; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; print "contents of infohash:\n", Dumper($infohash), "\n"; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
926cf3842a9b22ef4e36b3a6647cbebb85ef1aec
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index d5688b6..2a8f0b0 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,284 +1,284 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; use Data::Dumper; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; print "Sanman::LVM::get_lv_device_path( $vg, $lv )\n"; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); print "The device path is: ", $temp[0], "\n"; return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; - $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); + $infohash->{ 'lv_path' } = $self->get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; print "contents of infohash:\n", Dumper($infohash), "\n"; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
505b6c40d4f5fe985c1c66f7d247d44bb01d0509
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 2934497..d5688b6 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,278 +1,284 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; use Data::Dumper; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; + + print "Sanman::LVM::get_lv_device_path( $vg, $lv )\n"; + my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); + + print "The device path is: ", $temp[0], "\n"; return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; + print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; + $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; - print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; - print Dumper($infohash), "\n"; + print "contents of infohash:\n", Dumper($infohash), "\n"; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
766680d5213f541734c420e8ddcf2068754bd4c7
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 7f78ead..2881bdb 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,208 +1,210 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; return $results; } sub vg_info : Public( vg:str ) { my $s = shift; my $obj = shift; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->vg_exists( $vg ) ) { $results = $LVM->get_vg_info( $vg ); } else { $results->{'stderr'} = "The volume group '$vg' does not exist."; $results->{'code'} = 9101; } return $results; } sub lv_info : Public( vg:str, lv:str ) { my $s = shift; my $obj = shift; my $lv = $obj->{lv}; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; print "Sanman::Server::lv_info( { vg => $vg, lv => $lv } )\n"; if( $LVM->lv_exists( $vg, $lv ) ) { + print "$vg -> $lv exists!\n"; $results = $LVM->get_lv_info( $vg, $lv ); + print "Just ran get_lv_info\n"; } else { $results->{'stderr'} = "The volume '$vg -> $lv' does not exist."; $results->{'code'} = 9301; } return $results; } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { $results->{'code'} = 9102; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
cdb96f4e3b0ec76544f4592fcd0c7c444b019caf
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index f555f6d..2934497 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,274 +1,278 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; +use Data::Dumper; + require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; + print "Sanman::LVM::get_lv_info( $vg, $lv )\n"; + print Dumper($infohash), "\n"; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
5275b673ee5f298c62fcab9952e23e8e6bf4721b
Debugging Sanman::Server::lv_info
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 5f87182..f555f6d 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,274 +1,274 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; - print "Sanman::LVM::vg_exists( $vg )\n"; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; + print "Sanman::LVM::lv_exists( $vg, $lv )\n"; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index f2ae54e..7f78ead 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,206 +1,208 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; return $results; } sub vg_info : Public( vg:str ) { my $s = shift; my $obj = shift; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->vg_exists( $vg ) ) { $results = $LVM->get_vg_info( $vg ); } else { $results->{'stderr'} = "The volume group '$vg' does not exist."; $results->{'code'} = 9101; } return $results; } sub lv_info : Public( vg:str, lv:str ) { my $s = shift; my $obj = shift; my $lv = $obj->{lv}; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; + print "Sanman::Server::lv_info( { vg => $vg, lv => $lv } )\n"; + if( $LVM->lv_exists( $vg, $lv ) ) { $results = $LVM->get_lv_info( $vg, $lv ); } else { $results->{'stderr'} = "The volume '$vg -> $lv' does not exist."; $results->{'code'} = 9301; } return $results; } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { $results->{'code'} = 9102; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
a7a067dc2bb0399242a772d3d688c05d8dd66160
Debugging Sanman::LVM::vg_exists
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 0272e7a..5f87182 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,273 +1,274 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; + print "Sanman::LVM::vg_exists( $vg )\n"; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
7922023240cfed720ac3520666841a7405a9dedf
Had a flipped return value in Sanman::LVM::lv_exists and Sanman::LVM::vg_exists.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index f0b2f92..0272e7a 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,273 +1,273 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; - return scalar( grep { /^$vg$/ } @vgs ) == 0; + return scalar( grep { /^$vg$/ } @vgs ) == 1; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; my @lvs = @{ $self->get_lvs }; - return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 0; + return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
d5aef5a39428ddce2d84bd112f4a650e45f81612
vg_info probably shouldn't try to use pv calls.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 11e2d73..f2ae54e 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,206 +1,206 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; return $results; } -sub vg_info : Public( pv:str ) { +sub vg_info : Public( vg:str ) { my $s = shift; my $obj = shift; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->vg_exists( $vg ) ) { $results = $LVM->get_vg_info( $vg ); } else { $results->{'stderr'} = "The volume group '$vg' does not exist."; $results->{'code'} = 9101; } return $results; } sub lv_info : Public( vg:str, lv:str ) { my $s = shift; my $obj = shift; my $lv = $obj->{lv}; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->lv_exists( $vg, $lv ) ) { $results = $LVM->get_lv_info( $vg, $lv ); } else { $results->{'stderr'} = "The volume '$vg -> $lv' does not exist."; $results->{'code'} = 9301; } return $results; } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { $results->{'code'} = 9102; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
2f54e13388b12718147ba75053853e9ac0a2c247
vg_info probably shouldn't try to use pv calls.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 64ca3c3..11e2d73 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,206 +1,206 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; return $results; } sub vg_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; - if( $LVM->pv_exists( $pv ) ) { + if( $LVM->vg_exists( $vg ) ) { $results = $LVM->get_vg_info( $vg ); } else { $results->{'stderr'} = "The volume group '$vg' does not exist."; $results->{'code'} = 9101; } return $results; } sub lv_info : Public( vg:str, lv:str ) { my $s = shift; my $obj = shift; my $lv = $obj->{lv}; my $vg = $obj->{vg}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->lv_exists( $vg, $lv ) ) { $results = $LVM->get_lv_info( $vg, $lv ); } else { $results->{'stderr'} = "The volume '$vg -> $lv' does not exist."; $results->{'code'} = 9301; } return $results; } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { $results->{'code'} = 9102; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
c34ad6fcc93807af658560ef56d3a65dd902cea5
Fleshed out the RPC calls for vg_info and lv_info.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 98f28e5..64ca3c3 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,187 +1,206 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; return $results; } -sub vg_info { +sub vg_info : Public( pv:str ) { my $s = shift; my $obj = shift; + my $vg = $obj->{vg}; + my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; + + if( $LVM->pv_exists( $pv ) ) { + $results = $LVM->get_vg_info( $vg ); + } else { + $results->{'stderr'} = "The volume group '$vg' does not exist."; + $results->{'code'} = 9101; + } - return 0; + return $results; } -sub lv_info { +sub lv_info : Public( vg:str, lv:str ) { my $s = shift; my $obj = shift; + my $lv = $obj->{lv}; + my $vg = $obj->{vg}; + my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; - return 0 + if( $LVM->lv_exists( $vg, $lv ) ) { + $results = $LVM->get_lv_info( $vg, $lv ); + } else { + $results->{'stderr'} = "The volume '$vg -> $lv' does not exist."; + $results->{'code'} = 9301; + } + + return $results; } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { - $results->{'code'} = 9101; + $results->{'code'} = 9102; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
20f34004a1e7e42931aefb96576a36ee76b6bef8
Debugging the pv_info RPC call.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 6cbc0f2..98f28e5 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,185 +1,187 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, pv_info => \&pv_info, vg_info => \&vg_info, lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub pv_info : Public( pv:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{pv}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results = $LVM->get_pv_info( $pv ); } else { $results->{'stderr'} = "$pv does not exist as a physical volume."; $results->{'code'} = 9001; } - return $LVM->get_pv_info( $pv ); + + print "pv_info results:\n\n" . Dumper( $results ) . "\n\n"; + return $results; } sub vg_info { my $s = shift; my $obj = shift; return 0; } sub lv_info { my $s = shift; my $obj = shift; return 0 } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { $results->{'code'} = 9101; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
198b426c6dd72d87733ea1189e743922c029d351
More stupid LVM typos.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 878eb3c..f0b2f92 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,273 +1,273 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; - my @vgs = @{ $self->get_lvs }; + my @lvs = @{ $self->get_lvs }; return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 0; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
2742410e44dab2526e9cdd41913620c7207c14d2
More stupid LVM typos.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 8b8eb39..878eb3c 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,273 +1,273 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; my @vgs = @{ $self->get_lvs }; - return scalar( grep { /^$vg\s+-\>\s+$pv$/ } @lvs ) == 0; + return scalar( grep { /^$vg\s+-\>\s+$lv$/ } @lvs ) == 0; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
57ce3ba1c1201d3b906a60a69d7fc17039503480
Added *_info RPC call stubs.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 8398aac..8b8eb39 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,271 +1,273 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; + my @vgs = @{ $self->get_lvs }; + return scalar( grep { /^$vg\s+-\>\s+$pv$/ } @lvs ) == 0; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; #$self->get_lv_device_path($vg, $lv); "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 0a68946..6cbc0f2 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,153 +1,185 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { - list_pvs => \&list_pvs, - list_vgs => \&list_vgs, - list_lvs => \&list_lvs, - create_pv => \&create_pv, - create_vg => \&create_vg, - create_lv => \&create_lv, + list_pvs => \&list_pvs, + list_vgs => \&list_vgs, + list_lvs => \&list_lvs, + create_pv => \&create_pv, + create_vg => \&create_vg, + create_lv => \&create_lv, + pv_info => \&pv_info, + vg_info => \&vg_info, + lv_info => \&lv_info, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } +sub pv_info : Public( pv:str ) { + my $s = shift; + my $obj = shift; + my $pv = $obj->{pv}; + my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; + + if( $LVM->pv_exists( $pv ) ) { + $results = $LVM->get_pv_info( $pv ); + } else { + $results->{'stderr'} = "$pv does not exist as a physical volume."; + $results->{'code'} = 9001; + } + return $LVM->get_pv_info( $pv ); +} + +sub vg_info { + my $s = shift; + my $obj = shift; + + return 0; +} + +sub lv_info { + my $s = shift; + my $obj = shift; + + return 0 +} + sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; - $results->{'code'} = 9001; + $results->{'code'} = 9002; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; - $results->{'code'} = 9002; + $results->{'code'} = 9003; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { - $results->{'code'} = 9003; + $results->{'code'} = 9101; $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { - $results->{'code'} = 9004; + $results->{'code'} = 9001; $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
4dfc1b8e2818a93eacf936669ff31504cfce0456
Attempting to make the get_lvs output somewhat meaningful.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 7912121..8398aac 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,270 +1,271 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; - $self->get_lv_device_path($vg, $lv); + #$self->get_lv_device_path($vg, $lv); + "$vg -> $lv"; } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
e08346f515d9905c825be4676e224c7ec8dfa526
Continuing to remove stupid typos from the Server methods, too.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 0c09cf5..0a68946 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,153 +1,153 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9001; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9002; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); if( $LVM->pv_exists( $pv ) ) { if( $LVM->pv_available( $pv ) ) { $results = $LVM->make_vg( $vg, $pv ); } else { - $results{'code'} = 9003; - $results{'stderr'} = "$pv is already assigned to a volume group." + $results->{'code'} = 9003; + $results->{'stderr'} = "$pv is already assigned to a volume group." } } else { - $results{'code'} = 9004; - $results{'stderr'} = "$pv does not exist as a physical volume." + $results->{'code'} = 9004; + $results->{'stderr'} = "$pv does not exist as a physical volume." } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
885de62204af9e60fceba7e4fc1ca19b9bfdfebb
Continuing to remove stupid typos from the LVM methods.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 52c4159..7912121 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,270 +1,270 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; $self->get_lv_device_path($vg, $lv); } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, - 'name' => $2 + 'name' => $2, 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
4e05f40177591e4fd152d799aa16b1e5c3dbd830
Continuing to remove stupid typos from the LVM methods.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 4b454e7..52c4159 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,270 +1,270 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; } sub pv_available { my $self = shift; my $pv = shift; return length( $self->get_pv_info()->{'vg'} ) == 0; } sub vg_exists { my $self = shift; my $vg = shift; my @vgs = @{ $self->get_vgs() }; return scalar( grep { /^$vg$/ } @vgs ) == 0; } sub lv_exists { my $self = shift; my ($vg, $lv) = @_; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; @lines = map { my @temp = split(/\:/, $self->strip($_)); my $vg = $temp[0]; my $lv = $temp[1]; $self->get_lv_device_path($vg, $lv); } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, - 'name' => $2 + 'name' => $2, 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
796c62619493d6a66f691686c7d6e945cb3e39ba
Continuing to add constraints to the LVM methods.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 0b8095d..4b454e7 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,246 +1,270 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; - #return scalar(@pvs) == 1; +} + +sub pv_available { + my $self = shift; + my $pv = shift; + + return length( $self->get_pv_info()->{'vg'} ) == 0; +} + +sub vg_exists { + my $self = shift; + my $vg = shift; + + my @vgs = @{ $self->get_vgs() }; + return scalar( grep { /^$vg$/ } @vgs ) == 0; +} + +sub lv_exists { + my $self = shift; + my ($vg, $lv) = @_; + } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; - @lines = map { $self->strip($_) } @lines; + @lines = map { $self->strip( $_ ) } @lines; return \@lines; } sub get_lvs { my $self = shift; - my @lines = `$SBIN/lvs $COMMONOPTS -o lv_name`; - @lines = map { $self->strip($_) } @lines; + my @lines = `$SBIN/lvs $COMMONOPTS -o vg_name,lv_name`; + @lines = map { + my @temp = split(/\:/, $self->strip($_)); + my $vg = $temp[0]; + my $lv = $temp[1]; + $self->get_lv_device_path($vg, $lv); + } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; - @lines = map { $self->strip($_) } @lines; + @lines = map { $self->strip( $_ ) } @lines; foreach my $line (@lines) { if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2 'size' => $3, 'free' => $4, 'used' => $5, 'pe_count' => $6, 'pe_allocated' => $7, 'vg' => $8 }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'name' => $2 'size' => $3, 'free' => $4, 'extent_size' => $5, 'extent_count' => $6, 'extents_free' => $7, 'lv_count' => $8 }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); -# return $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index 7043b16..0c09cf5 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,142 +1,153 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub list_available_blockdevs : Public { my $s = shift; return $Block->unused_block_devices(); } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9001; } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); } else { $results->{'stderr'} = "$pv is not a viable block device."; $results->{'code'} = 9002; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; - my $results = {}; + my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); - $results = $LVM->make_vg( $vg, $pv ); + + if( $LVM->pv_exists( $pv ) ) { + if( $LVM->pv_available( $pv ) ) { + $results = $LVM->make_vg( $vg, $pv ); + } else { + $results{'code'} = 9003; + $results{'stderr'} = "$pv is already assigned to a volume group." + } + } else { + $results{'code'} = 9004; + $results{'stderr'} = "$pv does not exist as a physical volume." + } return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
6a6d137650382e6b2ea4185a61276de912c03c80
Breaking for the weekend.
diff --git a/modules/Sanman/lib/Sanman/LVM.pm b/modules/Sanman/lib/Sanman/LVM.pm index 077318e..0b8095d 100644 --- a/modules/Sanman/lib/Sanman/LVM.pm +++ b/modules/Sanman/lib/Sanman/LVM.pm @@ -1,228 +1,246 @@ package Sanman::LVM; use 5.006; use strict; use Sanman; require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Sanman); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = Sanman::sbin(); my $COMMONOPTS = Sanman::commonopts(); sub new { my $class = shift; my $self = $class->SUPER::new(); return $self; } sub get_pvs { my $self = shift; my @lines = `$SBIN/pvs $COMMONOPTS -o pv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub pv_exists { my $self = shift; my $pv = shift; my @pvs = @{ $self->get_pvs() }; return scalar( grep { /^$pv$/ } @pvs ) == 1; #return scalar(@pvs) == 1; } sub get_vgs { my $self = shift; my @lines = `$SBIN/vgs $COMMONOPTS -o vg_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub get_lvs { my $self = shift; my @lines = `$SBIN/lvs $COMMONOPTS -o lv_name`; @lines = map { $self->strip($_) } @lines; return \@lines; } sub get_pv_info { my $self = shift; my $pv = shift; my $infohash = {}; - my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count $pv`; + my @lines = `$SBIN/pvs $COMMONOPTS -o pv_uuid,pv_name,pv_size,pv_free,pv_used,pv_pe_count,pv_pe_alloc_count,vg_name $pv`; @lines = map { $self->strip($_) } @lines; foreach my $line (@lines) { - if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*)/) { - $infohash = { 'uuid' => $1, 'size' => $2, 'free' => $3, 'used' => $4, 'pe_count' => $5, 'pe_allocated' => $6 }; + if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { + $infohash = { + 'uuid' => $1, + 'name' => $2 + 'size' => $3, + 'free' => $4, + 'used' => $5, + 'pe_count' => $6, + 'pe_allocated' => $7, + 'vg' => $8 + }; } } return $infohash; } sub get_vg_info { my $self = shift; my $vg = shift; my $infohash = {}; - my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); + my $line = $self->strip( `$SBIN/vgs $COMMONOPTS -o vg_uuid,vg_name,vg_size,vg_free,vg_extent_size,vg_extent_count,vg_free_count,lv_count $vg 2>/dev/null` ); - if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { - $infohash = { 'uuid' => $1, 'size' => $2, 'free' => $3, 'extent_size' => $4, 'extent_count' => $5, 'extents_free' => $6, 'lv_count' => $7 }; + if($line =~ /(.*):(.*):(.*):(.*):(.*):(.*):(.*):(.*)/) { + $infohash = { + 'uuid' => $1, + 'name' => $2 + 'size' => $3, + 'free' => $4, + 'extent_size' => $5, + 'extent_count' => $6, + 'extents_free' => $7, + 'lv_count' => $8 + }; } return $infohash; } sub get_lv_device_path { my $self = shift; my ( $vg, $lv ) = @_; my $line = `$SBIN/lvdisplay -c $vg/$lv 2>/dev/null`; my @temp = split(/\:/, $self->strip( $line ) ); return $temp[0]; } sub get_lv_info { my $self = shift; my ($vg, $lv) = @_; my $infohash = {}; $infohash->{ 'lv_path' } = &get_lv_device_path( $vg, $lv ); if( length( $infohash->{ 'lv_path' } ) == 0 ) { return undef; } my $attributes; my $line = $self->strip( `$SBIN/lvs $COMMONOPTS -o lv_uuid,vg_name,lv_size,lv_attr $vg/$lv 2>/dev/null` ) ; if($line =~ /(.*):(.*):(.*):(.*)/) { $infohash = { 'uuid' => $1, 'vg' => $2, 'size' => $3 }; $attributes = $4; } my @attrs = split( //, $attributes ); $infohash->{ 'volume_type_attr' } = $attrs[0]; $infohash->{ 'permissions_attr' } = $attrs[1]; $infohash->{ 'allocation_policy_attr' } = $attrs[2]; $infohash->{ 'fixed_attr' } = $attrs[3]; $infohash->{ 'state_attr' } = $attrs[4]; $infohash->{ 'device_attr' } = $attrs[5]; return $infohash; } sub make_pv { my $self = shift; my $pvpath = shift; my $results = {}; $results = $self->execute_system_command("$SBIN/pvcreate $pvpath"); # return $self->execute_system_command("$SBIN/pvcreate $pvpath"); return $results; } sub make_vg { my $self = shift; my $vgname = shift; my $pvpath = shift; my $results = {}; print "Volume Group: $vgname\n\nPhysical Volume: $pvpath\n\n"; $results = $self->execute_system_command("$SBIN/vgcreate $vgname $pvpath"); return $results; } sub make_lv { my $self = shift; my $lvname = shift; my $lvsize = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/lvcreate -L " . $lvsize . "G -n $lvname $vgname"); } sub remove_pv { my $self = shift; my $pvpath = shift; return $self->execute_system_command("$SBIN/pvremove $pvpath"); } sub remove_vg { my $self = shift; my $vgname = shift; return $self->execute_system_command("$SBIN/vgremove $vgname"); } sub remove_lv { my $self = shift; my $lvname = shift; return $self->execute_system_command("$SBIN/lvremove $lvname"); } 1; __END__ =head1 NAME Sanman::LVM - Sanman LVM management module =head1 SYNOPSIS use Sanman::LVM; # Create the 10GB logical volume 'brick' inside the 'storage' group make_lv( 'storage', 'brick', 10 ); # Destroy the 'brick' volume remove_lv( 'storage', 'brick' ); =head1 DESCRIPTION This module provides LVM management to the Sanman suite. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
e4068122c2b22b7be70d4434c1ac6e94551e9d39
Added an API call to return valid block devices and altered create_pv to add consistency checks.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index a221fe9..7043b16 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,134 +1,142 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } +sub list_available_blockdevs : Public { + my $s = shift; + return $Block->unused_block_devices(); +} + sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9001; - } else { + } elsif( $Block->is_available( $pv ) ) { $results = $LVM->make_pv( $pv ); + } else { + $results->{'stderr'} = "$pv is not a viable block device."; + $results->{'code'} = 9002; } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); $results = $LVM->make_vg( $vg, $pv ); return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
b4426a6494e8948e939708f859c10ed92a10c2ab
'result' is not 'results' typo
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index a37b1a8..a221fe9 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,134 +1,134 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9001; } else { $results = $LVM->make_pv( $pv ); } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); $results = $LVM->make_vg( $vg, $pv ); return $results; } sub create_lv : Public( a:str, b:str, c:int ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); $results = $LVM->make_lv( $lv, $gigs, $vg ); - return $result; + return $results; } package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
32618243b3c7fa472a9529a8cad0f0f5fb7ca0d2
Added the create_lv RPC call.
diff --git a/modules/Sanman/lib/Sanman/Server.pm b/modules/Sanman/lib/Sanman/Server.pm index d9f6b73..a37b1a8 100644 --- a/modules/Sanman/lib/Sanman/Server.pm +++ b/modules/Sanman/lib/Sanman/Server.pm @@ -1,122 +1,134 @@ package Sanman::Server; use 5.006; use strict; use Sanman::LVM; use Sanman::ISCSI; use Sanman::Block; use base qw(JSON::RPC::Procedure); use Data::Dumper; our $VERSION = '0.0.0'; my $LVM = Sanman::LVM->new(); my $Block = Sanman::Block->new(); my $ISCSI = Sanman::ISCSI->new(); sub _allowable_procedure { return { list_pvs => \&list_pvs, list_vgs => \&list_vgs, list_lvs => \&list_lvs, create_pv => \&create_pv, create_vg => \&create_vg, create_lv => \&create_lv, }; } sub list_pvs : Public { my $s = shift; return $LVM->get_pvs(); } sub list_vgs : Public { my $s = shift; return $LVM->get_vgs(); } sub list_lvs : Public { my $s = shift; return $LVM->get_lvs(); } sub create_pv : Public( a:str ) { my $s = shift; my $obj = shift; my $pv = $obj->{a}; my $results = { 'stdout' => '', 'stderr' => '', 'code' => '' }; if( $LVM->pv_exists( $pv ) ) { $results->{'stderr'} = "$pv already exists as a physical volume."; $results->{'code'} = 9001; } else { $results = $LVM->make_pv( $pv ); } return $results; } sub create_vg : Public( a:str, b:str ) { my $s = shift; my $obj = shift; my $results = {}; my ($vg, $pv) = ( $obj->{a}, $obj->{b} ); $results = $LVM->make_vg( $vg, $pv ); return $results; } +sub create_lv : Public( a:str, b:str, c:int ) { + my $s = shift; + my $obj = shift; + my $results = {}; + + my ($vg, $lv, $gigs) = ( $obj->{a}, $obj->{b}, $obj->{c} ); + + $results = $LVM->make_lv( $lv, $gigs, $vg ); + + return $result; +} + package Sanman::Server::system; sub describe { { sdversion => '0.0.0', name => 'Sanman', } } 1; __END__ =head1 NAME Sanman::Server - Sanman back-end server library =head1 SYNOPSIS # I bet you would like to see some example code. # So would I. =head1 DESCRIPTION This module provides the back-end JSONRPC services that allow for SAN management. =head2 Methods =over 4 stub stub stub =back =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
ess/Sanman
9ddfad46d4e78d459ef9e2d1e9c8f7b30593afed
Added the read_config class method to Sanman.
diff --git a/modules/Sanman/lib/Sanman.pm b/modules/Sanman/lib/Sanman.pm index cc7afcf..fd0f017 100644 --- a/modules/Sanman/lib/Sanman.pm +++ b/modules/Sanman/lib/Sanman.pm @@ -1,118 +1,127 @@ package Sanman; use 5.006; use strict; +use JSON; use Sys::Syslog; use IO::CaptureOutput qw(capture capture_exec); require Exporter; use AutoLoader qw(AUTOLOAD); our @ISA = qw(Exporter); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.0.0'; my $SBIN = "/usr/sbin"; my $COMMONOPTS = "--noheadings --separator : --units g --nosuffix"; sub new { my $class = shift; my $self = shift; unless( ref( $self ) ) { $self = {}; } openlog( 'sanman', 'cons,pid', 'user' ); #$self->{ "_SBIN" } = \$SBIN; #$self->{ "_COMMONOPTS" } = \$COMMONOPTS; bless( $self, $class ); return $self; } sub strip { # strip whitespace from both ends of a string my $self = shift; my $returnval = shift; chomp($returnval); $returnval =~ s/^\s+//; $returnval =~ s/\s+$//; return $returnval; } sub execute_system_command { # executes a system command, returns success/fail my $self = shift; my $command = shift; my $stdout; my $stderr; #my $command = '/bin/bash -l -c "' . $self->strip(shift) . '"'; syslog( 'info', "Attempting to run '$command'" ); ($stdout,$stderr) = capture_exec( $self->strip( $command ) ); my $return = $? >> 8; if($return) { my @lines = split( /\n/, $stderr ); for my $line (@lines) { syslog("info", $self->strip($line)); } } else { my @lines = split( /\n/, $stdout ); for my $line (@lines) { syslog("info", $self->strip($line)); } } syslog("info", "Return code was '$return'."); return { 'stdout' => $stdout, 'stderr' => $stderr, 'code' => $return }; } sub sbin { return $SBIN; } sub commonopts { return $COMMONOPTS; } +sub read_config { + my $config; + open( CONFIG, "</etc/sanman.conf"); + $config = join('', <CONFIG> ); + close( CONFIG ); + return from_json( $config ); +} + 1; __END__ =head1 NAME Sanman - Sanman is a San Management suite =head1 SYNOPSIS The Sanman module should never be loaded directly, really. =head1 DESCRIPTION This module provides common methods and variables to the other Sanman modules. =head1 AUTHOR Dennis Walters <[email protected]> =head1 COPYRIGHT Copyright (C) 2009 Dennis Walters This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
benlund/node-beanstalk-client
b154d86119145c308579e79ad97e3e91bf66e374
tweaked readme
diff --git a/README b/README index 9789737..7e133d3 100644 --- a/README +++ b/README @@ -1,37 +1,39 @@ Beanstalkd Client for Node.js ============================= Version: 0.2.0 Example: var client = require('beanstalk_client').Client; client.connect('127.0.0.1:11300', function(err, conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; conn.put(0, 0, 1, JSON.stringify(job_data), function(err, job_id) { console.log('put job: ' + job_id); conn.reserve(function(err, job_id, job_json) { console.log('got job: ' + job_id); console.log('got job data: ' + job_json); console.log('module name is ' + JSON.parse(job_json).data.name); conn.destroy(job_id, function(err) { console.log('destroyed job'); }); }); }); }); Try it: $ node test/test.js +See also: http://github.com/benlund/node-beanstalk-worker + === NPM: $ npm install beanstalk_client
benlund/node-beanstalk-client
b52023a6ae2c86d94bfb3835da0e67c2875fa671
added not about npm to readme
diff --git a/README b/README index 397296c..9789737 100644 --- a/README +++ b/README @@ -1,31 +1,37 @@ Beanstalkd Client for Node.js ============================= Version: 0.2.0 Example: var client = require('beanstalk_client').Client; client.connect('127.0.0.1:11300', function(err, conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; conn.put(0, 0, 1, JSON.stringify(job_data), function(err, job_id) { console.log('put job: ' + job_id); conn.reserve(function(err, job_id, job_json) { console.log('got job: ' + job_id); console.log('got job data: ' + job_json); console.log('module name is ' + JSON.parse(job_json).data.name); conn.destroy(job_id, function(err) { console.log('destroyed job'); }); }); }); }); Try it: $ node test/test.js - \ No newline at end of file + + +=== + +NPM: + +$ npm install beanstalk_client
benlund/node-beanstalk-client
e58232e7ef0e9ebaf0a6cb28def36387bdb7a602
added package.json
diff --git a/README b/README index 640042f..397296c 100644 --- a/README +++ b/README @@ -1,31 +1,31 @@ Beanstalkd Client for Node.js ============================= -Version: 0.2 +Version: 0.2.0 Example: var client = require('beanstalk_client').Client; client.connect('127.0.0.1:11300', function(err, conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; conn.put(0, 0, 1, JSON.stringify(job_data), function(err, job_id) { console.log('put job: ' + job_id); conn.reserve(function(err, job_id, job_json) { console.log('got job: ' + job_id); console.log('got job data: ' + job_json); console.log('module name is ' + JSON.parse(job_json).data.name); conn.destroy(job_id, function(err) { console.log('destroyed job'); }); }); }); }); Try it: $ node test/test.js \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..fc407d2 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ "name": "beanstalk_client" +, "version": "0.2.0" +, "main": "lib/beanstalk_client" +, "description": "client library for the beanstalkd message queue server" +} \ No newline at end of file diff --git a/test/#connect.js# b/test/#connect.js# deleted file mode 100644 index de63a20..0000000 --- a/test/#connect.js# +++ /dev/null @@ -1,22 +0,0 @@ -var sys = require('sys'); -var client = require('../lib/beanstalk_client').Client; - -client.connect(null, function(err, conn) { - - sys.puts('success connecting'); - conn.use('test').addCallback(function() { - conn.watch('test').addCallback(function() { - conn.put(0, 0, 1, 'hiben').addCallback(function(job_id) { - sys.puts('put job: ' + job_id); - - conn.reserve().addCallback(function(job_id, data) { - sys.puts('got job: ' + job_id); - sys.puts('job data: ' + data); - conn.destroy(job_id); - }); - }); - }); - }); -}).addErrback(function() { - sys.puts('error connecting'); -});
benlund/node-beanstalk-client
7b26eeef4bf48bdb0028796b4a3b65b429269cff
added error arg to the calback data
diff --git a/README b/README index dbf2d27..640042f 100644 --- a/README +++ b/README @@ -1,32 +1,31 @@ Beanstalkd Client for Node.js ============================= -Version: 0.0.1 - --- Not all commands are yet implemented -- +Version: 0.2 Example: -var sys = require('sys'); -var bt = require('lib/beanstalk_client'); +var client = require('beanstalk_client').Client; -bt.Client.connect('127.0.0.1:11300').addCallback(function(conn) { +client.connect('127.0.0.1:11300', function(err, conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; - conn.put(0, 0, 1, JSON.stringify(job_data)).addCallback(function(job_id) { - - sys.puts('put job: ' + job_id); - - conn.reserve().addCallback(function(job_id, job_json) { - sys.puts('got job: ' + job_id); - sys.puts('got job data: ' + job_json); - sys.puts('module name is ' + JSON.parse(job_json).data.name); - conn.destroy(job_id); + conn.put(0, 0, 1, JSON.stringify(job_data), function(err, job_id) { + console.log('put job: ' + job_id); + + conn.reserve(function(err, job_id, job_json) { + console.log('got job: ' + job_id); + console.log('got job data: ' + job_json); + console.log('module name is ' + JSON.parse(job_json).data.name); + conn.destroy(job_id, function(err) { + console.log('destroyed job'); + }); }); }); }); + Try it: $ node test/test.js \ No newline at end of file diff --git a/lib/beanstalk_client.coffee b/lib/beanstalk_client.coffee index b17ecd9..65a983e 100644 --- a/lib/beanstalk_client.coffee +++ b/lib/beanstalk_client.coffee @@ -1,162 +1,162 @@ net: require 'net' Client: { DEFAULT_ADDR: '127.0.0.1' DEFAULT_PORT: 11300 LOWEST_PRIORITY: 4294967295 connect: (server, callback) -> if server [addr, port]: server.split(':') if !addr addr: Client.DEFAULT_ADDR if !port port: Client.DEFAULT_PORT stream: net.createConnection port, addr stream.on 'connect', () -> callback(false, new Connection(stream)) stream.on 'error', (err) -> callback(err) stream.on 'close', (has_error) -> #todo } make_command_method: (command_name, expected_response, sends_data) -> (args..., callback) -> args.unshift command_name if sends_data data: args.pop() args.push data.length this.send.apply this, args if data this.send data this.handlers.push([new ResponseHandler(expected_response), callback]) class Connection constructor: (stream) -> @stream: stream @buffer: '' @handlers: [] @stream.on 'data', (data) => @buffer += data @try_handling_response() - close: () -> - @stream.close() + end: () -> + @stream.end() try_handling_response: () -> [handler, callback]: @handlers[0] if handler? handler.handle @buffer if handler.complete @finished_handling_response(); if handler.success - callback.apply(null, handler.args) + callback.call(null, false, handler.args...) else - ##todo + callback.call(null, handler.args[0]) else handler.reset() finished_handling_response: () -> @buffer: '' hp: @handlers.shift() hp: null send: (args...) -> @stream.write(args.join(' ') + "\r\n") #submitting jobs use: make_command_method('use', 'USING') put: make_command_method('put', 'INSERTED', true) #handling jobs watch: make_command_method('watch', 'WATCHING') ignore: make_command_method('ignore', 'WATCHING') reserve: make_command_method('reserve', 'RESERVED') reserve_with_timeout: make_command_method('reserve-with-timeout', 'RESERVED') destroy: make_command_method('delete', 'DELETED') release: make_command_method('release', 'RELEASED') bury: make_command_method('bury', 'BURIED') touch: make_command_method('touch', 'TOUCHED') #other stuff peek: make_command_method('peek', 'FOUND') peek_ready: make_command_method('peek-ready', 'FOUND') peek_delayed: make_command_method('peek-delayed', 'FOUND') peek_buried: make_command_method('peek-buried', 'FOUND') kick: make_command_method('kick', 'KICKED') stats_job: make_command_method('stats-job', 'OK') stats_tube: make_command_method('stats-tube', 'OK') stats: make_command_method('stats', 'OK') class ResponseHandler constructor: (success_code) -> @success_code: success_code reset: () -> @complete: false @success: false @args: undefined @header: undefined @body: undefined CODES_REQUIRING_BODY: { 'RESERVED': true } handle: (data) -> i: data.indexOf("\r\n") if i >= 0 @header: data.substr(0, i) @body: data.substr(i + 2) @args = @header.split(' ') code = @args[0] if code == @success_code @args.shift() #don't include the code in the success args, but do in the err args @success: true if(@CODES_REQUIRING_BODY[code]) @parse_body() else @complete: true parse_body: () -> if @body? body_length: parseInt(@args[@args.length - 1], 10) if @body.length == (body_length + 2) @args.pop() #removed the length and add the data @args.push(@body.substr(0, @body.length-2)) @complete: true exports.Client: Client diff --git a/lib/beanstalk_client.js b/lib/beanstalk_client.js index 795b061..cf07fa5 100644 --- a/lib/beanstalk_client.js +++ b/lib/beanstalk_client.js @@ -1,167 +1,166 @@ (function(){ var Client, Connection, ResponseHandler, make_command_method, net; var __slice = Array.prototype.slice, __bind = function(func, obj, args) { return function() { return func.apply(obj || {}, args ? args.concat(__slice.call(arguments, 0)) : arguments); }; }; net = require('net'); Client = { DEFAULT_ADDR: '127.0.0.1', DEFAULT_PORT: 11300, LOWEST_PRIORITY: 4294967295, connect: function(server, callback) { var _a, addr, port, stream; if (server) { _a = server.split(':'); addr = _a[0]; port = _a[1]; } !addr ? (addr = Client.DEFAULT_ADDR) : null; !port ? (port = Client.DEFAULT_PORT) : null; stream = net.createConnection(port, addr); stream.on('connect', function() { return callback(false, new Connection(stream)); }); stream.on('error', function(err) { return callback(err); }); return stream.on('close', function(has_error) { }); //todo } }; make_command_method = function(command_name, expected_response, sends_data) { return function() { var args, data; var _a = arguments.length, _b = _a >= 2, callback = arguments[_b ? _a - 1 : 0]; args = __slice.call(arguments, 0, _a - 1); args.unshift(command_name); if (sends_data) { data = args.pop(); args.push(data.length); } this.send.apply(this, args); data ? this.send(data) : null; return this.handlers.push([new ResponseHandler(expected_response), callback]); }; }; Connection = function(stream) { this.stream = stream; this.buffer = ''; this.handlers = []; this.stream.on('data', __bind(function(data) { this.buffer += data; return this.try_handling_response(); }, this)); return this; }; - Connection.prototype.close = function() { - return this.stream.close(); + Connection.prototype.end = function() { + return this.stream.end(); }; Connection.prototype.try_handling_response = function() { var _a, callback, handler; _a = this.handlers[0]; handler = _a[0]; callback = _a[1]; if ((typeof handler !== "undefined" && handler !== null)) { handler.handle(this.buffer); if (handler.complete) { this.finished_handling_response(); if (handler.success) { - return callback.apply(null, handler.args); + return callback.call.apply(callback, [null, false].concat(handler.args)); } else { - + return callback.call(null, handler.args[0]); } - //#todo } else { return handler.reset(); } } }; Connection.prototype.finished_handling_response = function() { var hp; this.buffer = ''; hp = this.handlers.shift(); hp = null; return hp; }; Connection.prototype.send = function() { var args; var _a = arguments.length, _b = _a >= 1; args = __slice.call(arguments, 0, _a - 0); return this.stream.write(args.join(' ') + "\r\n"); }; //submitting jobs Connection.prototype.use = make_command_method('use', 'USING'); Connection.prototype.put = make_command_method('put', 'INSERTED', true); //handling jobs Connection.prototype.watch = make_command_method('watch', 'WATCHING'); Connection.prototype.ignore = make_command_method('ignore', 'WATCHING'); Connection.prototype.reserve = make_command_method('reserve', 'RESERVED'); Connection.prototype.reserve_with_timeout = make_command_method('reserve-with-timeout', 'RESERVED'); Connection.prototype.destroy = make_command_method('delete', 'DELETED'); Connection.prototype.release = make_command_method('release', 'RELEASED'); Connection.prototype.bury = make_command_method('bury', 'BURIED'); Connection.prototype.touch = make_command_method('touch', 'TOUCHED'); //other stuff Connection.prototype.peek = make_command_method('peek', 'FOUND'); Connection.prototype.peek_ready = make_command_method('peek-ready', 'FOUND'); Connection.prototype.peek_delayed = make_command_method('peek-delayed', 'FOUND'); Connection.prototype.peek_buried = make_command_method('peek-buried', 'FOUND'); Connection.prototype.kick = make_command_method('kick', 'KICKED'); Connection.prototype.stats_job = make_command_method('stats-job', 'OK'); Connection.prototype.stats_tube = make_command_method('stats-tube', 'OK'); Connection.prototype.stats = make_command_method('stats', 'OK'); ResponseHandler = function(success_code) { this.success_code = success_code; return this; }; ResponseHandler.prototype.reset = function() { this.complete = false; this.success = false; this.args = undefined; this.header = undefined; this.body = undefined; return this.body; }; ResponseHandler.prototype.CODES_REQUIRING_BODY = { 'RESERVED': true }; ResponseHandler.prototype.handle = function(data) { var code, i; i = data.indexOf("\r\n"); if (i >= 0) { this.header = data.substr(0, i); this.body = data.substr(i + 2); this.args = this.header.split(' '); code = this.args[0]; if (code === this.success_code) { this.args.shift(); //don't include the code in the success args, but do in the err args this.success = true; } if ((this.CODES_REQUIRING_BODY[code])) { return this.parse_body(); } else { this.complete = true; return this.complete; } } }; ResponseHandler.prototype.parse_body = function() { var _a, body_length; if ((typeof (_a = this.body) !== "undefined" && _a !== null)) { body_length = parseInt(this.args[this.args.length - 1], 10); if (this.body.length === (body_length + 2)) { this.args.pop(); //removed the length and add the data this.args.push(this.body.substr(0, this.body.length - 2)); this.complete = true; return this.complete; } } }; exports.Client = Client; })(); diff --git a/test/#connect.js# b/test/#connect.js# new file mode 100644 index 0000000..de63a20 --- /dev/null +++ b/test/#connect.js# @@ -0,0 +1,22 @@ +var sys = require('sys'); +var client = require('../lib/beanstalk_client').Client; + +client.connect(null, function(err, conn) { + + sys.puts('success connecting'); + conn.use('test').addCallback(function() { + conn.watch('test').addCallback(function() { + conn.put(0, 0, 1, 'hiben').addCallback(function(job_id) { + sys.puts('put job: ' + job_id); + + conn.reserve().addCallback(function(job_id, data) { + sys.puts('got job: ' + job_id); + sys.puts('job data: ' + data); + conn.destroy(job_id); + }); + }); + }); + }); +}).addErrback(function() { + sys.puts('error connecting'); +}); diff --git a/test/connect.coffee b/test/connect.coffee index edf74e5..a9964ea 100644 --- a/test/connect.coffee +++ b/test/connect.coffee @@ -1,30 +1,30 @@ sys: require('sys') client: require('../lib/beanstalk_client').Client #producer client.connect null, (err, conn) -> if err sys.puts 'Producer connection error:', sys,inspect(err) else sys.puts('Producer connected') conn.use 'test', () -> - conn.put 0, 0, 1, 'hiben', (job_id) -> + conn.put 0, 0, 1, 'hiben', (err, job_id) -> sys.puts('Producer sent job: ' + job_id) #consumer client.connect null, (err, conn) -> if err sys.puts 'Consumer connection error:', sys,inspect(err) else sys.puts('Consumer connected') - conn.watch 'test', () -> + conn.watch 'test', (err) -> - conn.reserve (job_id, data) -> + conn.reserve (err, job_id, data) -> sys.puts('Consumer got job: ' + job_id) sys.puts(' job data: ' + data) - conn.destroy job_id, () -> - sys.puts('Consumer destroyed job: ' + job_id) \ No newline at end of file + conn.destroy job_id, (err) -> + sys.puts('Consumer destroyed job: ' + job_id) diff --git a/test/connect.js b/test/connect.js index 4a625b5..dddadd4 100644 --- a/test/connect.js +++ b/test/connect.js @@ -1,36 +1,36 @@ (function(){ var client, sys; sys = require('sys'); client = require('../lib/beanstalk_client').Client; //producer client.connect(null, function(err, conn) { if (err) { sys.puts('Producer connection error:', sys, inspect(err)); } else { } sys.puts('Producer connected'); return conn.use('test', function() { - return conn.put(0, 0, 1, 'hiben', function(job_id) { + return conn.put(0, 0, 1, 'hiben', function(err, job_id) { return sys.puts('Producer sent job: ' + job_id); }); }); }); //consumer client.connect(null, function(err, conn) { if (err) { return sys.puts('Consumer connection error:', sys, inspect(err)); } else { sys.puts('Consumer connected'); - return conn.watch('test', function() { - return conn.reserve(function(job_id, data) { + return conn.watch('test', function(err) { + return conn.reserve(function(err, job_id, data) { sys.puts('Consumer got job: ' + job_id); sys.puts(' job data: ' + data); - return conn.destroy(job_id, function() { + return conn.destroy(job_id, function(err) { return sys.puts('Consumer destroyed job: ' + job_id); }); }); }); } }); })(); diff --git a/test/test.js b/test/test.js index 5d2c65f..f64976b 100644 --- a/test/test.js +++ b/test/test.js @@ -1,19 +1,18 @@ -var sys = require('sys'); var client = require('../lib/beanstalk_client').Client; client.connect('127.0.0.1:11300', function(err, conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; - conn.put(0, 0, 1, JSON.stringify(job_data), function(job_id) { - sys.puts('put job: ' + job_id); + conn.put(0, 0, 1, JSON.stringify(job_data), function(err, job_id) { + console.log('put job: ' + job_id); - conn.reserve(function(job_id, job_json) { - sys.puts('got job: ' + job_id); - sys.puts('got job data: ' + job_json); - sys.puts('module name is ' + JSON.parse(job_json).data.name); - conn.destroy(job_id, function() { - sys.puts('destroyed job'); + conn.reserve(function(err, job_id, job_json) { + console.log('got job: ' + job_id); + console.log('got job data: ' + job_json); + console.log('module name is ' + JSON.parse(job_json).data.name); + conn.destroy(job_id, function(err) { + console.log('destroyed job'); }); }); }); });
benlund/node-beanstalk-client
fc71fb9db6521259c841411a0bbe59fa17903d6a
added release API call
diff --git a/README b/README index 057293d..dbf2d27 100644 --- a/README +++ b/README @@ -1,31 +1,32 @@ Beanstalkd Client for Node.js ============================= Version: 0.0.1 -- Not all commands are yet implemented -- Example: var sys = require('sys'); var bt = require('lib/beanstalk_client'); bt.Client.connect('127.0.0.1:11300').addCallback(function(conn) { var job_data = {"data": {"name": "node-beanstalk-client"}}; conn.put(0, 0, 1, JSON.stringify(job_data)).addCallback(function(job_id) { sys.puts('put job: ' + job_id); conn.reserve().addCallback(function(job_id, job_json) { sys.puts('got job: ' + job_id); sys.puts('got job data: ' + job_json); sys.puts('module name is ' + JSON.parse(job_json).data.name); conn.destroy(job_id); }); }); }); Try it: $ node test/test.js + \ No newline at end of file diff --git a/lib/beanstalk_client.js b/lib/beanstalk_client.js index 1933f4f..fa64e94 100644 --- a/lib/beanstalk_client.js +++ b/lib/beanstalk_client.js @@ -1,209 +1,211 @@ var events = require('events'), tcp = require('tcp'), Promise= require('./promise').Promise; var sys = require('sys'); var Client = { DEFAULT_ADDR: '127.0.0.1', DEFAULT_PORT: 11300, LOWEST_PRIORITY: 4294967295, connect: function(server) { var addr, port, parts, promise; if(server) { parts = server.split(':'); addr = parts[0]; port = parts[1]; } if(!addr) { addr = this.DEFAULT_ADDR; } if(!port) { port = this.DEFAULT_PORT; } promise = new Promise(); var tcp_conn = tcp.createConnection(port, addr); tcp_conn.addListener('connect', function() { promise.emitSuccess(Connection.make(tcp_conn)); }); tcp_conn.addListener('close', function(had_error) { if(had_error) { promise.emitError(); } }); return promise; } }; var make_command_method = function(command_name, expected_response, sends_data) { return function() { var args = Array.prototype.slice.call(arguments); var data; args.unshift(command_name); var p = this.expect_response(expected_response); if(sends_data) { data = args.pop(); args.push(data.length); } this.send.apply(this, args); if(data){ this.send(data); } return p; }; }; var Connection = { make: function(tcp_conn) { function F() {} F.prototype = this; var self = new F(); self.conn = tcp_conn; //self.conn.setNoDelay(); self.buffer = ''; self.handlers = []; self.conn.addListener('data', function(data) { self.buffer += data; self.try_handling_response(); }); return self; }, close: function() { this.conn.close(); }, expect_response: function(success_code) { var promise = new Promise(); this.handlers.push([ResponseHandler.make(success_code), promise]); return promise; }, try_handling_response: function() { var handler, promise; var handler_and_promise = this.handlers[0]; if(handler_and_promise) { handler = handler_and_promise[0]; promise = handler_and_promise[1]; handler.handle(this.buffer); if(handler.complete) { this.finished_handling_response(); if(handler.success) { promise.emitSuccess.apply(promise, handler.args); } else { promise.emitError.apply(promise, handler.args); } } else { handler.reset(); } } }, finished_handling_response: function() { this.buffer = ''; var hp = this.handlers.shift(); hp = null; }, //handling jobs watch: make_command_method('watch', 'WATCHING'), ignore: make_command_method('ignore', 'WATCHING'), reserve: make_command_method('reserve', 'RESERVED'), reserve_with_timeout: make_command_method('reserve-with-timeout', 'RESERVED'), + destroy: make_command_method('delete', 'DELETED'), + release: make_command_method('release', 'RELEASED'), + bury: make_command_method('bury', 'BURIED'), //submitting jobs use: make_command_method('use', 'USING'), put: make_command_method('put', 'INSERTED', true), - bury: make_command_method('bury', 'BURIED'), // put: function(priority, delay, ttr, data) { // var p = this.expect_response('INSERTED'); // this.send('put', priority, delay, ttr, data.length); // this.send(data); // return p; // }, send: function() { this.conn.write(Array.prototype.slice.call(arguments).join(' ') + "\r\n"); } }; var ResponseHandler = { make: function(success_code) { function F() {} F.prototype = this; var self = new F(); self.success_code = success_code; return self; }, reset: function() { this.complete = false; this.success = false; this.args = undefined; this.header = undefined; this.body = undefined; }, CODES_REQUIRING_BODY: { 'RESERVED': true }, handle: function(data) { var args, code; var i = data.indexOf("\r\n"); if(i >= 0) { this.header = data.substr(0, i); this.body = data.substr(i + 2); this.args = this.header.split(' '); code = this.args[0]; if(code === this.success_code) { this.args.shift(); //don't include the code in the success args, but do in the err args this.success = true; } if(this.CODES_REQUIRING_BODY[code]) { this.parse_body(); } else { this.complete = true; } } }, parse_body: function() { var body_length; if('undefined' !== typeof this.body) { body_length = parseInt(this.args[this.args.length - 1], 10); if(this.body.length === (body_length + 2)) { this.args.pop(); //removed the length and add the data this.args.push(this.body.substr(0, this.body.length-2)); this.complete = true; } } } }; exports.Client = Client;
benlund/node-beanstalk-client
af7fb0fa0d1574ff72b3ebeee18e911625b343b3
switched to sys.inherits
diff --git a/lib/beanstalk_client.js b/lib/beanstalk_client.js index 121ecd3..1933f4f 100644 --- a/lib/beanstalk_client.js +++ b/lib/beanstalk_client.js @@ -1,208 +1,209 @@ var events = require('events'), tcp = require('tcp'), Promise= require('./promise').Promise; var sys = require('sys'); var Client = { DEFAULT_ADDR: '127.0.0.1', DEFAULT_PORT: 11300, LOWEST_PRIORITY: 4294967295, connect: function(server) { var addr, port, parts, promise; if(server) { parts = server.split(':'); addr = parts[0]; port = parts[1]; } if(!addr) { addr = this.DEFAULT_ADDR; } if(!port) { port = this.DEFAULT_PORT; } promise = new Promise(); var tcp_conn = tcp.createConnection(port, addr); tcp_conn.addListener('connect', function() { promise.emitSuccess(Connection.make(tcp_conn)); }); tcp_conn.addListener('close', function(had_error) { if(had_error) { promise.emitError(); } }); return promise; } }; var make_command_method = function(command_name, expected_response, sends_data) { return function() { var args = Array.prototype.slice.call(arguments); var data; args.unshift(command_name); var p = this.expect_response(expected_response); if(sends_data) { data = args.pop(); args.push(data.length); } this.send.apply(this, args); if(data){ this.send(data); } return p; }; }; var Connection = { make: function(tcp_conn) { function F() {} F.prototype = this; var self = new F(); self.conn = tcp_conn; //self.conn.setNoDelay(); self.buffer = ''; self.handlers = []; self.conn.addListener('data', function(data) { self.buffer += data; self.try_handling_response(); }); return self; }, close: function() { this.conn.close(); }, expect_response: function(success_code) { var promise = new Promise(); this.handlers.push([ResponseHandler.make(success_code), promise]); return promise; }, try_handling_response: function() { var handler, promise; var handler_and_promise = this.handlers[0]; if(handler_and_promise) { handler = handler_and_promise[0]; promise = handler_and_promise[1]; handler.handle(this.buffer); if(handler.complete) { this.finished_handling_response(); if(handler.success) { promise.emitSuccess.apply(promise, handler.args); } else { promise.emitError.apply(promise, handler.args); } } else { handler.reset(); } } }, finished_handling_response: function() { this.buffer = ''; - this.handlers.shift(); + var hp = this.handlers.shift(); + hp = null; }, //handling jobs watch: make_command_method('watch', 'WATCHING'), ignore: make_command_method('ignore', 'WATCHING'), reserve: make_command_method('reserve', 'RESERVED'), reserve_with_timeout: make_command_method('reserve-with-timeout', 'RESERVED'), destroy: make_command_method('delete', 'DELETED'), //submitting jobs use: make_command_method('use', 'USING'), put: make_command_method('put', 'INSERTED', true), bury: make_command_method('bury', 'BURIED'), // put: function(priority, delay, ttr, data) { // var p = this.expect_response('INSERTED'); // this.send('put', priority, delay, ttr, data.length); // this.send(data); // return p; // }, send: function() { this.conn.write(Array.prototype.slice.call(arguments).join(' ') + "\r\n"); } }; var ResponseHandler = { make: function(success_code) { function F() {} F.prototype = this; var self = new F(); self.success_code = success_code; return self; }, reset: function() { this.complete = false; this.success = false; this.args = undefined; this.header = undefined; this.body = undefined; }, CODES_REQUIRING_BODY: { 'RESERVED': true }, handle: function(data) { var args, code; var i = data.indexOf("\r\n"); if(i >= 0) { this.header = data.substr(0, i); this.body = data.substr(i + 2); this.args = this.header.split(' '); code = this.args[0]; if(code === this.success_code) { this.args.shift(); //don't include the code in the success args, but do in the err args this.success = true; } if(this.CODES_REQUIRING_BODY[code]) { this.parse_body(); } else { this.complete = true; } } }, parse_body: function() { var body_length; if('undefined' !== typeof this.body) { body_length = parseInt(this.args[this.args.length - 1], 10); if(this.body.length === (body_length + 2)) { this.args.pop(); //removed the length and add the data this.args.push(this.body.substr(0, this.body.length-2)); this.complete = true; } } } }; exports.Client = Client; diff --git a/lib/promise.js b/lib/promise.js index 67a4312..99f5ad0 100644 --- a/lib/promise.js +++ b/lib/promise.js @@ -1,165 +1,166 @@ //Promise object extracted from old vesion of node.js source -- to be removed soon -events = require('events'); +var events = require('events'); +var sys = require('sys'); exports.Promise = function () { events.EventEmitter.call(this); this._blocking = false; this.hasFired = false; this._values = undefined; }; -process.inherits(exports.Promise, events.EventEmitter); +sys.inherits(exports.Promise, events.EventEmitter); exports.Promise.prototype.timeout = function(timeout) { if (!timeout) { return this._timeoutDuration; } this._timeoutDuration = timeout; if (this.hasFired) return; this._clearTimeout(); var self = this; this._timer = setTimeout(function() { self._timer = null; if (self.hasFired) { return; } self.emitError(new Error('timeout')); }, timeout); return this; }; exports.Promise.prototype._clearTimeout = function() { if (!this._timer) return; clearTimeout(this._timer); this._timer = null; }; exports.Promise.prototype.emitSuccess = function() { if (this.hasFired) return; this.hasFired = 'success'; this._clearTimeout(); this._values = Array.prototype.slice.call(arguments); this.emit.apply(this, ['success'].concat(this._values)); }; exports.Promise.prototype.emitError = function() { if (this.hasFired) return; this.hasFired = 'error'; this._clearTimeout(); this._values = Array.prototype.slice.call(arguments); this.emit.apply(this, ['error'].concat(this._values)); if (this.listeners('error').length == 0) { var self = this; process.nextTick(function() { if (self.listeners('error').length == 0) { throw (self._values[0] instanceof Error) ? self._values[0] : new Error('Unhandled emitError: '+JSON.stringify(self._values)); } }); } }; exports.Promise.prototype.addCallback = function (listener) { if (this.hasFired === 'success') { listener.apply(this, this._values); } return this.addListener("success", listener); }; exports.Promise.prototype.addErrback = function (listener) { if (this.hasFired === 'error') { listener.apply(this, this._values); } return this.addListener("error", listener); };
benlund/node-beanstalk-client
56c0bd251b9fdef45a6ca1b29d09361500df4b01
added README
diff --git a/README b/README index e69de29..057293d 100644 --- a/README +++ b/README @@ -0,0 +1,31 @@ +Beanstalkd Client for Node.js +============================= + +Version: 0.0.1 + +-- Not all commands are yet implemented -- + +Example: + +var sys = require('sys'); +var bt = require('lib/beanstalk_client'); + +bt.Client.connect('127.0.0.1:11300').addCallback(function(conn) { + var job_data = {"data": {"name": "node-beanstalk-client"}}; + conn.put(0, 0, 1, JSON.stringify(job_data)).addCallback(function(job_id) { + + sys.puts('put job: ' + job_id); + + conn.reserve().addCallback(function(job_id, job_json) { + sys.puts('got job: ' + job_id); + sys.puts('got job data: ' + job_json); + sys.puts('module name is ' + JSON.parse(job_json).data.name); + conn.destroy(job_id); + }); + + }); +}); + +Try it: + +$ node test/test.js
benlund/node-beanstalk-client
866eeac38abe2be32afbfbee7702b0ba756d0073
version 0.0.1
diff --git a/lib/beanstalk_client.js b/lib/beanstalk_client.js new file mode 100644 index 0000000..121ecd3 --- /dev/null +++ b/lib/beanstalk_client.js @@ -0,0 +1,208 @@ +var events = require('events'), + tcp = require('tcp'), + Promise= require('./promise').Promise; + +var sys = require('sys'); + +var Client = { + + DEFAULT_ADDR: '127.0.0.1', + DEFAULT_PORT: 11300, + + LOWEST_PRIORITY: 4294967295, + + connect: function(server) { + var addr, port, + parts, + promise; + + if(server) { + parts = server.split(':'); + addr = parts[0]; + port = parts[1]; + } + if(!addr) { + addr = this.DEFAULT_ADDR; + } + if(!port) { + port = this.DEFAULT_PORT; + } + + promise = new Promise(); + + + var tcp_conn = tcp.createConnection(port, addr); + tcp_conn.addListener('connect', function() { + promise.emitSuccess(Connection.make(tcp_conn)); + }); + tcp_conn.addListener('close', function(had_error) { + if(had_error) { + promise.emitError(); + } + }); + + return promise; + } + +}; + +var make_command_method = function(command_name, expected_response, sends_data) { + return function() { + var args = Array.prototype.slice.call(arguments); + var data; + args.unshift(command_name); + var p = this.expect_response(expected_response); + if(sends_data) { + data = args.pop(); + args.push(data.length); + } + this.send.apply(this, args); + if(data){ + this.send(data); + } + return p; + }; +}; + +var Connection = { + make: function(tcp_conn) { + function F() {} + F.prototype = this; + var self = new F(); + self.conn = tcp_conn; + //self.conn.setNoDelay(); + self.buffer = ''; + self.handlers = []; + self.conn.addListener('data', function(data) { + self.buffer += data; + self.try_handling_response(); + }); + return self; + }, + + close: function() { + this.conn.close(); + }, + + expect_response: function(success_code) { + var promise = new Promise(); + this.handlers.push([ResponseHandler.make(success_code), promise]); + return promise; + }, + + try_handling_response: function() { + var handler, promise; + var handler_and_promise = this.handlers[0]; + if(handler_and_promise) { + handler = handler_and_promise[0]; + promise = handler_and_promise[1]; + + handler.handle(this.buffer); + + if(handler.complete) { + this.finished_handling_response(); + if(handler.success) { + promise.emitSuccess.apply(promise, handler.args); + } + else { + promise.emitError.apply(promise, handler.args); + } + } + else { + handler.reset(); + } + } + }, + + finished_handling_response: function() { + this.buffer = ''; + this.handlers.shift(); + }, + + //handling jobs + watch: make_command_method('watch', 'WATCHING'), + ignore: make_command_method('ignore', 'WATCHING'), + reserve: make_command_method('reserve', 'RESERVED'), + reserve_with_timeout: make_command_method('reserve-with-timeout', 'RESERVED'), + destroy: make_command_method('delete', 'DELETED'), + + //submitting jobs + use: make_command_method('use', 'USING'), + put: make_command_method('put', 'INSERTED', true), + bury: make_command_method('bury', 'BURIED'), + +// put: function(priority, delay, ttr, data) { +// var p = this.expect_response('INSERTED'); +// this.send('put', priority, delay, ttr, data.length); +// this.send(data); + +// return p; +// }, + + send: function() { + this.conn.write(Array.prototype.slice.call(arguments).join(' ') + "\r\n"); + } + +}; + +var ResponseHandler = { + + make: function(success_code) { + function F() {} + F.prototype = this; + var self = new F(); + self.success_code = success_code; + return self; + }, + + reset: function() { + this.complete = false; + this.success = false; + this.args = undefined; + + this.header = undefined; + this.body = undefined; + }, + + CODES_REQUIRING_BODY: { + 'RESERVED': true + }, + + handle: function(data) { + var args, code; + var i = data.indexOf("\r\n"); + + if(i >= 0) { + this.header = data.substr(0, i); + this.body = data.substr(i + 2); + this.args = this.header.split(' '); + code = this.args[0]; + if(code === this.success_code) { + this.args.shift(); //don't include the code in the success args, but do in the err args + this.success = true; + } + if(this.CODES_REQUIRING_BODY[code]) { + this.parse_body(); + } + else { + this.complete = true; + } + } + }, + + parse_body: function() { + var body_length; + if('undefined' !== typeof this.body) { + body_length = parseInt(this.args[this.args.length - 1], 10); + if(this.body.length === (body_length + 2)) { + this.args.pop(); //removed the length and add the data + this.args.push(this.body.substr(0, this.body.length-2)); + this.complete = true; + } + } + } + + +}; + +exports.Client = Client; diff --git a/lib/promise.js b/lib/promise.js new file mode 100644 index 0000000..67a4312 --- /dev/null +++ b/lib/promise.js @@ -0,0 +1,165 @@ +//Promise object extracted from old vesion of node.js source -- to be removed soon + +events = require('events'); + +exports.Promise = function () { + + events.EventEmitter.call(this); + + this._blocking = false; + + this.hasFired = false; + + this._values = undefined; + +}; + +process.inherits(exports.Promise, events.EventEmitter); + +exports.Promise.prototype.timeout = function(timeout) { + + if (!timeout) { + + return this._timeoutDuration; + + } + + + + this._timeoutDuration = timeout; + + + + if (this.hasFired) return; + + this._clearTimeout(); + + + + var self = this; + + this._timer = setTimeout(function() { + + self._timer = null; + + if (self.hasFired) { + + return; + + } + + + + self.emitError(new Error('timeout')); + + }, timeout); + + + + return this; + +}; + + + +exports.Promise.prototype._clearTimeout = function() { + + if (!this._timer) return; + + + + clearTimeout(this._timer); + + this._timer = null; + +}; + + + +exports.Promise.prototype.emitSuccess = function() { + + if (this.hasFired) return; + + this.hasFired = 'success'; + + this._clearTimeout(); + + + + this._values = Array.prototype.slice.call(arguments); + + this.emit.apply(this, ['success'].concat(this._values)); + +}; + + + +exports.Promise.prototype.emitError = function() { + + if (this.hasFired) return; + + this.hasFired = 'error'; + + this._clearTimeout(); + + + + this._values = Array.prototype.slice.call(arguments); + + this.emit.apply(this, ['error'].concat(this._values)); + + + + if (this.listeners('error').length == 0) { + + var self = this; + + process.nextTick(function() { + + if (self.listeners('error').length == 0) { + + throw (self._values[0] instanceof Error) + + ? self._values[0] + + : new Error('Unhandled emitError: '+JSON.stringify(self._values)); + + } + + }); + + } + +}; + + + +exports.Promise.prototype.addCallback = function (listener) { + + if (this.hasFired === 'success') { + + listener.apply(this, this._values); + + } + + + + return this.addListener("success", listener); + +}; + + + +exports.Promise.prototype.addErrback = function (listener) { + + if (this.hasFired === 'error') { + + listener.apply(this, this._values); + + } + + + + return this.addListener("error", listener); + +}; diff --git a/test/test.js b/test/test.js new file mode 100644 index 0000000..06c4be6 --- /dev/null +++ b/test/test.js @@ -0,0 +1,18 @@ +var sys = require('sys'); +var bt = require('../lib/beanstalk_client'); + +bt.Client.connect('127.0.0.1:11300').addCallback(function(conn) { + var job_data = {"data": {"name": "node-beanstalk-client"}}; + conn.put(0, 0, 1, JSON.stringify(job_data)).addCallback(function(job_id) { + + sys.puts('put job: ' + job_id); + + conn.reserve().addCallback(function(job_id, job_json) { + sys.puts('got job: ' + job_id); + sys.puts('got job data: ' + job_json); + sys.puts('module name is ' + JSON.parse(job_json).data.name); + conn.destroy(job_id); + }); + + }); +});
markpasc/textmate-emptylines
b0b34cce91fd2893dfa31e17721be0bc528669d1
Fake the document into reloading if the sed succeeded by changing the last-mod date Look for trailing tabs, not backslashes and t's
diff --git a/Emptylines.h b/Emptylines.h index 4b749eb..0eabae5 100644 --- a/Emptylines.h +++ b/Emptylines.h @@ -1,38 +1,42 @@ // // Emptylines.h // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import <Cocoa/Cocoa.h> @protocol TMPlugInController - (float)version; @end @interface OakDocument : NSObject { NSString* filename; } + +-(NSString*) filename; +-(BOOL) checkForFilesystemChanges; +-(BOOL) setFileModificationDate:(id)fp1; @end @interface OakDocumentController : NSWindowController { NSObject *textView; id statusBar; OakDocument *textDocument; } @end @interface OakDocumentController (Unspacer) - (void) saveUnspacedDocument:(id)fp8; @end @interface Emptylines : NSObject { } - (id)initWithPlugInController:(id <TMPlugInController>)aController; - (void)installSaver; @end \ No newline at end of file diff --git a/Emptylines.mm b/Emptylines.mm index 27f7e28..a4a4e5b 100644 --- a/Emptylines.mm +++ b/Emptylines.mm @@ -1,55 +1,58 @@ // // Emptylines.mm // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import </usr/include/objc/runtime.h> #import "Emptylines.h" #import "MethodSwizzle.h" @implementation OakDocumentController (Unspacer) - (void)saveUnspacedDocument:(id)fp8 { // Call the swizzled original method. [self saveUnspacedDocument:fp8]; // sed us some fileage. NSString* fn = [textDocument filename]; + if (!fn) return; + NSTask* jerb = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/sed" arguments: - [NSArray arrayWithObjects:@"-i",@"",@"-e",@"s/[ \\t]*$//g",fn,nil]]; + [NSArray arrayWithObjects:@"-i",@"",@"-e",@"s/[ \t]*$//g",fn,nil]]; [jerb waitUntilExit]; // meh - NSLog(@"YAY SED ENDED VIA %d", [jerb terminationStatus]); if ([jerb terminationStatus] == 0) { - NSLog(@"YAY I SHOULD RELOAD NOW"); + // Make me reload. + [textDocument setFileModificationDate:[NSDate distantPast]]; + [textDocument checkForFilesystemChanges]; } } @end @implementation Emptylines - (id)initWithPlugInController:(id <TMPlugInController>)aController { self = [self init]; NSApp = [NSApplication sharedApplication]; if (self) [self installSaver]; return self; } - (void)installSaver { MethodSwizzle(NSClassFromString(@"OakDocumentController"), @selector(saveDocument:), @selector(saveUnspacedDocument:)); } @end
markpasc/textmate-emptylines
cd7a3395013eeb90b083a08e136e5c78c5b61bf5
Use NSTask to run a sed instead of screwing around in memory
diff --git a/Emptylines.h b/Emptylines.h index e59e2c5..4b749eb 100644 --- a/Emptylines.h +++ b/Emptylines.h @@ -1,27 +1,38 @@ // // Emptylines.h // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import <Cocoa/Cocoa.h> @protocol TMPlugInController - (float)version; @end +@interface OakDocument : NSObject +{ + NSString* filename; +} +@end + +@interface OakDocumentController : NSWindowController +{ + NSObject *textView; + id statusBar; + OakDocument *textDocument; +} +@end + @interface OakDocumentController (Unspacer) - (void) saveUnspacedDocument:(id)fp8; @end @interface Emptylines : NSObject { - NSMenu* fileMenu; - NSMenuItem* oldSaver; } - (id)initWithPlugInController:(id <TMPlugInController>)aController; - (void)installSaver; -- (void)saveDocument:(id)fp8; @end \ No newline at end of file diff --git a/Emptylines.mm b/Emptylines.mm index e3d10e3..27f7e28 100644 --- a/Emptylines.mm +++ b/Emptylines.mm @@ -1,53 +1,55 @@ // // Emptylines.mm // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import </usr/include/objc/runtime.h> #import "Emptylines.h" #import "MethodSwizzle.h" @implementation OakDocumentController (Unspacer) - (void)saveUnspacedDocument:(id)fp8 { - NSLog(@"OH HAI SAVER OF DOCUMENTSES"); + // Call the swizzled original method. + [self saveUnspacedDocument:fp8]; - unsigned int count; - Method* foo = class_copyMethodList(NSClassFromString(@"OakDocumentController"), &count); - NSLog(@"YAY GOT %d METHODS", count); - for (; count; count--) { - NSLog(@"YAY METHOD %s", sel_getName(method_getName(foo[count - 1]))); - } + // sed us some fileage. + NSString* fn = [textDocument filename]; + NSTask* jerb = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/sed" arguments: + [NSArray arrayWithObjects:@"-i",@"",@"-e",@"s/[ \\t]*$//g",fn,nil]]; + [jerb waitUntilExit]; // meh - // Call the swizzled original method. - [self saveUnspacedDocument]; + NSLog(@"YAY SED ENDED VIA %d", [jerb terminationStatus]); + if ([jerb terminationStatus] == 0) { + NSLog(@"YAY I SHOULD RELOAD NOW"); + } } @end @implementation Emptylines - (id)initWithPlugInController:(id <TMPlugInController>)aController { self = [self init]; NSApp = [NSApplication sharedApplication]; if (self) [self installSaver]; return self; } - (void)installSaver { - MethodSwizzle(NSClassFromString("OakDocumentController"), + MethodSwizzle(NSClassFromString(@"OakDocumentController"), @selector(saveDocument:), @selector(saveUnspacedDocument:)); } @end
markpasc/textmate-emptylines
c7c670d93affb14dd005d93871af5dd6459dedea
Move test document saver to a swizzly category
diff --git a/Emptylines.h b/Emptylines.h index 943f102..e59e2c5 100644 --- a/Emptylines.h +++ b/Emptylines.h @@ -1,23 +1,27 @@ // // Emptylines.h // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import <Cocoa/Cocoa.h> @protocol TMPlugInController - (float)version; @end +@interface OakDocumentController (Unspacer) +- (void) saveUnspacedDocument:(id)fp8; +@end + @interface Emptylines : NSObject { NSMenu* fileMenu; NSMenuItem* oldSaver; } - (id)initWithPlugInController:(id <TMPlugInController>)aController; - (void)installSaver; - (void)saveDocument:(id)fp8; @end \ No newline at end of file diff --git a/Emptylines.mm b/Emptylines.mm index 333d590..e3d10e3 100644 --- a/Emptylines.mm +++ b/Emptylines.mm @@ -1,57 +1,53 @@ // // Emptylines.mm // Emptylines // // Created by mark on 3/25/09. // Copyright 2009 Six Apart, Ltd.. All rights reserved. // #import </usr/include/objc/runtime.h> #import "Emptylines.h" #import "MethodSwizzle.h" +@implementation OakDocumentController (Unspacer) + +- (void)saveUnspacedDocument:(id)fp8 +{ + NSLog(@"OH HAI SAVER OF DOCUMENTSES"); + + unsigned int count; + Method* foo = class_copyMethodList(NSClassFromString(@"OakDocumentController"), &count); + NSLog(@"YAY GOT %d METHODS", count); + for (; count; count--) { + NSLog(@"YAY METHOD %s", sel_getName(method_getName(foo[count - 1]))); + } + + // Call the swizzled original method. + [self saveUnspacedDocument]; +} + +@end + @implementation Emptylines - (id)initWithPlugInController:(id <TMPlugInController>)aController { self = [self init]; NSApp = [NSApplication sharedApplication]; if (self) [self installSaver]; return self; } - (void)installSaver { - fileMenu = [[[NSApp mainMenu] itemWithTitle:@"File"] submenu]; - if (!fileMenu) - return; - [fileMenu retain]; - - int oldSaverIndex = [fileMenu indexOfItemWithTitle:@"Save"]; - oldSaver = [[fileMenu itemAtIndex:oldSaverIndex] retain]; - [fileMenu removeItemAtIndex:oldSaverIndex]; - - NSMenuItem* newSaver = [[NSMenuItem alloc] initWithTitle:@"Save Without Spaces" action:@selector(saveDocument:) keyEquivalent:@"s"]; - [newSaver setTarget:self]; - [newSaver setKeyEquivalentModifierMask:NSCommandKeyMask]; - - [fileMenu insertItem:newSaver atIndex:oldSaverIndex]; -} - -- (void)saveDocument:(id)fp8 -{ - NSLog(@"OH HAI SAVER OF DOCUMENTSES"); - - unsigned int count; - Method* foo = class_copyMethodList(NSClassFromString(@"OakDocumentController"), &count); - NSLog(@"YAY GOT %d METHODS", count); - for (; count; count--) { - NSLog(@"YAY METHOD %s", sel_getName(method_getName(foo[count - 1]))); - } + MethodSwizzle(NSClassFromString("OakDocumentController"), + @selector(saveDocument:), + @selector(saveUnspacedDocument:)); } @end
markpasc/textmate-emptylines
2cb54a19966152812aa3c90a15d2c9c26cda970f
import without products or project files
diff --git a/Emptylines.h b/Emptylines.h new file mode 100644 index 0000000..943f102 --- /dev/null +++ b/Emptylines.h @@ -0,0 +1,23 @@ +// +// Emptylines.h +// Emptylines +// +// Created by mark on 3/25/09. +// Copyright 2009 Six Apart, Ltd.. All rights reserved. +// + +#import <Cocoa/Cocoa.h> + +@protocol TMPlugInController +- (float)version; +@end + +@interface Emptylines : NSObject +{ + NSMenu* fileMenu; + NSMenuItem* oldSaver; +} +- (id)initWithPlugInController:(id <TMPlugInController>)aController; +- (void)installSaver; +- (void)saveDocument:(id)fp8; +@end \ No newline at end of file diff --git a/Emptylines.mm b/Emptylines.mm new file mode 100644 index 0000000..333d590 --- /dev/null +++ b/Emptylines.mm @@ -0,0 +1,57 @@ +// +// Emptylines.mm +// Emptylines +// +// Created by mark on 3/25/09. +// Copyright 2009 Six Apart, Ltd.. All rights reserved. +// + +#import </usr/include/objc/runtime.h> + +#import "Emptylines.h" +#import "MethodSwizzle.h" + +@implementation Emptylines + +- (id)initWithPlugInController:(id <TMPlugInController>)aController +{ + self = [self init]; + NSApp = [NSApplication sharedApplication]; + + if (self) + [self installSaver]; + + return self; +} + +- (void)installSaver +{ + fileMenu = [[[NSApp mainMenu] itemWithTitle:@"File"] submenu]; + if (!fileMenu) + return; + [fileMenu retain]; + + int oldSaverIndex = [fileMenu indexOfItemWithTitle:@"Save"]; + oldSaver = [[fileMenu itemAtIndex:oldSaverIndex] retain]; + [fileMenu removeItemAtIndex:oldSaverIndex]; + + NSMenuItem* newSaver = [[NSMenuItem alloc] initWithTitle:@"Save Without Spaces" action:@selector(saveDocument:) keyEquivalent:@"s"]; + [newSaver setTarget:self]; + [newSaver setKeyEquivalentModifierMask:NSCommandKeyMask]; + + [fileMenu insertItem:newSaver atIndex:oldSaverIndex]; +} + +- (void)saveDocument:(id)fp8 +{ + NSLog(@"OH HAI SAVER OF DOCUMENTSES"); + + unsigned int count; + Method* foo = class_copyMethodList(NSClassFromString(@"OakDocumentController"), &count); + NSLog(@"YAY GOT %d METHODS", count); + for (; count; count--) { + NSLog(@"YAY METHOD %s", sel_getName(method_getName(foo[count - 1]))); + } +} + +@end diff --git a/Emptylines_Prefix.pch b/Emptylines_Prefix.pch new file mode 100644 index 0000000..d164ffb --- /dev/null +++ b/Emptylines_Prefix.pch @@ -0,0 +1,7 @@ +// +// Prefix header for all source files of the 'Emptylines' target in the 'Emptylines' project. +// + +#ifdef __OBJC__ + #import <Cocoa/Cocoa.h> +#endif diff --git a/English.lproj/.svn/all-wcprops b/English.lproj/.svn/all-wcprops new file mode 100644 index 0000000..0d3a782 --- /dev/null +++ b/English.lproj/.svn/all-wcprops @@ -0,0 +1,11 @@ +K 25 +svn:wc:ra_dav:version-url +V 59 +/!svn/ver/10901/trunk/Tools/TextMate%20Plugin/English.lproj +END +InfoPlist.strings +K 25 +svn:wc:ra_dav:version-url +V 77 +/!svn/ver/10901/trunk/Tools/TextMate%20Plugin/English.lproj/InfoPlist.strings +END diff --git a/English.lproj/.svn/entries b/English.lproj/.svn/entries new file mode 100644 index 0000000..e134bae --- /dev/null +++ b/English.lproj/.svn/entries @@ -0,0 +1,41 @@ +8 + +dir +11410 +http://svn.textmate.org/trunk/Tools/TextMate%20Plugin/English.lproj +http://svn.textmate.org + + + +2008-11-29T17:44:36.553170Z +10901 +ciaran + + +svn:special svn:externals svn:needs-lock + + + + + + + + + + + +dfb7d73b-c2ec-0310-8fea-fb051d288c6d + +InfoPlist.strings +file + + + + +2009-03-25T23:00:37.000000Z +503b02bf710f69136bc65c133bd75c2f +2008-11-29T17:44:36.553170Z +10901 +ciaran +has-props + diff --git a/English.lproj/.svn/format b/English.lproj/.svn/format new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/English.lproj/.svn/format @@ -0,0 +1 @@ +8 diff --git a/English.lproj/.svn/prop-base/InfoPlist.strings.svn-base b/English.lproj/.svn/prop-base/InfoPlist.strings.svn-base new file mode 100644 index 0000000..5e9587e --- /dev/null +++ b/English.lproj/.svn/prop-base/InfoPlist.strings.svn-base @@ -0,0 +1,5 @@ +K 13 +svn:mime-type +V 24 +application/octet-stream +END diff --git a/English.lproj/.svn/text-base/InfoPlist.strings.svn-base b/English.lproj/.svn/text-base/InfoPlist.strings.svn-base new file mode 100644 index 0000000..20ab7da Binary files /dev/null and b/English.lproj/.svn/text-base/InfoPlist.strings.svn-base differ diff --git a/English.lproj/InfoPlist.strings b/English.lproj/InfoPlist.strings new file mode 100644 index 0000000..5e7429a Binary files /dev/null and b/English.lproj/InfoPlist.strings differ diff --git a/Info.plist b/Info.plist new file mode 100644 index 0000000..fd6e966 --- /dev/null +++ b/Info.plist @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleExecutable</key> + <string>${EXECUTABLE_NAME}</string> + <key>CFBundleName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundleIconFile</key> + <string></string> + <key>CFBundleIdentifier</key> + <string>com.yourcompany.yourtmplugin</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundlePackageType</key> + <string>BNDL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1.0</string> + <key>NSPrincipalClass</key> + <string></string> +</dict> +</plist> diff --git a/MethodSwizzle.h b/MethodSwizzle.h new file mode 100644 index 0000000..0bed2b8 --- /dev/null +++ b/MethodSwizzle.h @@ -0,0 +1,37 @@ +// +// MethodSwizzle.h +// +// Copyright (c) 2006 Tildesoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +#import <objc/objc.h> + +#ifdef __cplusplus +extern "C" { +#endif + +#import <objc/objc.h> + +BOOL ClassMethodSwizzle(Class klass, SEL origSel, SEL altSel); +BOOL MethodSwizzle(Class klass, SEL origSel, SEL altSel); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/MethodSwizzle.m b/MethodSwizzle.m new file mode 100644 index 0000000..4c838b4 --- /dev/null +++ b/MethodSwizzle.m @@ -0,0 +1,123 @@ +// +// MethodSwizzle.m +// +// Copyright (c) 2006 Tildesoft. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +// Implementation of Method Swizzling, inspired by +// http://www.cocoadev.com/index.pl?MethodSwizzling + +// solves the inherited method problem + +#import "MethodSwizzle.h" +#import <stdlib.h> +#import <string.h> +#import <objc/objc-runtime.h> +#import <objc/objc-class.h> +#import <uuid/uuid.h> + +static BOOL _PerformSwizzle(Class klass, SEL origSel, SEL altSel, BOOL forInstance); + +BOOL ClassMethodSwizzle(Class klass, SEL origSel, SEL altSel) { + return _PerformSwizzle(klass, origSel, altSel, NO); +} + +BOOL MethodSwizzle(Class klass, SEL origSel, SEL altSel) { + return _PerformSwizzle(klass, origSel, altSel, YES); +} + +// if the origSel isn't present in the class, pull it up from where it exists +// then do the swizzle +BOOL _PerformSwizzle(Class klass, SEL origSel, SEL altSel, BOOL forInstance) { + // First, make sure the class isn't nil + if (klass != nil) { + Method origMethod = NULL, altMethod = NULL; + + // Next, look for the methods + Class iterKlass = (forInstance ? klass : klass->isa); + void *iterator = NULL; + struct objc_method_list *mlist = class_nextMethodList(iterKlass, &iterator); + while (mlist != NULL) { + int i; + for (i = 0; i < mlist->method_count; ++i) { + if (mlist->method_list[i].method_name == origSel) { + origMethod = &mlist->method_list[i]; + break; + } + if (mlist->method_list[i].method_name == altSel) { + altMethod = &mlist->method_list[i]; + break; + } + } + mlist = class_nextMethodList(iterKlass, &iterator); + } + + if (origMethod == NULL || altMethod == NULL) { + // one or both methods are not in the immediate class + // try searching the entire hierarchy + // remember, iterKlass is the class we care about - klass || klass->isa + // class_getInstanceMethod on a metaclass is the same as class_getClassMethod on the real class + BOOL pullOrig = NO, pullAlt = NO; + if (origMethod == NULL) { + origMethod = class_getInstanceMethod(iterKlass, origSel); + pullOrig = YES; + } + if (altMethod == NULL) { + altMethod = class_getInstanceMethod(iterKlass, altSel); + pullAlt = YES; + } + + // die now if one of the methods doesn't exist anywhere in the hierarchy + // this way we won't make any changes to the class if we can't finish + if (origMethod == NULL || altMethod == NULL) { + NSLog(@"origMethod: %d altMethod: %d", origMethod, altMethod); + return NO; + } + + // we can safely assume one of the two methods, at least, will be pulled + // pull them up + size_t listSize = sizeof(struct objc_method_list); + if (pullOrig && pullAlt) listSize += sizeof(struct objc_method); // need 2 methods + struct objc_method_list *mlist = malloc(listSize); + mlist->obsolete = NULL; + int i = 0; + if (pullOrig) { + memcpy(&mlist->method_list[i], origMethod, sizeof(struct objc_method)); + origMethod = &mlist->method_list[i]; + i++; + } + if (pullAlt) { + memcpy(&mlist->method_list[i], altMethod, sizeof(struct objc_method)); + altMethod = &mlist->method_list[i]; + i++; + } + mlist->method_count = i; + class_addMethods(iterKlass, mlist); + } + + // now swizzle + IMP temp = origMethod->method_imp; + origMethod->method_imp = altMethod->method_imp; + altMethod->method_imp = temp; + + return YES; + } + return NO; +} diff --git a/README.mdown b/README.mdown new file mode 100644 index 0000000..0129d25 --- /dev/null +++ b/README.mdown @@ -0,0 +1,15 @@ +# TextMate Plugin Project Template + +This is a project template for Xcode that can be used to create a new, empty project for a TextMate plug-in. + +## Installation + +### Xcode 3.0+ + +Copy this directory to `/Developer/Library/Xcode/Project Templates/Bundle/`. Then the template will appear in the _New Project_ window in Xcode, under the _Bundle_ section. + + +### Xcode 2.0+ + +Copy this directory to `/Library/Application Support/Apple/Developer Tools/Project Templates/Bundle`. Then the template will appear in the _New Project_ window in Xcode, under the _Bundle_ section. + diff --git a/class-dump.mm b/class-dump.mm new file mode 100644 index 0000000..893c4db --- /dev/null +++ b/class-dump.mm @@ -0,0 +1,3763 @@ +/* + * Generated by class-dump 3.1.1. + * + * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2006 by Steve Nygard. + */ + +struct ATSUI_render { + struct TextLayout _field1; + struct list<ATSUI_render::new_node, std::allocator<ATSUI_render::new_node>> _field2; +}; + +struct ATSUTab; + +struct OakClickInfo { + int type; + unsigned int tabIndex; +}; + +struct OpaqueMenuRef; + +struct TextLayout { + unsigned int atsuFontID; + int fontSize; + int M_ascend; + int M_descend; + int M_charWidth; + unsigned int M_lineHeight; + struct vector<ATSUTab, std::allocator<ATSUTab>> tabStops; + unsigned int tabSize; + _Bool antiAlias; +}; + +struct _Alloc_hider { + char *_M_p; +}; + +struct _Deque_impl { + struct callback_record **_M_map; + unsigned int _M_map_size; + struct _Deque_iterator<callback_record, callback_record&, callback_record*> _M_start; + struct _Deque_iterator<callback_record, callback_record&, callback_record*> _M_finish; +}; + +struct _Deque_iterator<callback_record, callback_record&, callback_record*> { + struct callback_record *_M_cur; + struct callback_record *_M_first; + struct callback_record *_M_last; + struct callback_record **_M_node; +}; + +struct _Deque_iterator<text::undo_manager::node, text::undo_manager::node&, text::undo_manager::node*> { + struct node *_field1; + struct node *_field2; + struct node *_field3; + struct node **_field4; +}; + +struct _List_impl { + struct _List_node_base _M_node; +}; + +struct _List_iterator<text::storage::observer*> { + struct _List_node_base *_field1; +}; + +struct _List_node_base { + struct _List_node_base *_M_next; + struct _List_node_base *_M_prev; +}; + +struct _NSPoint { + float x; + float y; +}; + +struct _NSRange { + unsigned int _field1; + unsigned int _field2; +}; + +struct _NSRect { + struct _NSPoint origin; + struct _NSSize size; +}; + +struct _NSSize { + float width; + float height; +}; + +struct _NSZone; + +struct _Rb_tree<bit_stack::storage, std::pair<const bit_stack::storage, objc_ptr<objc_object*>>, std::_Select1st<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>, std::less<bit_stack::storage>, std::allocator<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>> { + struct _Rb_tree_impl<std::less<bit_stack::storage>, false> _M_impl; +}; + +struct _Rb_tree<int, std::pair<const int, std::pair<int, int>>, std::_Select1st<std::pair<const int, std::pair<int, int>>>, std::less<int>, std::allocator<std::pair<const int, std::pair<int, int>>>> { + struct _Rb_tree_impl<std::less<int>, false> _M_impl; +}; + +struct _Rb_tree<size_t, std::pair<const size_t, size_t>, std::_Select1st<std::pair<const size_t, size_t>>, std::less<size_t>, std::allocator<std::pair<const size_t, size_t>>> { + struct _Rb_tree_impl<std::less<size_t>, false> _field1; +}; + +struct _Rb_tree<size_t, std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>, std::_Select1st<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>> { + struct _Rb_tree_impl<std::less<size_t>, false> _field1; +}; + +struct _Rb_tree<size_t, std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>, std::_Select1st<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>> { + struct _Rb_tree_impl<std::less<size_t>, false> _field1; +}; + +struct _Rb_tree<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>, std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>> { + struct _Rb_tree_impl<std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, false> _M_impl; +}; + +struct _Rb_tree<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>, std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>> { + struct _Rb_tree_impl<std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, false> _M_impl; +}; + +struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>, std::_Select1st<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>> { + struct _Rb_tree_impl<std::less<text::undo_key>, false> _field1; +}; + +struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>, std::_Select1st<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>> { + struct _Rb_tree_impl<std::less<text::undo_key>, false> _field1; +}; + +struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, text::selection>, std::_Select1st<std::pair<const text::undo_key, text::selection>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, text::selection>>> { + struct _Rb_tree_impl<std::less<text::undo_key>, false> _field1; +}; + +struct _Rb_tree<text::view::filter_index, std::pair<const text::view::filter_index, text::filter*>, std::_Select1st<std::pair<const text::view::filter_index, text::filter*>>, std::less<text::view::filter_index>, std::allocator<std::pair<const text::view::filter_index, text::filter*>>> { + struct _Rb_tree_impl<std::less<text::view::filter_index>, false> _field1; +}; + +struct _Rb_tree<text::view::folding_filter::folding_t, text::view::folding_filter::folding_t, std::_Identity<text::view::folding_filter::folding_t>, std::less<text::view::folding_filter::folding_t>, std::allocator<text::view::folding_filter::folding_t>> { + struct _Rb_tree_impl<std::less<text::view::folding_filter::folding_t>, false> _field1; +}; + +struct _Rb_tree<text::view::folding_filter::marker_t, text::view::folding_filter::marker_t, std::_Identity<text::view::folding_filter::marker_t>, std::less<text::view::folding_filter::marker_t>, std::allocator<text::view::folding_filter::marker_t>> { + struct _Rb_tree_impl<std::less<text::view::folding_filter::marker_t>, false> _field1; +}; + +struct _Rb_tree<unichar, unichar, std::_Identity<unichar>, std::less<unichar>, std::allocator<unichar>> { + struct _Rb_tree_impl<std::less<unichar>, false> _M_impl; +}; + +struct _Rb_tree_impl<std::less<bit_stack::storage>, false> { + struct less<bit_stack::storage> _M_key_compare; + struct _Rb_tree_node_base _M_header; + unsigned int _M_node_count; +}; + +struct _Rb_tree_impl<std::less<int>, false> { + struct less<int> _M_key_compare; + struct _Rb_tree_node_base _M_header; + unsigned int _M_node_count; +}; + +struct _Rb_tree_impl<std::less<size_t>, false> { + struct less<size_t> _field1; + struct _Rb_tree_node_base _field2; + unsigned int _field3; +}; + +struct _Rb_tree_impl<std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, false> { + struct less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>> _M_key_compare; + struct _Rb_tree_node_base _M_header; + unsigned int _M_node_count; +}; + +struct _Rb_tree_impl<std::less<text::undo_key>, false> { + struct less<text::undo_key> _field1; + struct _Rb_tree_node_base _field2; + unsigned int _field3; +}; + +struct _Rb_tree_impl<std::less<text::view::filter_index>, false> { + struct less<text::view::filter_index> _field1; + struct _Rb_tree_node_base _field2; + unsigned int _field3; +}; + +struct _Rb_tree_impl<std::less<text::view::folding_filter::folding_t>, false> { + struct less<text::view::folding_filter::folding_t> _field1; + struct _Rb_tree_node_base _field2; + unsigned int _field3; +}; + +struct _Rb_tree_impl<std::less<text::view::folding_filter::marker_t>, false> { + struct less<text::view::folding_filter::marker_t> _field1; + struct _Rb_tree_node_base _field2; + unsigned int _field3; +}; + +struct _Rb_tree_impl<std::less<unichar>, false> { + struct less<unichar> _M_key_compare; + struct _Rb_tree_node_base _M_header; + unsigned int _M_node_count; +}; + +struct _Rb_tree_node_base { + int _M_color; + struct _Rb_tree_node_base *_M_parent; + struct _Rb_tree_node_base *_M_left; + struct _Rb_tree_node_base *_M_right; +}; + +struct _Vector_impl { + struct shared_buffer<text::char_t> *_M_start; + struct shared_buffer<text::char_t> *_M_finish; + struct shared_buffer<text::char_t> *_M_end_of_storage; +}; + +struct __CFArray; + +struct _opaque_pthread_cond_t { + long _field1; + unsigned char _field2[24]; +}; + +struct _opaque_pthread_mutex_t { + long _field1; + unsigned char _field2[40]; +}; + +struct _opaque_pthread_t; + +struct action_map { + struct map<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>> _field1; +}; + +struct basic_string<char, std::char_traits<char>, std::allocator<char>> { + struct _Alloc_hider _field1; +}; + +struct basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>; + +struct bookmark_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct map<size_t, size_t, std::less<size_t>, std::allocator<std::pair<const size_t, size_t>>> _field4; +}; + +struct callback_record; + +struct completion_helper { + unsigned int _field1; + unsigned int _field2; + unsigned int _field3; + struct view_iterator _field4; + struct view_iterator _field5; + struct vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>>> _field6; +}; + +struct deque<callback_record, std::allocator<callback_record>> { + struct _Deque_impl _M_impl; +}; + +struct deque<text::undo_manager::node, std::allocator<text::undo_manager::node>> { + struct _Deque_impl _field1; +}; + +struct detail { + struct vector<shared_buffer<text::char_t>, std::allocator<shared_buffer<text::char_t>>> _field1; + struct list<text::storage::observer*, std::allocator<text::storage::observer*>> _field2; + struct _opaque_pthread_mutex_t _field3; +}; + +struct erase_t; + +struct filter; + +struct folding_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct ptrn_t *_field4; + struct ptrn_t *_field5; + struct set<text::view::folding_filter::marker_t, std::less<text::view::folding_filter::marker_t>, std::allocator<text::view::folding_filter::marker_t>> _field6; + struct set<text::view::folding_filter::folding_t, std::less<text::view::folding_filter::folding_t>, std::allocator<text::view::folding_filter::folding_t>> _field7; + _Bool _field8; + unsigned int _field9; +}; + +struct insert_t; + +struct iterator { + unsigned int _field1; + unsigned int _field2; + struct storage *_field3; +}; + +struct iterator_observer { + void **_field1; + struct list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>> _field2; + struct list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>> _field3; + struct list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>> _field4; + struct list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>> _field5; + struct map<text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>> _field6; + struct map<text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>> _field7; + struct vector<text::iterator_observer::pending_erase, std::allocator<text::iterator_observer::pending_erase>> _field8; + struct vector<text::iterator_observer::pending_insert, std::allocator<text::iterator_observer::pending_insert>> _field9; + struct vector<unichar, std::allocator<unichar>> _field10; + unsigned int _field11; + _Bool _field12; + _Bool _field13; + _Bool _field14; +}; + +struct kill_buffer_t { + struct vector<unichar, std::allocator<unichar>> _field1; + unsigned int _field2; + struct iterator _field3; + _Bool _field4; +}; + +struct less<bit_stack::storage>; + +struct less<int>; + +struct less<size_t>; + +struct less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>; + +struct less<text::undo_key>; + +struct less<text::view::filter_index>; + +struct less<text::view::folding_filter::folding_t>; + +struct less<text::view::folding_filter::marker_t>; + +struct less<unichar>; + +struct line_range; + +struct list<ATSUI_render::new_node, std::allocator<ATSUI_render::new_node>> { + struct _List_impl _M_impl; +}; + +struct list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>> { + struct _List_impl _field1; +}; + +struct list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>> { + struct _List_impl _field1; +}; + +struct list<text::storage::observer*, std::allocator<text::storage::observer*>> { + struct _List_impl _field1; +}; + +struct map<bit_stack::storage, objc_ptr<objc_object*>, std::less<bit_stack::storage>, std::allocator<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>> { + struct _Rb_tree<bit_stack::storage, std::pair<const bit_stack::storage, objc_ptr<objc_object*>>, std::_Select1st<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>, std::less<bit_stack::storage>, std::allocator<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>> _field1; +}; + +struct map<int, std::pair<int, int>, std::less<int>, std::allocator<std::pair<const int, std::pair<int, int>>>> { + struct _Rb_tree<int, std::pair<const int, std::pair<int, int>>, std::_Select1st<std::pair<const int, std::pair<int, int>>>, std::less<int>, std::allocator<std::pair<const int, std::pair<int, int>>>> _field1; +}; + +struct map<size_t, size_t, std::less<size_t>, std::allocator<std::pair<const size_t, size_t>>> { + struct _Rb_tree<size_t, std::pair<const size_t, size_t>, std::_Select1st<std::pair<const size_t, size_t>>, std::less<size_t>, std::allocator<std::pair<const size_t, size_t>>> _field1; +}; + +struct map<size_t, std::_List_iterator<text::iterator_observer::subset>, std::less<size_t>, std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>> { + struct _Rb_tree<size_t, std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>, std::_Select1st<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>> _field1; +}; + +struct map<size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>> { + struct _Rb_tree<size_t, std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>, std::_Select1st<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>> _field1; +}; + +struct map<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>> { + struct _Rb_tree<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>, std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, action_map::action*>>> _M_t; +}; + +struct map<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>> { + struct _Rb_tree<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>, std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>> _M_t; +}; + +struct map<text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>> { + struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>, std::_Select1st<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>>>>>> _field1; +}; + +struct map<text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>> { + struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>, std::_Select1st<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset>>>>> _field1; +}; + +struct map<text::undo_key, text::selection, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, text::selection>>> { + struct _Rb_tree<text::undo_key, std::pair<const text::undo_key, text::selection>, std::_Select1st<std::pair<const text::undo_key, text::selection>>, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, text::selection>>> _field1; +}; + +struct map<text::view::filter_index, text::filter*, std::less<text::view::filter_index>, std::allocator<std::pair<const text::view::filter_index, text::filter*>>> { + struct _Rb_tree<text::view::filter_index, std::pair<const text::view::filter_index, text::filter*>, std::_Select1st<std::pair<const text::view::filter_index, text::filter*>>, std::less<text::view::filter_index>, std::allocator<std::pair<const text::view::filter_index, text::filter*>>> _field1; +}; + +struct map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage>>>; + +struct node; + +struct node_t; + +struct observer { + void **_field1; +}; + +struct pending_erase; + +struct pending_insert; + +struct pos { + unsigned int _field1; + unsigned int _field2; +}; + +struct ptrn_t; + +struct selection { + struct view_iterator _field1; + struct view_iterator _field2; + struct view_iterator _field3; + _Bool _field4; + struct vector<unichar, std::allocator<unichar>> _field5; +}; + +struct set<text::view::folding_filter::folding_t, std::less<text::view::folding_filter::folding_t>, std::allocator<text::view::folding_filter::folding_t>> { + struct _Rb_tree<text::view::folding_filter::folding_t, text::view::folding_filter::folding_t, std::_Identity<text::view::folding_filter::folding_t>, std::less<text::view::folding_filter::folding_t>, std::allocator<text::view::folding_filter::folding_t>> _field1; +}; + +struct set<text::view::folding_filter::marker_t, std::less<text::view::folding_filter::marker_t>, std::allocator<text::view::folding_filter::marker_t>> { + struct _Rb_tree<text::view::folding_filter::marker_t, text::view::folding_filter::marker_t, std::_Identity<text::view::folding_filter::marker_t>, std::less<text::view::folding_filter::marker_t>, std::allocator<text::view::folding_filter::marker_t>> _field1; +}; + +struct set<unichar, std::less<unichar>, std::allocator<unichar>> { + struct _Rb_tree<unichar, unichar, std::_Identity<unichar>, std::less<unichar>, std::allocator<unichar>> _field1; +}; + +struct shared_buffer<text::char_t>; + +struct snippet_observer_t { + void **_field1; + struct iterator _field2; + struct snippet_t *_field3; + struct vector<text::snippet_observer_t::insert_t, std::allocator<text::snippet_observer_t::insert_t>> _field4; + struct vector<text::snippet_observer_t::erase_t, std::allocator<text::snippet_observer_t::erase_t>> _field5; +}; + +struct snippet_t; + +struct soft_wrap_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct pos _field4; + struct pos _field5; + struct vector<text::view::soft_wrap_filter::line_range, std::allocator<text::view::soft_wrap_filter::line_range>> _field6; +}; + +struct spellcheck_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct vector<text::view::spellcheck_filter::node_t, std::allocator<text::view::spellcheck_filter::node_t>> _field4; +}; + +struct stack<callback_record, std::deque<callback_record, std::allocator<callback_record>>> { + struct deque<callback_record, std::allocator<callback_record>> _field1; +}; + +struct stack<text::undo_manager::node, std::deque<text::undo_manager::node, std::allocator<text::undo_manager::node>>> { + struct deque<text::undo_manager::node, std::allocator<text::undo_manager::node>> _field1; +}; + +struct storage { + struct detail _field1; + struct kill_buffer_t _field2; + struct vector<text::storage::undo_record, std::allocator<text::storage::undo_record>> _field3; + unsigned int _field4; + unsigned int _field5; + unsigned int _field6; + unsigned int _field7; + struct undo_manager _field8; +}; + +struct storage_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct _List_iterator<text::storage::observer*> _field4; +}; + +struct title_action_map { + struct map<std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char>>>, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>>, title_action_map::action*>>> _field1; +}; + +struct tokenize_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct __CFArray *_field4; + unsigned int _field5; + struct vector<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage>>>, std::allocator<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage>>>>> _field6; + struct map<size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>, std::less<size_t>, std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper>>>>>> _field7; + struct _opaque_pthread_t *_field8; + struct _opaque_pthread_cond_t _field9; + struct _opaque_pthread_cond_t _field10; + unsigned int _field11; + unsigned int _field12; + unsigned int _field13; + unsigned int _field14; + unsigned int _field15; + _Bool _field16; + int _field17; + int _field18; + void *_field19; +}; + +struct undo_manager { + struct stack<text::undo_manager::node, std::deque<text::undo_manager::node, std::allocator<text::undo_manager::node>>> _field1; +}; + +struct undo_record; + +struct vector<ATSUTab, std::allocator<ATSUTab>> { + struct _Vector_impl _M_impl; +}; + +struct vector<NSTrackingRectTag, std::allocator<NSTrackingRectTag>> { + struct _Vector_impl _field1; +}; + +struct vector<shared_buffer<text::char_t>, std::allocator<shared_buffer<text::char_t>>> { + struct _Vector_impl _field1; +}; + +struct vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>, std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>>>> { + struct _Vector_impl _field1; +}; + +struct vector<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage>>>, std::allocator<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage>>>>> { + struct _Vector_impl _field1; +}; + +struct vector<std::vector<text::char_t, std::allocator<text::char_t>>, std::allocator<std::vector<text::char_t, std::allocator<text::char_t>>>> { + struct _Vector_impl _field1; +}; + +struct vector<text::char_t, std::allocator<text::char_t>>; + +struct vector<text::iterator_observer::pending_erase, std::allocator<text::iterator_observer::pending_erase>> { + struct _Vector_impl _field1; +}; + +struct vector<text::iterator_observer::pending_insert, std::allocator<text::iterator_observer::pending_insert>> { + struct _Vector_impl _field1; +}; + +struct vector<text::snippet_observer_t::erase_t, std::allocator<text::snippet_observer_t::erase_t>> { + struct _Vector_impl _field1; +}; + +struct vector<text::snippet_observer_t::insert_t, std::allocator<text::snippet_observer_t::insert_t>> { + struct _Vector_impl _field1; +}; + +struct vector<text::storage::undo_record, std::allocator<text::storage::undo_record>> { + struct _Vector_impl _field1; +}; + +struct vector<text::view*, std::allocator<text::view*>> { + struct _Vector_impl _field1; +}; + +struct vector<text::view::soft_wrap_filter::line_range, std::allocator<text::view::soft_wrap_filter::line_range>> { + struct _Vector_impl _field1; +}; + +struct vector<text::view::spellcheck_filter::node_t, std::allocator<text::view::spellcheck_filter::node_t>> { + struct _Vector_impl _field1; +}; + +struct vector<unichar, std::allocator<unichar>> { + struct _Vector_impl _field1; +}; + +struct view { + struct iterator_observer _field1; + struct iterator_observer _field2; + struct snippet_observer_t _field3; + struct selection _field4; + struct selection _field5; + unsigned int _field6; + unsigned int _field7; + unsigned int _field8; + unsigned int _field9; + unsigned int _field10; + unsigned int _field11; + unsigned int _field12; + _Bool _field13; + _Bool _field14; + _Bool _field15; + _Bool _field16; + _Bool _field17; + _Bool _field18; + _Bool _field19; + struct map<size_t, std::_List_iterator<text::iterator_observer::subset>, std::less<size_t>, std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset>>>> _field20; + int _field21; + _Bool _field22; + _Bool _field23; + struct storage_filter _field24; + struct tokenize_filter _field25; + struct bookmark_filter _field26; + struct spellcheck_filter _field27; + struct folding_filter _field28; + struct soft_wrap_filter _field29; + struct view_filter _field30; + struct map<text::view::filter_index, text::filter*, std::less<text::view::filter_index>, std::allocator<std::pair<const text::view::filter_index, text::filter*>>> _field31; + struct completion_helper _field32; +}; + +struct view_filter { + void **_field1; + struct filter *_field2; + struct filter *_field3; + struct map<text::undo_key, text::selection, std::less<text::undo_key>, std::allocator<std::pair<const text::undo_key, text::selection>>> _field4; +}; + +struct view_iterator { + struct view *_field1; + struct iterator _field2; + unsigned int _field3; + unsigned int _field4; +}; + +/* + * File: /Applications/TextMate.app/Contents/MacOS/TextMate + * Arch: Intel 80x86 (i386) + */ + +@protocol NSTextInput +- (void)insertText:(id)fp8; +- (void)doCommandBySelector:(SEL)fp8; +- (void)setMarkedText:(id)fp8 selectedRange:(struct _NSRange)fp12; +- (void)unmarkText; +- (BOOL)hasMarkedText; +- (long)conversationIdentifier; +- (id)attributedSubstringFromRange:(struct _NSRange)fp8; +- (struct _NSRange)markedRange; +- (struct _NSRange)selectedRange; +- (struct _NSRect)firstRectForCharacterRange:(struct _NSRange)fp8; +- (unsigned int)characterIndexForPoint:(struct _NSPoint)fp8; +- (id)validAttributesForMarkedText; +@end + +@protocol OakKeyObserver +- (BOOL)shouldSwallowEvent:(id)fp8; +@end + +@protocol QSStringRanker +- (id)initWithString:(id)fp8; +- (double)scoreForAbbreviation:(id)fp8; +- (id)maskForAbbreviation:(id)fp8; +@end + +@protocol TextMateServerProtocol +- (int)textMateServerProtocolVersion; +- (BOOL)openFiles:(id)fp8 options:(id)fp12 delegate:(id)fp16 didCloseSelector:(SEL)fp20; +@end + +@interface AppDelegate : NSObject +{ + OakEncodingView *savePanelAccessoryView; + NSPanel *fillWithStringPanel; + NSPanel *goToLinePanel; + NSTextField *goToLineTextField; + NSView *openPanelAccessoryView; + NSArray *allWindowDelegates; + BOOL shouldOpenSavedDocuments; + unsigned int numberOfUntitledDocuments; + unsigned int nextUntitledDocumentCount; + unsigned int numberOfUntitledProjects; + unsigned int nextUntitledProjectCount; + NSString *currentDirectory; +} + ++ (void)initialize; +- (void)applicationWillFinishLaunching:(id)fp8; +- (void)applicationDidFinishLaunching:(id)fp8; +- (void)showExtendedTerminalUsageHelp:(id)fp8; +- (void)readPrefs:(id)fp8; +- (int)orderFrontRegistrationPanel:(id)fp8; +- (void)orderFrontPreferences:(id)fp8; +- (void)orderFrontPasteboardPanel:(id)fp8; +- (void)newProject:(id)fp8; +- (void)newDocument:(id)fp8; +- (void)workaroundHideBug:(id)fp8; +- (id)collectAuxiliaryInfo; +- (id)bundlePaths; +- (void)openFiles:(id)fp8; +- (void)openDocument:(id)fp8; +- (BOOL)panel:(id)fp8 shouldShowFilename:(id)fp12; +- (BOOL)applicationOpenUntitledFile:(id)fp8; +- (BOOL)applicationShouldHandleReopen:(id)fp8 hasVisibleWindows:(BOOL)fp12; +- (BOOL)applicationShouldOpenUntitledFile:(id)fp8; +- (void)application:(id)fp8 openFiles:(id)fp12; +- (BOOL)application:(id)fp8 openFile:(id)fp12; +- (void)sendFeedback:(id)fp8; +- (void)orderFrontFindPanel:(id)fp8; +- (void)orderFrontFindInProjectPanel:(id)fp8; +- (void)executeCommand:(id)fp8; +- (void)rememberDocumentFiles:(id)fp8; +- (void)didCloseWindow:(id)fp8 callStack:(id)fp12; +- (int)applicationShouldTerminate:(id)fp8; +- (BOOL)application:(id)fp8 delegateHandlesKey:(id)fp12; +- (id)orderedDocuments; +- (unsigned long)registerUntitledDocument; +- (void)unregisterUntitledDocument:(unsigned long)fp8; +- (unsigned long)registerUntitledProject; +- (void)unregisterUntitledProject:(unsigned long)fp8; +- (void)orderFrontGoToLinePanel:(id)fp8; +- (void)goToLineAction:(id)fp8; +- (void)orderFrontReleaseNotes:(id)fp8; +- (void)goToSupportPage:(id)fp8; +- (void)selectFileAtTabIndex:(id)fp8; +- (void)menuNeedsUpdate:(id)fp8; +- (id)supportPath; +- (id)environmentVariables; + +@end + +@interface OakApplication : NSApplication +{ + NSMutableArray *keyObservers; +} + +- (id)init; +- (void)addKeyObserver:(id)fp8; +- (void)removeKeyObserver:(id)fp8; +- (void)sendEvent:(id)fp8; + +@end + +@interface OakEncodingView : NSView +{ + NSPopUpButton *encodingPopupButton; + NSPopUpButton *lineEndingPopupButton; +} + +- (int)fileEncodingChoice; +- (void)setFileEncodingChoice:(int)fp8; +- (int)lineEndingChoice; +- (void)setLineEndingChoice:(int)fp8; + +@end + +@interface OakHackedDocumentController : NSDocumentController +{ +} + +- (unsigned int)maximumRecentDocumentCount; + +@end + +@interface TextMateServer : NSObject <TextMateServerProtocol> +{ +} + +- (int)textMateServerProtocolVersion; +- (BOOL)openFiles:(id)fp8 options:(id)fp12 delegate:(id)fp16 didCloseSelector:(SEL)fp20; + +@end + +@interface OakDocumentDidCloseObserver : NSObject +{ + id delegate; + SEL selector; + id fileObject; +} + +- (void)documentDidClose:(id)fp8; +- (void)setSelector:(SEL)fp8; +- (void)dealloc; + +@end + +@interface OakArrayToStringTransformer : NSValueTransformer +{ +} + ++ (Class)transformedValueClass; ++ (BOOL)allowsReverseTransformation; ++ (void)load; +- (id)transformedValue:(id)fp8; +- (id)reverseTransformedValue:(id)fp8; + +@end + +@interface OakStringListTransformer : NSValueTransformer +{ + NSArray *stringList; +} + ++ (Class)transformedValueClass; ++ (BOOL)allowsReverseTransformation; ++ (void)setStringListTransformer:(id)fp8 forName:(id)fp12; ++ (void)createTransformerWithName:(id)fp8 andObjects:(id)fp12; +- (void)dealloc; +- (id)transformedValue:(id)fp8; +- (id)reverseTransformedValue:(id)fp8; + +@end + +@interface OakVerifyFileTransformer : NSValueTransformer +{ +} + ++ (Class)transformedValueClass; +- (id)transformedValue:(id)fp8; + +@end + +@interface OakPreOrderArrayEnumerator : NSEnumerator +{ + NSMutableArray *stack; +} + +- (id)initWithArray:(id)fp8; +- (void)dealloc; +- (id)nextObject; + +@end + +@interface NSTextView (OakFindNextPrevious) +- (void)copySelectionToFindPboard:(id)fp8; +- (void)findNext:(id)fp8; +- (void)findPrevious:(id)fp8; +- (id)findWithOptions:(id)fp8; +@end + +@interface NSDictionary (PrettyPrint) +- (BOOL)plistFitsSingleLine; +- (id)stringWithIndent:(unsigned int)fp8 isKey:(BOOL)fp12 isSingleLine:(BOOL)fp16; +@end + +@interface NSArray (PrettyPrint) +- (BOOL)plistFitsSingleLine; +- (id)stringWithIndent:(unsigned int)fp8 isKey:(BOOL)fp12 isSingleLine:(BOOL)fp16; +@end + +@interface NSString (PrettyPrint) +- (id)stringWithIndent:(unsigned int)fp8 isKey:(BOOL)fp12 isSingleLine:(BOOL)fp16; +@end + +@interface NSObject (PrettyPrint) +- (BOOL)plistFitsSingleLine; +- (id)stringWithIndent:(unsigned int)fp8 isKey:(BOOL)fp12 isSingleLine:(BOOL)fp16; +@end + +@interface NSString (OakString) ++ (id)stringWithData:(id)fp8; +- (id)labelForCopyWithExistingLabels:(id)fp8; +@end + +@interface NSString (OakRegEx) +- (BOOL)isEqualToRegEx:(id)fp8; +- (id)componentsInRegEx:(id)fp8; +@end + +@interface NSAlert (OakAlert) +- (void)addButtons:(id)fp8; +@end + +@interface NSWindow (OakView) +- (void)toggleVisibility; +@end + +@interface NSView (OakView) +- (id)imageForRect:(struct _NSRect)fp8 withClip:(id)fp24; +@end + +@interface NSPasteboard (OakPasteboard) +- (id)stringRepresentation; +@end + +@interface NSMutableArray (OakMutableArray) +- (void)insertObjectsFromArray:(id)fp8 atIndex:(int)fp12; +- (void)removeObjectsWithKey:(id)fp8; +- (id)arrayContainingItem:(id)fp8; +- (id)ancestorsForItem:(id)fp8; +@end + +@interface NSArray (OakArray) +- (id)preOrderObjectEnumerator; +- (id)firstObject; +- (void)tagItemsWithString:(id)fp8; +- (void)untagItemsWithString:(id)fp8; +@end + +@interface NSString (OakPath) ++ (id)stringWithUTF8String:(const char *)fp8 length:(unsigned int)fp12; +- (id)pathExtensions; +- (id)stringByDeletingPathExtensions; +- (id)associatedApplication; +- (id)stringByRemovingAbsolutePath:(id)fp8; +- (id)modificationDate; +- (BOOL)existsAsPath; +- (BOOL)isDirectory; +- (BOOL)canCreateAsDirectory; +- (BOOL)moveFileToTrash; +- (BOOL)moveFileTo:(id)fp8; +@end + +@interface NSString (UUID) ++ (id)stringWithUUID; +@end + +@interface NSOutlineView (OakOutlineView) +- (id)selectedItem; +- (id)selectedItems; +- (void)selectItem:(id)fp8; +- (void)selectItems:(id)fp8; +- (id)expandedItems; +- (void)expandItems:(id)fp8; +@end + +@interface NSBezierPath (OakBezierPath) ++ (id)bezierPathWithRoundRectInRect:(struct _NSRect)fp8 radius:(float)fp24; +@end + +@interface NSSavePanel (DeselectExtension) +- (void)deselectExtension; +@end + +@interface NSObject (DeepCopy) +- (id)deepCopy; +@end + +@interface NSWindow (RevealInFinder) +- (void)revealFileInFinder:(id)fp8; +@end + +@interface NSScreen (RestrainFrames) ++ (id)screenWithFrame:(struct _NSRect)fp8; +- (struct _NSRect)restrainFrameToVisibleScreen:(struct _NSRect)fp8; +@end + +@interface NSDictionary (MutableDeepCopy) +- (id)mutableDeepCopy; +@end + +@interface NSArray (MutableDeepCopy) +- (id)mutableDeepCopy; +@end + +@interface NSObject (MutableDeepCopy) +- (id)mutableDeepCopy; +@end + +@interface DuffStringRanker : NSObject <QSStringRanker> +{ + unsigned short *string; + unsigned int *originalIndex; + unsigned int length; +} + +- (id)initWithString:(id)fp8; +- (void)dealloc; +- (double)scoreForAbbreviation:(id)fp8; +- (id)maskForAbbreviation:(id)fp8; + +@end + +@interface OakBundleEditor : NSObject +{ + NSPanel *bundleEditorPanel; + NSSplitView *mainSplitView; + OakBundleOutlineView *outlineView; + NSTextField *boxTitle; + NSBox *editorBox; + OakKeyEquivalent *keyEquivalentField; + NSMenu *bundleFilterMenu; + NSPanel *bundleListEditorSheet; + NSTableView *bundleListEditorTableView; + NSView *snippetEditor; + NSView *commandEditor; + NSView *dragCommandEditor; + NSView *macroEditor; + NSView *languageEditor; + NSTextView *languageTextView; + NSView *preferenceEditor; + NSTextView *preferenceTextView; + NSView *templateEditor; + NSView *templateFileEditor; + NSTextView *templateFileTextView; + OakBundleSplitView *splitView; + NSView *noSelection; + NSImageView *imageView; + NSOutlineView *menuStructureOutlineview; + NSTableView *excludedMenuItemsTableView; + NSView *bundlePropertiesEditor; + OakBundlePropertiesEditor *bundlePropertiesEditorDelegate; + NSArray *cachedBundles; + NSMutableDictionary *cachedBundleItems; + NSUndoManager *undoManager; + NSString *bundleFilter; + id selection; + BOOL canAddBundleItem; + BOOL canDuplicateBundleItem; + BOOL canRemoveBundleItem; + BOOL updateLanguages; + BOOL updatePreferences; + NSDate *animationStart; + NSTimer *animationTimer; + BOOL pendingShowOutputPatternOptions; + BOOL showOutputPatternOptions; + NSMutableArray *editors; + NSMutableArray *allBundles; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (id)windowWillReturnUndoManager:(id)fp8; +- (id)init; +- (void)dealloc; +- (BOOL)validateMenuItem:(id)fp8; +- (void)undo:(id)fp8; +- (void)redo:(id)fp8; +- (void)setFilterLabels; +- (BOOL)loadNib; +- (void)bundlesDidChange:(id)fp8; +- (void)orderFrontBundleEditor:(id)fp8; +- (void)showItem:(id)fp8; +- (id)windowWillReturnFieldEditor:(id)fp8 toObject:(id)fp12; +- (void)outlineView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 item:(id)fp20; +- (int)outlineView:(id)fp8 numberOfChildrenOfItem:(id)fp12; +- (id)outlineView:(id)fp8 child:(int)fp12 ofItem:(id)fp16; +- (BOOL)outlineView:(id)fp8 isItemExpandable:(id)fp12; +- (id)outlineView:(id)fp8 objectValueForTableColumn:(id)fp12 byItem:(id)fp16; +- (void)reloadOutlineView:(id)fp8; +- (void)outlineView:(id)fp8 setObjectValue:(id)fp12 forTableColumn:(id)fp16 byItem:(id)fp20; +- (BOOL)outlineView:(id)fp8 writeItems:(id)fp12 toPasteboard:(id)fp16; +- (id)outlineView:(id)fp8 namesOfPromisedFilesDroppedAtDestination:(id)fp12 forDraggedItems:(id)fp16; +- (unsigned int)outlineView:(id)fp8 validateDrop:(id)fp12 proposedItem:(id)fp16 proposedChildIndex:(int)fp20; +- (BOOL)outlineView:(id)fp8 acceptDrop:(id)fp12 item:(id)fp16 childIndex:(int)fp20; +- (BOOL)commitEditing; +- (void)outlineViewSelectionDidChange:(id)fp8; +- (void)reloadOutlineView; +- (void)setBundleFilter:(id)fp8; +- (void)animationTick:(id)fp8; +- (BOOL)showPatternOptions; +- (void)setShowPatternOptions:(BOOL)fp8; +- (float)splitView:(id)fp8 constrainMinCoordinate:(float)fp12 ofSubviewAt:(int)fp16; +- (float)splitView:(id)fp8 constrainMaxCoordinate:(float)fp12 ofSubviewAt:(int)fp16; +- (void)splitView:(id)fp8 resizeSubviewsWithOldSize:(struct _NSSize)fp12; +- (void)editBundleList:(id)fp8; +- (void)orderOutBundleList:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; +- (void)tableView:(id)fp8 setObjectValue:(id)fp12 forTableColumn:(id)fp16 row:(int)fp20; +- (void)testTemplate:(id)fp8; +- (void)newItem:(id)fp8; +- (void)newCommand:(id)fp8; +- (void)newDragCommand:(id)fp8; +- (void)newLanguage:(id)fp8; +- (void)newSnippet:(id)fp8; +- (void)newTemplate:(id)fp8; +- (void)newTemplateFile:(id)fp8; +- (void)newPreference:(id)fp8; +- (void)newBundle:(id)fp8; +- (void)duplicateItem:(id)fp8; +- (void)removeItem:(id)fp8; +- (void)objectDidBeginEditing:(id)fp8; +- (void)objectDidEndEditing:(id)fp8; +- (BOOL)windowShouldClose:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (void)testLanguage:(id)fp8; +- (void)selectCurrentMode; +- (void)orderFrontAndShow:(id)fp8; +- (void)showHelpForCommands:(id)fp8; +- (void)showHelpForDragCommands:(id)fp8; +- (void)showHelpForLanguageGrammars:(id)fp8; +- (void)showHelpForPreferences:(id)fp8; +- (void)showHelpForSnippets:(id)fp8; +- (void)showHelpForTemplates:(id)fp8; +- (void)showHelpForMoreBundles:(id)fp8; + +@end + +@interface OakBundleEditorWindow : NSWindow +{ + NSUndoManager *textViewUndoManager; +} + +- (id)currentUndoManager; +- (BOOL)validateMenuItem:(id)fp8; +- (void)undo:(id)fp8; +- (void)redo:(id)fp8; +- (BOOL)canBecomeMainWindow; +- (void)keyDown:(id)fp8; + +@end + +@interface OakBundleSplitView : NSSplitView +{ +} + +- (float)dividerThickness; +- (void)drawDividerInRect:(struct _NSRect)fp8; + +@end + +@interface OakBundleOutlineView : NSOutlineView +{ +} + +- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)fp8; + +@end + +@interface OakTemplateFileBundleItem : NSObject +{ + TemplateFile *templateFile; +} + ++ (id)templateFileBundleItemWithTemplate:(id)fp8; ++ (void)initialize; +- (BOOL)canSetFallbackInput; +- (BOOL)canSetScopeSelector; +- (BOOL)canSetActivation; +- (BOOL)canSetCapturePatterns; +- (id)initTemplateBundleItemWithTemplate:(id)fp8; +- (id)valueForKey:(id)fp8; +- (void)setValue:(id)fp8 forKey:(id)fp12; +- (id)kind; +- (id)name; +- (id)templateFileContents; +- (void)setName:(id)fp8; +- (void)setTemplateFileContents:(id)fp8; +- (id)keyEquivalent; +- (id)editItemTitle; + +@end + +@interface OakUnifiedBundleItem : NSObject +{ + BundleItem *bundleItem; + NSString *activationMethod; + NSString *inputPattern; + NSString *templateFileContents; + NSString *preferences; + NSString *languageGrammar; +} + ++ (id)unifiedBundleItemWithBundleItem:(id)fp8; ++ (void)initialize; +- (BOOL)canSetFallbackInput; +- (BOOL)canSetScopeSelector; +- (BOOL)canSetActivation; +- (BOOL)canSetCapturePatterns; +- (id)initWithBundleItem:(id)fp8; +- (id)valueForKey:(id)fp8; +- (void)setValue:(id)fp8 forKey:(id)fp12; +- (id)name; +- (void)setName:(id)fp8; +- (id)scopeSelector; +- (void)setScopeSelector:(id)fp8; +- (id)tabTrigger; +- (void)setTabTrigger:(id)fp8; +- (id)keyEquivalent; +- (void)setKeyEquivalent:(id)fp8; +- (id)draggedFileExtensions; +- (void)setDraggedFileExtensions:(id)fp8; +- (id)editItemTitle; +- (void)setLanguageGrammar:(id)fp8; +- (void)setPreferences:(id)fp8; +- (BOOL)validateSnippet:(id *)fp8 error:(id *)fp12; +- (BOOL)validateLanguageGrammar:(id *)fp8 error:(id *)fp12; +- (BOOL)validatePreferences:(id *)fp8 error:(id *)fp12; + +@end + +@interface OakBundlePropertiesEditor : NSObject +{ + Bundle *bundle; + NSMutableDictionary *groups; + NSMutableSet *separators; + NSMutableArray *excluded; +} + +- (id)init; +- (void)commit; +- (void)setBundle:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (void)tableView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 row:(int)fp20; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; +- (int)outlineView:(id)fp8 numberOfChildrenOfItem:(id)fp12; +- (id)outlineView:(id)fp8 child:(int)fp12 ofItem:(id)fp16; +- (BOOL)outlineView:(id)fp8 isItemExpandable:(id)fp12; +- (void)outlineView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 item:(id)fp20; +- (id)outlineView:(id)fp8 objectValueForTableColumn:(id)fp12 byItem:(id)fp16; +- (void)outlineView:(id)fp8 setObjectValue:(id)fp12 forTableColumn:(id)fp16 byItem:(id)fp20; +- (BOOL)outlineView:(id)fp8 shouldEditTableColumn:(id)fp12 item:(id)fp16; +- (BOOL)tableView:(id)fp8 writeRows:(id)fp12 toPasteboard:(id)fp16; +- (unsigned int)tableView:(id)fp8 validateDrop:(id)fp12 proposedRow:(int)fp16 proposedDropOperation:(int)fp20; +- (BOOL)tableView:(id)fp8 acceptDrop:(id)fp12 row:(int)fp16 dropOperation:(int)fp20; +- (BOOL)outlineView:(id)fp8 writeItems:(id)fp12 toPasteboard:(id)fp16; +- (unsigned int)outlineView:(id)fp8 validateDrop:(id)fp12 proposedItem:(id)fp16 proposedChildIndex:(int)fp20; +- (BOOL)outlineView:(id)fp8 acceptDrop:(id)fp12 item:(id)fp16 childIndex:(int)fp20; + +@end + +@interface OakButton : NSButton +{ + NSImage *normalImage; + NSImage *disabledImage; +} + +- (id)initWithCoder:(id)fp8; +- (void)setEnabled:(BOOL)fp8; +- (void)dealloc; + +@end + +@interface OakCallbackStack : NSObject +{ + struct stack<callback_record, std::deque<callback_record, std::allocator<callback_record>>> *stack; +} + ++ (id)callbackStack; +- (id)init; +- (void)dealloc; +- (void)pushSelector:(SEL)fp8 andObject:(id)fp12; +- (void)returnWithSucces:(BOOL)fp8; + +@end + +@interface OakHTMLOutputManager : NSObject +{ + NSWindow *window; + WebView *webView; + NSProgressIndicator *progressIndicator; + NSString *commandUUID; + NSString *scriptFile; + id observedWebView; + NSDictionary *environment; + struct _NSRect webViewFrame; + struct _NSRect pendingVisibleRect; + BOOL userDidScrollOutput; + BOOL didMoveProgressIndicator; + BOOL shouldScrollToBottom; + BOOL shouldScrollToPendingRect; + BOOL scrollsOnOutput; + BOOL isLoadingPage; + BOOL isBusy; + int taskPID; + int writerPID; +} + ++ (void)registerIdleWindow:(id)fp8 forUUID:(id)fp12; ++ (void)unregisterIdleWindowForUUID:(id)fp8; ++ (id)idleWindowForUUID:(id)fp8; ++ (void)releaseWebViewAfterDelay:(id)fp8; +- (id)environment; +- (void)setEnvironment:(id)fp8; +- (void)printDocument:(id)fp8; +- (void)updateProgressIndicator; +- (void)setBusy:(BOOL)fp8; +- (void)setLoadingPage:(BOOL)fp8; +- (BOOL)cleanup; +- (void)webView:(id)fp8 addMessageToConsole:(id)fp12; +- (id)webView:(id)fp8 identifierForInitialRequest:(id)fp12 fromDataSource:(id)fp16; +- (id)webView:(id)fp8 resource:(id)fp12 willSendRequest:(id)fp16 redirectResponse:(id)fp20 fromDataSource:(id)fp24; +- (void)removeFrameObserver; +- (void)addFrameObserverToView:(id)fp8; +- (void)webView:(id)fp8 didStartProvisionalLoadForFrame:(id)fp12; +- (void)webView:(id)fp8 didCommitLoadForFrame:(id)fp12; +- (void)webView:(id)fp8 willCloseFrame:(id)fp12; +- (void)webView:(id)fp8 didReceiveTitle:(id)fp12 forFrame:(id)fp16; +- (void)webView:(id)fp8 didFinishLoadForFrame:(id)fp12; +- (void)webViewDidChangeFrame:(id)fp8; +- (id)textView; +- (void)dealloc; +- (void)webView:(id)fp8 windowScriptObjectAvailable:(id)fp12; +- (void)runCommand:(id)fp8 withInput:(id)fp12; +- (void)showOutput:(id)fp8 forCommand:(id)fp12 withEnvironment:(id)fp16; +- (BOOL)windowShouldClose:(id)fp8; +- (void)closeWarningDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; +- (void)terminateProcess:(int)fp8; +- (void)windowWillClose:(id)fp8; + +@end + +@interface OakTextMateJSBridge : NSObject +{ + id delegate; + NSDictionary *environment; + BOOL isBusy; +} + ++ (BOOL)isSelectorExcludedFromWebScript:(SEL)fp8; ++ (id)webScriptNameForSelector:(SEL)fp8; ++ (BOOL)isKeyExcludedFromWebScript:(const char *)fp8; ++ (id)webScriptNameForKey:(const char *)fp8; +- (id)environment; +- (void)setEnvironment:(id)fp8; +- (void)dealloc; +- (void)setIsBusy:(BOOL)fp8; +- (void)setDelegate:(id)fp8; +- (void)log:(id)fp8; +- (id)system:(id)fp8 handler:(id)fp12; + +@end + +@interface OakJSShellCommand : NSObject +{ + NSDictionary *environment; + id onreadoutput; + id onreaderror; + NSMutableData *outputData; + NSMutableData *errorData; + int status; + BOOL didTerminate; + NSString *outputString; + NSString *errorString; + NSTask *task; + NSPipe *stdInput; + NSPipe *stdOutput; + NSPipe *stdError; + id endHandler; +} + ++ (BOOL)isKeyExcludedFromWebScript:(const char *)fp8; ++ (id)webScriptNameForKey:(const char *)fp8; ++ (BOOL)isSelectorExcludedFromWebScript:(SEL)fp8; ++ (id)webScriptNameForSelector:(SEL)fp8; +- (id)environment; +- (void)setEnvironment:(id)fp8; +- (void)checkForData; +- (id)outputString; +- (id)errorString; +- (void)write:(id)fp8; +- (void)close; +- (void)cancel; +- (void)terminateTask:(id)fp8; +- (void)dataAvailable:(id)fp8; +- (void)setOnreadoutput:(id)fp8; +- (void)setOnreaderror:(id)fp8; +- (void)taskDidTerminate:(id)fp8; +- (void)finalizeForWebScript; +- (id)runTaskWithCommand:(id)fp8; +- (void)dealloc; + +@end + +@interface OakTextView (ExecuteCommand) ++ (id)defaultEnvironmentVariables; +- (id)wordAtCaret; +- (id)xmlRepresentationForSelection:(BOOL)fp8; +- (id)xmlRepresentation; +- (id)xmlRepresentationForSelection; +- (struct _NSPoint)positionForWindowUnderCaret; +- (id)environmentVariables; +- (void)extendSelectionInScope:(id)fp8; +- (void)selectCurrentScope:(id)fp8; +- (BOOL)selectFallbackInputForCommand:(id)fp8; +- (id)inputForCommand:(id)fp8 offset:(id *)fp12; +- (id)inputForCommand:(id)fp8; +- (void)executeCommandWithOptions:(id)fp8; +- (void)selectCommandResult:(id)fp8; +@end + +@interface WebView (OakFindNextPrevious) +- (void)viewSource:(id)fp8; +- (void)copySelectionToFindPboard:(id)fp8; +- (BOOL)findWithDirection:(BOOL)fp8; +- (void)findNext:(id)fp8; +- (void)findPrevious:(id)fp8; +- (id)findWithOptions:(id)fp8; +@end + +@interface OakDateFormatter : NSDateFormatter +{ +} + +- (id)stringForObjectValue:(id)fp8; +- (id)attributedStringForObjectValue:(id)fp8 withDefaultAttributes:(id)fp12; + +@end + +@interface OakDocument : NSObject +{ + NSString *filename; + NSDate *fileModificationDate; + unsigned int untitledCount; + unsigned int lastSavedMemento; + // Error parsing type: ^{storage={detail="data"{vector<shared_buffer<text::char_t>,std::allocator<shared_buffer<text::char_t> > >="_M_impl"{_Vector_impl="_M_start"^{shared_buffer<text::char_t>}"_M_finish"^{shared_buffer<text::char_t>}"_M_end_of_storage"^{shared_buffer<text::char_t>}}}"observers"{list<text::storage::observer*,std::allocator<text::storage::observer*> >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"mutex"{_opaque_pthread_mutex_t="__sig"l"__opaque"[40C]}}{kill_buffer_t="data"{vector<unichar,std::allocator<unichar> >="_M_impl"{_Vector_impl="_M_start"^S"_M_finish"^S"_M_end_of_storage"^S}}"memento"I"position"{iterator="line"I"column"I"storage"^{storage}}"disabled"B}{vector<text::storage::undo_record,std::allocator<text::storage::undo_record> >="_M_impl"{_Vector_impl="_M_start"^{undo_record}"_M_finish"^{undo_record}"_M_end_of_storage"^{undo_record}}}IIII{undo_manager="storage""stack"{stack<text::undo_manager::node,std::deque<text::undo_manager::node, std::allocator<text::undo_manager::node> > >="c"{deque<text::undo_manager::node,std::allocator<text::undo_manager::node> >="_M_impl"{_Deque_impl="_M_map"^^{node}"_M_map_size"I"_M_start"{_Deque_iterator<text::undo_manager::node,text::undo_manager::node&,text::undo_manager::node*>="_M_cur"^{node}"_M_first"^{node}"_M_last"^{node}"_M_node"^^{node}}"_M_finish"{_Deque_iterator<text::undo_manager::node,text::undo_manager::node&,text::undo_manager::node*>="_M_cur"^{node}"_M_first"^{node}"_M_last"^{node}"_M_node"^^{node}}}}}}}, name: storage + struct observer *observer; + struct vector<text::view*, std::allocator<text::view*>> *viewCache; + struct vector<text::view*, std::allocator<text::view*>> *openViews; + int fileEncoding; + int lineEnding; + BOOL isDocumentEdited; + BOOL byteOrderMark; + unsigned int openCount; + BOOL documentHasBeenSaved; + BOOL hideFromRecentMenu; + BOOL fileModifiedOnDiskAndWaitingForUser; + NSDictionary *auxiliaryFileInfo; +} + ++ (void)initialize; ++ (id)document; ++ (id)documentWithContentsOfFile:(id)fp8; ++ (void)sendAsyncAppleEvent:(id)fp8; ++ (int)defaultFileEncoding; ++ (int)defaultLineEnding; +- (id)initWithStorage:(struct storage *)fp8; +- (id)init; +- (id)initWithContentsOfFile:(id)fp8; +- (void)release; +- (BOOL)hideFromRecentMenu; +- (void)setHideFromRecentMenu:(BOOL)fp8; +- (BOOL)shouldSaveMetaData; +- (void)saveMetaData:(id)fp8 forView:(const struct view *)fp12; +- (void)dealloc; +- (unsigned int)length; +- (BOOL)byteOrderMark; +- (void)setByteOrderMark:(BOOL)fp8; +- (void)setFileEncodingAndLineEndingsToDefaults; +- (BOOL)writeToFile:(id)fp8; +- (id)displayName; +- (BOOL)isDocumentEdited; +- (void)setDocumentEdited:(BOOL)fp8; +- (id)filename; +- (id)fileModificationDate; +- (void)setFileModificationDate:(id)fp8; +- (void)setFilename:(id)fp8; +- (struct view *)obtainView; +- (void)releaseView:(struct view *)fp8; +- (id)metaData; +- (void)setMetaData:(id)fp8; +- (BOOL)checkForFilesystemChanges; +- (BOOL)reopenWithEncoding:(int)fp8; +- (int)fileEncoding; +- (void)setFileEncoding:(int)fp8; +- (int)lineEnding; +- (void)setLineEnding:(int)fp8; +- (BOOL)openDocument; +- (void)closeDocument; + +@end + +@interface OakDocumentCache : NSObject +{ + NSMutableDictionary *documents; +} + +- (id)init; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; + +@end + +@interface NSString (xattr) +- (void)_saveStringMetadata:(id)fp8 forKey:(id)fp12; +- (void)savePlistMetadata:(id)fp8 forKey:(id)fp12; +@end + +@interface OakDocumentController : NSWindowController +{ + OakTextView *textView; + id statusBar; + OakDocument *textDocument; + BOOL snapshotFrame; + BOOL showStatusBarView; + NSMutableDictionary *bindingProxy; +} + ++ (void)initialize; +- (id)textView; +- (void)dealloc; +- (void)setTextDocument:(id)fp8; +- (void)goToFileCounterpart:(id)fp8; +- (void)layoutWindow; +- (void)toggleShowStatusBarView:(id)fp8; +- (id)toggleShowStatusBarViewMenuTitle; +- (void)windowDidLoad; +- (void)windowDidResize:(id)fp8; +- (void)windowDidMove:(id)fp8; +- (void)savePanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(id)fp16; +- (void)saveAs:(id)fp8; +- (void)saveDocumentAs:(id)fp8; +- (void)saveDocument:(id)fp8; +- (BOOL)isDocumentEdited; +- (BOOL)canBeUsedForNewDocument; +- (void)applicationWillResignActiveNotification:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (BOOL)windowShouldClose:(id)fp8; +- (void)askToSaveAndCallBack:(id)fp8; +- (void)closeWarningDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(id)fp16; +- (void)closeWindow:(id)fp8 andCallStack:(id)fp12; +- (BOOL)validateMenuItem:(id)fp8; +- (void)revealFileInFinder:(id)fp8; +- (BOOL)textView:(id)fp8 willExecuteCommand:(id)fp12; +- (void)selectCommandResult:(id)fp8; + +@end + +@interface OakMacroContinuation : NSObject +{ + OakTextView *textView; + NSDictionary *command; + BundleItem *bundleItem; +} + ++ (id)macroContinuationForTextView:(id)fp8 withCommand:(id)fp12; +- (void)dealloc; +- (void)delayedExecuteBundleItem:(id)fp8; +- (void)continueMacro:(id)fp8 andCallStack:(id)fp12; + +@end + +@interface OakTextView (DragCommand) +- (BOOL)dropFile:(id)fp8; +@end + +@interface OakExecuteCommandManager : NSObject +{ + NSPanel *executeCommandPanel; + NSMenu *executeCommandMenu; + NSMutableDictionary *options; + NSMutableArray *history; + NSMutableArray *editors; +} + ++ (void)initialize; ++ (id)sharedInstance; +- (id)init; +- (void)applicationWillTerminate:(id)fp8; +- (void)populateMenu; +- (void)clearMenu:(id)fp8; +- (void)addToHistory:(id)fp8; +- (void)awakeFromNib; +- (void)orderFrontExecuteCommandPanel:(id)fp8; +- (void)setInput:(int)fp8; +- (void)setOutput:(int)fp8; +- (int)input; +- (int)output; +- (void)executeCommandWithTag:(id)fp8; +- (void)performExecuteCommand:(id)fp8; +- (void)objectDidBeginEditing:(id)fp8; +- (void)objectDidEndEditing:(id)fp8; + +@end + +@interface OakFileChooserWindow : NSPanel +{ + NSText *searchFieldEditor; +} + +- (id)fieldEditor:(BOOL)fp8 forObject:(id)fp12; +- (void)dealloc; +- (void)keyDown:(id)fp8; + +@end + +@interface OakFileChooser : OakTableViewController +{ + NSArray *allItems; + NSArray *displayItems; + NSDictionary *displayPrefix; + NSString *filterString; + OakProjectController *projectController; + NSSearchField *searchField; + NSDrawer *drawer; + id statusBar; +} + ++ (void)initialize; +- (void)windowDidLoad; +- (void)userDefaultsDidChange:(id)fp8; +- (void)orderFront:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (void)accept:(id)fp8; +- (void)cancel:(id)fp8; +- (void)dealloc; +- (void)selectDefaultItem; +- (void)search:(id)fp8; +- (void)tableViewSelectionDidChange:(id)fp8; +- (void)rearrangeObjects; +- (void)setFilterString:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; + +@end + +@interface OakTableViewController : NSWindowController +{ + NSTableView *tableView; +} + +- (void)moveUp:(id)fp8; +- (void)moveDown:(id)fp8; +- (void)movePageUp:(id)fp8; +- (void)movePageDown:(id)fp8; +- (void)pageUp:(id)fp8; +- (void)pageDown:(id)fp8; +- (void)scrollPageUp:(id)fp8; +- (void)scrollPageDown:(id)fp8; +- (void)moveToBeginningOfDocument:(id)fp8; +- (void)moveToEndOfDocument:(id)fp8; + +@end + +@interface OakSearchFieldEditor : NSTextView +{ +} + +- (void)keyDown:(id)fp8; +- (void)doCommandBySelector:(SEL)fp8; + +@end + +@interface OakFileChooserStatusBar : NSView +{ + NSString *string; + NSString *filterString; +} + +- (void)dealloc; +- (void)drawRect:(struct _NSRect)fp8; +- (void)setString:(id)fp8; +- (void)setFilterString:(id)fp8; +- (id)filterString; + +@end + +@interface DuffStringRanker (NormalizeFilterString) ++ (id)prepareFilterString:(id)fp8; +@end + +@interface OakFilenameTextField : NSTextField +{ +} + +- (void)selectBaseName:(id)fp8; +- (BOOL)becomeFirstResponder; + +@end + +@interface OakFileTemplateManager : NSObject +{ + NSMutableArray *templateArray; + int selectedItemTag; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (id)init; +- (void)addTemplatesToMenu:(id)fp8; +- (int)selectedItemTag; +- (void)setSelectedItemTag:(int)fp8; +- (id)extensionForTemplateWithTag:(int)fp8; +- (id)filesForTemplate:(id)fp8 withVariables:(id)fp12; +- (id)filesForTemplateWithTag:(int)fp8 andVariables:(id)fp12; + +@end + +@interface OakFindManager : NSObject +{ + NSPanel *findPanel; + NSPanel *findInProjectPanel; + NSTextField *findStatusText; + NSButton *replaceAllButton; + NSButton *findInProjectReplaceAllButton; + NSOutlineView *findInProjectOutlineView; + NSComboBox *findComboBox; + NSComboBox *replaceComboBox; + NSTextField *replaceLabel; + NSButton *toggleWindowSizeButton; + NSArray *findInProjectResults; + NSArray *findInProjectOutlineResults; + NSMutableArray *editors; + NSMutableDictionary *options; + int changeCount; + BOOL canReplaceInProject; +} + ++ (void)initialize; ++ (id)sharedInstance; +- (id)init; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (void)applicationWillTerminate:(id)fp8; +- (void)applicationWillResignActiveNotification:(id)fp8; +- (void)applicationDidBecomeActiveNotification:(id)fp8; +- (BOOL)loadNib; +- (void)didDoubleClickFindInProjectList:(id)fp8; +- (void)didBecomeMainWindow:(id)fp8; +- (void)orderFrontFindPanel:(id)fp8; +- (void)orderFrontFindInProjectPanel:(id)fp8; +- (void)writeStringToFindPboard:(id)fp8; +- (id)options; +- (void)setOptions:(id)fp8; +- (void)objectDidBeginEditing:(id)fp8; +- (void)objectDidEndEditing:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (void)commitEditing; +- (void)performFindAction:(id)fp8; +- (void)replaceAll:(id)fp8; +- (void)replaceAllInSelection:(id)fp8; +- (id)convertFindResultsToOutline:(id)fp8; +- (void)performFindInProjectAction:(id)fp8; +- (void)outlineViewSelectionDidChange:(id)fp8; +- (int)outlineView:(id)fp8 numberOfChildrenOfItem:(id)fp12; +- (id)outlineView:(id)fp8 child:(int)fp12 ofItem:(id)fp16; +- (BOOL)outlineView:(id)fp8 isItemExpandable:(id)fp12; +- (id)outlineView:(id)fp8 objectValueForTableColumn:(id)fp12 byItem:(id)fp16; +- (void)raiseControls; +- (void)lowerControls; +- (void)toggleWindowSize:(id)fp8; +- (unsigned int)comboBox:(id)fp8 indexOfItemWithStringValue:(id)fp12; +- (id)comboBox:(id)fp8 objectValueForItemAtIndex:(int)fp12; +- (int)numberOfItemsInComboBox:(id)fp8; + +@end + +@interface OakCompletionTextField : NSComboBox +{ +} + +- (id)textView:(id)fp8 completions:(id)fp12 forPartialWordRange:(struct _NSRange)fp16 indexOfSelectedItem:(int *)fp24; + +@end + +@interface OakFindInProjectOutlineView : NSOutlineView +{ +} + +- (void)mouseDown:(id)fp8; + +@end + +@interface OakNonKeyButton : NSButton +{ +} + +- (BOOL)canBecomeKeyView; + +@end + +@interface OakFindPanel : NSPanel +{ +} + +- (void)sendEvent:(id)fp8; + +@end + +@interface OakTextView (CompletionMatches) +- (id)matchesForString:(id)fp8; +@end + +@interface OakReloadBundlesScriptCommand : NSScriptCommand +{ +} + +- (id)performDefaultImplementation; + +@end + +@interface OakInsertTextScriptCommand : NSScriptCommand +{ +} + +- (id)performDefaultImplementation; + +@end + +@interface OakGetURLScriptCommand : NSScriptCommand +{ +} + +- (id)performDefaultImplementation; + +@end + +@interface OakGotoLineHelper : NSObject +{ + id options; +} + ++ (id)gotoLineHelperWithOptions:(id)fp8; +- (id)initWithOptions:(id)fp8; +- (void)dealloc; +- (void)windowDidBecomeKey:(id)fp8; + +@end + +@interface AppDelegate (OpenURL) +- (BOOL)openURLWithOptions:(id)fp8; +@end + +@interface OakImageAndTextCell : NSTextFieldCell +{ + NSImage *image; +} + +- (void)dealloc; +- (id)copyWithZone:(struct _NSZone *)fp8; +- (void)setImage:(id)fp8; +- (id)image; +- (void)editWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 event:(id)fp36; +- (void)selectWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 start:(int)fp36 length:(int)fp40; +- (void)drawWithFrame:(struct _NSRect)fp8 inView:(id)fp24; +- (struct _NSSize)cellSize; + +@end + +@interface OakInformationPanel : NSObject +{ + NSWindow *fileInfoPanel; + NSWindow *folderInfoPanel; + NSWindow *groupInfoPanel; + NSWindow *projectInfoPanel; + NSObjectController *objectController; + id item; + NSMutableArray *projectVariables; + NSString *name; + NSString *path; + NSString *fullPath; + NSString *filePattern; + NSString *folderPattern; + BOOL saveAsAbsolutePath; + id delegate; +} + +- (id)init; +- (void)dealloc; +- (void)windowWillClose:(id)fp8; +- (void)showWindowForProjectVariables:(id)fp8; +- (void)showWindowFor:(id)fp8 delegate:(id)fp12; +- (void)orderFrontChoosePathSheet:(id)fp8; +- (void)choosePathPanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; +- (void)setName:(id)fp8; +- (void)dirtyItem:(id)fp8 andChildren:(BOOL)fp12; +- (void)updateOutlineView; +- (void)setFilePattern:(id)fp8; +- (void)setFolderPattern:(id)fp8; +- (void)setSaveAsAbsolutePath:(id)fp8; + +@end + +@interface OakDefaultProjectVariable : NSObject +{ +} + +- (id)init; + +@end + +@interface OakKeyBindingManager : NSObject +{ + NSDictionary *keyBindings; +} + ++ (id)sharedInstance; +- (id)allKeyBindingFiles; +- (id)init; +- (BOOL)interpretKeyEvent:(id)fp8 forTextView:(id)fp12; +- (SEL)selectorForEvent:(id)fp8; + +@end + +@interface OakKeyEquivalentFieldEditor : NSTextView <OakKeyObserver> +{ + BOOL hotkeyEditing; + NSString *keyString; + int trackingRectTag; + BOOL hover; + BOOL pressed; + BOOL mouseDownInRemoveButtonFrame; +} + +- (struct _NSRect)removeButtonFrame; +- (BOOL)becomeFirstResponder; +- (BOOL)resignFirstResponder; +- (void)viewFrameDidChange:(id)fp8; +- (BOOL)shouldSwallowEvent:(id)fp8; +- (void)resetCursorRects; +- (void)mouseEntered:(id)fp8; +- (void)mouseExited:(id)fp8; +- (void)mouseDown:(id)fp8; +- (void)mouseUp:(id)fp8; +- (void)mouseDragged:(id)fp8; +- (void)drawRect:(struct _NSRect)fp8; +- (id)string; + +@end + +@interface OakKeyEquivalentCell : NSTextFieldCell +{ +} + +- (id)initTextCell:(id)fp8; +- (id)copyWithZone:(struct _NSZone *)fp8; +- (void)editWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 event:(id)fp36; +- (void)selectWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 start:(int)fp36 length:(int)fp40; +- (void)drawInteriorWithFrame:(struct _NSRect)fp8 inView:(id)fp24; +- (void)endEditing:(id)fp8; + +@end + +@interface OakKeyEquivalent : NSControl +{ + NSTextView *fieldEditor; + NSString *keyString; + NSMutableArray *observers; + BOOL isObservingFocus; + BOOL shouldSelectNextKeyView; + int isDiscarding; +} + ++ (Class)cellClass; +- (id)initWithFrame:(struct _NSRect)fp8; +- (BOOL)acceptsFirstMouse:(id)fp8; +- (BOOL)canBecomeKeyView; +- (BOOL)acceptsFirstResponder; +- (void)windowDidChangeKey:(id)fp8; +- (BOOL)becomeFirstResponder; +- (struct _NSRect)fieldEditorFrame; +- (void)viewWillMoveToWindow:(id)fp8; +- (void)setUpFieldEditor:(id)fp8; +- (void)textDidChange:(id)fp8; +- (void)textDidEndEditing:(id)fp8; +- (BOOL)commitEditing; +- (void)discardEditing; +- (void)mouseDown:(id)fp8; +- (void)drawRect:(struct _NSRect)fp8; +- (void)makeFocusRingDirty:(id)fp8; +- (void)setKeyString:(id)fp8; +- (id)value; +- (void)setValue:(id)fp8; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (void)bind:(id)fp8 toObject:(id)fp12 withKeyPath:(id)fp16 options:(id)fp20; +- (void)unbind:(id)fp8; +- (void)dealloc; + +@end + +@interface OakKeyEvent : NSObject +{ + NSString *key; + unsigned int qualifiers; +} + ++ (id)keyEvent; ++ (id)keyEventWithEvent:(id)fp8; ++ (id)keyEventWithString:(id)fp8; +- (id)initWithString:(id)fp8; +- (id)initWithKey:(id)fp8 andQualifiers:(unsigned int)fp12; +- (id)initWithEvent:(id)fp8; +- (id)copyWithZone:(struct _NSZone *)fp8; +- (void)dealloc; +- (BOOL)isEqual:(id)fp8; +- (id)stringRepresentation; +- (id)key; +- (void)setKey:(id)fp8; +- (unsigned int)qualifiers; +- (void)setQualifiers:(unsigned int)fp8; +- (void)setKey:(id)fp8 andQualifiers:(unsigned int)fp12; +- (id)glyphsForModifiers:(unsigned int)fp8; +- (id)modifierGlyphs; +- (id)keyGlyph; +- (id)glyphRepresentation; +- (id)description; + +@end + +@interface OakMacPADManager : NSObject +{ + NSTimer *softwareUpdateTimer; + int typeOfCheck; + BOOL manualCheck; + BOOL suspendAutomaticVersionCheck; + BOOL isPerformingVersionCheck; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (void)versionCheck:(id)fp8; +- (id)init; +- (void)scheduleNewVersionCheck; +- (void)didWakeNotification:(id)fp8; +- (void)timerDidFire:(id)fp8; +- (void)scheduledVersionCheck:(id)fp8; +- (void)performManualVersionCheck:(id)fp8; +- (void)returnSuccess:(id)fp8; +- (void)returnError:(id)fp8; + +@end + +@interface OakMacroManager : NSObject +{ +} + ++ (id)sharedInstance; +- (id)init; +- (id)scratchMacro; +- (void)setScratchMacro:(id)fp8; +- (BOOL)validateMenuItem:(id)fp8; +- (void)saveScratchMacro:(id)fp8; +- (void)playMacroWithTag:(id)fp8; + +@end + +@interface OakMenuButton : NSButton +{ + NSMenu *actionMenu; + NSOutlineView *outlineView; + id delegate; + NSPopUpButtonCell *popUpMenuCell; +} + +- (void)dealloc; +- (void)awakeFromNib; +- (BOOL)validateMenuItem:(id)fp8; +- (void)mouseDown:(id)fp8; +- (void)popUpMenuDidClose:(id)fp8; +- (void)projectRenameFile:(id)fp8; + +@end + +@interface OakOutlineView : NSOutlineView +{ + int clickedRow; +} + +- (id)initWithCoder:(id)fp8; +- (id)menuForEvent:(id)fp8; +- (BOOL)shouldActivate; +- (BOOL)acceptsFirstResponder; +- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)fp8; +- (void)textDidEndEditing:(id)fp8; +- (int)clickedRow; +- (void)keyDown:(id)fp8; +- (void)drawRect:(struct _NSRect)fp8; + +@end + +@interface NSBezierPath (RoundedRectangle) ++ (id)bezierPathWithRoundRectInRect:(struct _NSRect)fp8 radius:(float)fp24; +@end + +@interface OakPasteboardManager : NSObject +{ + NSPanel *sharedPanel; + NSTableView *tableView; + NSMutableArray *stack; + unsigned int pasteIndex; + int changeCount; +} + ++ (id)sharedInstance; +- (id)init; +- (void)windowDidResignKey:(id)fp8; +- (void)orderFrontPasteboardPanel:(id)fp8; +- (id)memento; +- (void)setMemento:(id)fp8; +- (void)storeClip:(id)fp8; +- (id)currentClip; +- (id)nextClip; +- (id)previousClip; +- (BOOL)hasClip; +- (void)applicationWillResignActiveNotification:(id)fp8; +- (void)applicationDidBecomeActiveNotification:(id)fp8; +- (void)pasteboard:(id)fp8 provideDataForType:(id)fp12; +- (void)tableViewSelectionDidChange:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; + +@end + +@interface OakTextClip : NSObject +{ + struct vector<unichar, std::allocator<unichar>> *text; + unsigned int indent; + BOOL rectangular; +} + +- (void)dealloc; +- (struct vector<unichar, std::allocator<unichar>> *)vector; +- (unsigned int)indent; +- (BOOL)rectangular; + +@end + +@interface OakColorWell : NSColorWell +{ +} + ++ (void)registerColorWell:(id)fp8; ++ (void)unregisterColorWell:(id)fp8; ++ (void)deactivateAll; +- (void)activate:(BOOL)fp8; +- (void)deactivate; + +@end + +@interface OakColorWellCell : NSCell +{ +} + +- (void)drawWithFrame:(struct _NSRect)fp8 inView:(id)fp24; +- (BOOL)trackMouse:(id)fp8 inRect:(struct _NSRect)fp12 ofView:(id)fp28 untilMouseUp:(BOOL)fp32; + +@end + +@interface OakSettingsTableView : NSTableView +{ +} + +- (void)drawRow:(int)fp8 clipRect:(struct _NSRect)fp12; +- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)fp8; +- (unsigned int)draggingUpdated:(id)fp8; +- (unsigned int)draggingEntered:(id)fp8; +- (void)draggingExited:(id)fp8; +- (BOOL)prepareForDragOperation:(id)fp8; +- (BOOL)performDragOperation:(id)fp8; + +@end + +@interface OakFontsAndColorsController : NSObject +{ + NSWindow *preferencesWindow; + NSPopUpButton *themePopUpButton; + NSTableView *settingsTableView; + NSPanel *themeListSheet; + NSTableView *themesTableView; + NSTextField *themeCommentTextField; + NSColor *foregroundColor; + NSColor *backgroundColor; + NSColor *selectionColor; + NSColor *caretColor; + NSColor *lineHighlightColor; + NSColor *invisiblesColor; + NSMutableArray *settingsArray; + id selection; + NSObjectController *themeObjectController; + id selectedTheme; + NSMutableArray *themesArray; + unsigned int disableThemeBroadcasting; + BOOL isDirty; + BOOL isEditingColorCell; + int colorCellRow; + NSString *colorCellIdentifier; + BOOL didInitialize; +} + ++ (id)sharedInstance; +- (id)init; +- (void)setDirty:(BOOL)fp8; +- (id)pathForNewFile:(id)fp8 inDirectory:(id)fp12; +- (BOOL)saveTheme:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (void)broadcastNewTheme; +- (id)selectableScopes; +- (id)font; +- (void)didChangeFont:(id)fp8; +- (void)deactivate; +- (void)didChangeColorPanel:(id)fp8; +- (void)didCloseColorPanel:(id)fp8; +- (void)populateThemePopUp; +- (void)awakeFromNib; +- (void)singleClick:(id)fp8; +- (void)addSetting:(id)fp8; +- (void)removeSetting:(id)fp8; +- (void)acceptThemeListChanges:(id)fp8; +- (void)cancelThemeListChanges:(id)fp8; +- (void)orderOutThemeList; +- (void)themeDidChange; +- (void)changeTheme:(id)fp8; +- (void)addTheme:(id)fp8; +- (void)duplicateTheme:(id)fp8; +- (void)removeTheme:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; +- (void)tableView:(id)fp8 setObjectValue:(id)fp12 forTableColumn:(id)fp16 row:(int)fp20; +- (BOOL)tableView:(id)fp8 writeRowsWithIndexes:(id)fp12 toPasteboard:(id)fp16; +- (unsigned int)tableView:(id)fp8 validateDrop:(id)fp12 proposedRow:(int)fp16 proposedDropOperation:(int)fp20; +- (BOOL)tableView:(id)fp8 acceptDrop:(id)fp12 row:(int)fp16 dropOperation:(int)fp20; +- (void)reloadData:(id)fp8; +- (void)tableViewSelectionDidChange:(id)fp8; +- (void)tableView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 row:(int)fp20; +- (void)setValue:(id)fp8 forKey:(id)fp12; +- (void)setValue:(id)fp8 forKeyPath:(id)fp12; +- (void)installTheme:(id)fp8; + +@end + +@interface OakPreferencesManager : NSWindowController +{ + NSView *generalPrefs; + NSView *textEditingPrefs; + NSView *fontsAndColorsPrefs; + NSView *softwareUpdatePrefs; + NSView *printingPrefs; + NSView *advancedPrefs; + NSArrayController *arrayController; + OakFontsAndColorsController *fontsAndcolorsController; + NSMutableArray *shellVariables; + NSMutableDictionary *toolbarItems; + NSString *selectedToolbarItem; + NSString *creatorCodeAction; + BOOL canSetCreatorCode; +} + ++ (void)initialize; ++ (id)sharedInstance; +- (id)init; +- (void)setCreatorCodeAction:(id)fp8; +- (void)dealloc; +- (void)orderFrontPreferences:(id)fp8; +- (void)privateChangeFont:(id)fp8; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (void)windowDidLoad; +- (void)windowWillClose:(id)fp8; +- (void)windowDidChangeKeyStatus:(id)fp8; +- (id)shellVariables; +- (void)setShellVariables:(id)fp8; +- (id)toolbarAllowedItemIdentifiers:(id)fp8; +- (id)toolbarDefaultItemIdentifiers:(id)fp8; +- (id)toolbarSelectableItemIdentifiers:(id)fp8; +- (float)toolbarHeight; +- (void)selectToolbarItem:(id)fp8; +- (id)toolbar:(id)fp8 itemForItemIdentifier:(id)fp12 willBeInsertedIntoToolbar:(BOOL)fp16; + +@end + +@interface OakProjectController : NSWindowController +{ + OakTabBarView *tabBarView; + OakTextView *textView; + id statusBar; + NSDrawer *groupsAndFilesDrawer; + NSOutlineView *outlineView; + NSImageView *imageView; + NSColor *backgroundColor; + NSWindow *newFileSheet; + NSPopUpButton *newFileTemplatePopupButton; + NSString *newFileSheetFilename; + NSString *newFileSheetDirectory; + int newFileCurrentTemplateTag; + NSString *projectDirectory; + NSString *filename; + NSMutableArray *rootItems; + NSMutableDictionary *currentDocument; + NSSet *allFilenames; + NSMutableDictionary *fileMetaData; + NSMutableArray *projectVariables; + BOOL showTabBarView; + BOOL showStatusBarView; + BOOL canOpenInformationPanel; + BOOL isScratchProject; + unsigned int untitledCount; + BOOL snapshotFrame; + NSArray *itemsBeingDragged; + NSMutableDictionary *bindingProxy; + NSMutableArray *observingItems; + OakFileChooser *fileChooser; + BOOL boldFolders; +} + ++ (void)initialize; ++ (BOOL)canOpenFile:(id)fp8; +- (id)init; +- (id)initWithContentsOfFile:(id)fp8; +- (void)prepareToDisposeItems:(id)fp8; +- (void)dealloc; +- (void)applicationWillTerminate:(id)fp8; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (BOOL)isItemChanged:(id)fp8; +- (void)applicationDidBecomeActiveNotification:(id)fp8; +- (id)textView; +- (id)documentForItem:(id)fp8; +- (id)filename; +- (id)projectDirectory; +- (void)setProjectDirectory:(id)fp8; +- (void)setFilename:(id)fp8; +- (void)setIsScratchProject:(BOOL)fp8; +- (id)displayName; +- (id)windowTitle; +- (void)layoutWindow; +- (void)toggleShowTabBarView:(id)fp8; +- (void)toggleShowStatusBarView:(id)fp8; +- (id)toggleShowTabBarViewMenuTitle; +- (id)toggleShowStatusBarViewMenuTitle; +- (void)openProjectDrawer:(id)fp8; +- (void)windowDidLoad; +- (void)windowDidResize:(id)fp8; +- (void)windowDidMove:(id)fp8; +- (void)setCloseTabActionAsPrimary:(BOOL)fp8; +- (void)tabBarView:(id)fp8 didOpenTab:(id)fp12; +- (void)tabBarView:(id)fp8 didCloseTab:(id)fp12; +- (void)windowDidChangeKey:(id)fp8; +- (void)setCurrentDocument:(id)fp8; +- (void)tabBarView:(id)fp8 didSelectTab:(id)fp12; +- (void)selectItem:(id)fp8; +- (id)itemWithPath:(id)fp8; +- (void)performCloseTab:(id)fp8; +- (void)performCloseAllTabs:(id)fp8; +- (BOOL)tabBarView:(id)fp8 shouldCloseTab:(id)fp12; +- (void)saveProject:(id)fp8; +- (void)saveProjectAs:(id)fp8; +- (void)saveProjectPanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(id)fp16; +- (id)mutableDocumentTreeForItems:(id)fp8; +- (id)savableDocumentTreeForItems:(id)fp8 inDirectory:(id)fp12; +- (BOOL)writeToFile:(id)fp8; +- (void)insertItems:(id)fp8 before:(id)fp12; +- (void)insertItemsBeforeSelection:(id)fp8; +- (void)setNewFileCurrentTemplateTag:(int)fp8; +- (void)projectNewFile:(id)fp8; +- (void)newFileSheetPopUpDidChange:(id)fp8; +- (void)performNewFileSheetAction:(id)fp8; +- (void)projectAddFiles:(id)fp8; +- (BOOL)panel:(id)fp8 shouldShowFilename:(id)fp12; +- (void)addFilesPanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; +- (void)projectNewGroup:(id)fp8; +- (void)projectGroupFiles:(id)fp8; +- (BOOL)selectedRowsShouldBeRemovedInOutlineView:(id)fp8; +- (void)projectRemoveFiles:(id)fp8; +- (void)removeProjectFilesWarningDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; +- (void)userDefaultsDidChange:(id)fp8; +- (int)outlineView:(id)fp8 numberOfChildrenOfItem:(id)fp12; +- (id)outlineView:(id)fp8 child:(int)fp12 ofItem:(id)fp16; +- (BOOL)outlineView:(id)fp8 isItemExpandable:(id)fp12; +- (void)outlineView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 item:(id)fp20; +- (id)outlineView:(id)fp8 objectValueForTableColumn:(id)fp12 byItem:(id)fp16; +- (void)outlineView:(id)fp8 setObjectValue:(id)fp12 forTableColumn:(id)fp16 byItem:(id)fp20; +- (void)singleClickItem:(id)fp8; +- (void)doubleClickItem:(id)fp8; +- (BOOL)validateMenuItem:(id)fp8; +- (void)goToNextFile:(id)fp8; +- (void)goToPreviousFile:(id)fp8; +- (void)goToFileCounterpart:(id)fp8; +- (void)revealInProject:(id)fp8; +- (BOOL)respondsToSelector:(SEL)fp8; +- (id)performSelector:(SEL)fp8; +- (id)performSelector:(SEL)fp8 withObject:(id)fp12; +- (id)_getOakTextViewInstance:(id)fp8; +- (BOOL)outlineView:(id)fp8 writeItems:(id)fp12 toPasteboard:(id)fp16; +- (unsigned int)outlineView:(id)fp8 validateDrop:(id)fp12 proposedItem:(id)fp16 proposedChildIndex:(int)fp20; +- (id)addFiles:(id)fp8 toArray:(id)fp12 atIndex:(int)fp16; +- (id)addFiles:(id)fp8 toArray:(id)fp12 atIndex:(int)fp16 fileFilter:(id)fp20 folderFilter:(id)fp24; +- (BOOL)outlineView:(id)fp8 acceptDrop:(id)fp12 item:(id)fp16 childIndex:(int)fp20; +- (void)saveDocument:(id)fp8; +- (void)saveDocumentAs:(id)fp8; +- (void)saveDocumentPanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; +- (BOOL)saveAllDocuments:(id)fp8; +- (void)applicationWillResignActiveNotification:(id)fp8; +- (void)openFileInNewWindow:(id)fp8; +- (void)revealFileInFinder:(id)fp8; +- (void)openFileWithFinder:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (unsigned int)numberOfModifiedDocuments; +- (BOOL)isDocumentEdited; +- (BOOL)windowShouldClose:(id)fp8; +- (void)askToSaveProjectAndCallBack:(id)fp8; +- (void)saveProjectWarningDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(id)fp16; +- (void)askToSaveModifiedDocumentsAndCallBack:(id)fp8; +- (void)saveModifiedDocumentsWarningDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(id)fp16; +- (void)askToSaveAndCallBack:(id)fp8; +- (void)closeWindow:(id)fp8 andCallStack:(id)fp12; +- (id)resultForMatchInLine:(id)fp8 fromLine:(unsigned long)fp12 fromColumn:(unsigned long)fp16 toLine:(unsigned long)fp20 toColumn:(unsigned long)fp24 memento:(unsigned long)fp28 fileInfo:(id)fp32; +- (id)findString:(id)fp8 inDocument:(id)fp12 withOptions:(id)fp16; +- (id)findInProjectWithOptions:(id)fp8; +- (void)selectFindInProjectResult:(id)fp8; +- (BOOL)textView:(id)fp8 willExecuteCommand:(id)fp12; +- (void)harvestItemsForArray:(id)fp8 foldersInto:(id)fp12 andFilesInto:(id)fp16; +- (id)findProjectDirectory; +- (id)environmentVariables; +- (void)selectCommandResult:(id)fp8; +- (void)toggleGroupsAndFilesDrawer:(id)fp8; +- (void)outlineViewSelectionDidChange:(id)fp8; +- (void)projectShowInformationPanel:(id)fp8; +- (void)toggleTreatFileAsText:(id)fp8; +- (void)goToFile:(id)fp8; +- (id)openFiles:(id)fp8; + +@end + +@interface OakIconCache : NSObject +{ + NSMutableDictionary *cache; + NSDictionary *bindings; + NSImage *folderIcon; + NSImage *updatingFolderIcon; +} + ++ (id)sharedInstance; +- (id)init; +- (id)iconForFolder; +- (id)iconForUpdatingFolder; +- (id)modifiedVersion:(id)fp8; +- (id)iconForFileType:(id)fp8 isModified:(BOOL)fp12; +- (id)applySymbolicLinkArrow:(id)fp8; + +@end + +@interface OakRegexpMatch : NSObject +{ + struct map<int, std::pair<int, int>, std::less<int>, std::allocator<std::pair<const int, std::pair<int, int>>>> *captures; +} + ++ (id)regexpMatchWithCaptures:; +- (id)initWithCaptures:; +- (void)dealloc; + +@end + +@interface OakRegistrationManager : NSObject +{ + NSPanel *registrationPanel; + NSView *registrationInfoView; + NSView *enterLicenseView; + NSTextField *ownerNameTextField; + NSString *owner; + NSString *licenseKey; + NSData *imageData; + NSString *registrationType; +} + ++ (void)initialize; ++ (id)sharedInstance; +- (id)init; +- (BOOL)canRegister; +- (id)ownerPortrait; +- (void)setOwner:(id)fp8; +- (void)setLicenseKey:(id)fp8; +- (void)setLicenseInfo:; +- (int)orderFrontRegistrationPanel:(id)fp8; +- (void)changeToLicenseInformationView:(id)fp8; +- (void)changeLicense:(id)fp8; +- (void)windowWillClose:(id)fp8; +- (void)ok:(id)fp8; +- (void)cancel:(id)fp8; +- (void)continue:(id)fp8; +- (void)lostLicense:(id)fp8; +- (void)buyOnline:(id)fp8; + +@end + +@interface OakTextView (snippets) +- (void)leaveCodeSnippetEditing; +- (void)nextSnippetField:(id)fp8; +- (void)previousSnippetField:(id)fp8; +- (void)insertBacktab:(id)fp8; +- (void)deleteTabTrigger:(id)fp8; +- (BOOL)expandCodeSnippet:(id)fp8; +- (void)insertSnippet:(id)fp8; +- (void)insertSnippetWithOptions:(id)fp8; +@end + +@interface OakStatusBar : NSView +{ + OakTabSizeWindowController *tabSizeWindowController; + NSImage *recordingMacroImage; + struct _NSRect recordingMacroImageRect; + NSTimer *recordingMacroTimer; + float animationTime; + NSMutableArray *observers; + struct _NSRect lineColumnRect; + struct _NSRect languageRect; + struct _NSRect tabSettingsRect; + struct _NSRect bundlePopUpRect; + struct _NSRect symbolPopUpRect; + NSPopUpButtonCell *languagePopUpButtonCell; + NSArray *languageChoices; + int selectedLanguageIndex; + int lineNumber; + int columnNumber; + NSString *currentMode; + id currentSymbol; + int tabSize; + BOOL softTabs; + BOOL isRecordingMacro; + BOOL enabled; +} + +- (id)initWithFrame:(struct _NSRect)fp8; +- (void)dealloc; +- (void)setFrame:(struct _NSRect)fp8; +- (void)updateMacroRecordingAnimation:(id)fp8; +- (void)setLineNumber:(int)fp8; +- (void)setColumnNumber:(int)fp8; +- (void)setTabSize:(int)fp8; +- (void)setSoftTabs:(BOOL)fp8; +- (void)setCurrentSymbol:(id)fp8; +- (void)setIsRecordingMacro:(BOOL)fp8; +- (void)setCurrentMode:(id)fp8; +- (void)layout; +- (void)setEnabled:(BOOL)fp8; +- (void)drawText:(id)fp8 inRect:(struct _NSRect)fp12; +- (void)drawRect:(struct _NSRect)fp8; +- (BOOL)acceptsFirstMouse:(id)fp8; +- (void)disposeMenuChoices:(id)fp8; +- (void)popUpMenuDidClose:(id)fp8; +- (void)showPopUpCell:(id)fp8 withFrame:(struct _NSRect)fp12; +- (void)showBundlePopUp; +- (void)mouseDown:(id)fp8; +- (void)toggleKeepSymbolsAlphabetized:(id)fp8; +- (BOOL)performKeyEquivalent:(id)fp8; +- (void)performLanguageMenuChoice:(id)fp8; +- (void)performSymbolMenuChoice:(id)fp8; +- (void)performTabSettingsMenuChoice:(id)fp8; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (void)bind:(id)fp8 toObject:(id)fp12 withKeyPath:(id)fp16 options:(id)fp20; +- (void)unbind:(id)fp8; + +@end + +@interface OakTabSizeWindowController : NSWindowController +{ +} + +- (void)didMoveSlider:(id)fp8; + +@end + +@interface OakTabBarView : NSView +{ + id delegate; + NSMutableArray *tabs; + struct _NSRect clipIndicatorRect; + struct vector<NSTrackingRectTag, std::allocator<NSTrackingRectTag>> *trackingRectTags; + struct _NSPoint mouseDownPosition; + struct OakClickInfo mouseDownInfo; + OakTab *draggedTab; + int draggedTabNewIndex; + BOOL drawClipIndicator; + NSMutableArray *toolTips; +} + +- (id)initWithFrame:(struct _NSRect)fp8; +- (void)dealloc; +- (void)setDelegate:(id)fp8; +- (id)delegate; +- (void)closeTab:(id)fp8; +- (void)selectTab:(id)fp8; +- (void)selectNextTab:(id)fp8; +- (void)selectPreviousTab:(id)fp8; +- (void)sizeTabsToFitAndChangeTrackingRects:(BOOL)fp8; +- (void)sizeTabsToFit; +- (void)updateWindowKeyStateForTabs:(id)fp8; +- (void)viewDidMoveToWindow; +- (void)viewWillMoveToWindow:(id)fp8; +- (void)mouseEntered:(id)fp8; +- (void)mouseExited:(id)fp8; +- (void)viewFrameDidChange:(id)fp8; +- (id)addTabWithTitle:(id)fp8 andIdentifier:(id)fp12; +- (BOOL)selectTabWithIdentifier:(id)fp8; +- (void)closeTabsWithIdentifiers:(id)fp8; +- (void)setIsModified:(BOOL)fp8 forTabWithIdentifier:(id)fp12; +- (void)setTitle:(id)fp8 forTabWithIdentifier:(id)fp12; +- (void)changeIdentiferTo:(id)fp8 forTabWithIdentifier:(id)fp12; +- (struct OakClickInfo)clickInfoForPoint:(struct _NSPoint)fp8; +- (BOOL)acceptsFirstMouse:(id)fp8; +- (BOOL)shouldDelayWindowOrderingForEvent:(id)fp8; +- (void)preventWindowOrdering:(id)fp8; +- (void)mouseDown:(id)fp8; +- (void)mouseUp:(id)fp8; +- (void)drawRect:(struct _NSRect)fp8; +- (void)takeSelectedTabFrom:(id)fp8; +- (void)closeSelectedTab; +- (void)mouseDragged:(id)fp8; +- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)fp8; +- (unsigned int)dragOperationForInfo:(id)fp8; +- (BOOL)performDragOperation:(id)fp8; +- (unsigned int)draggingUpdated:(id)fp8; +- (void)draggingExited:(id)fp8; + +@end + +@interface OakTab : NSObject +{ + NSString *title; + id identifier; + struct _NSRect frame; + BOOL hidden; + BOOL isWindowKey; + BOOL isModified; + int state; + int closeButtonState; +} + ++ (id)tabWithTitle:(id)fp8 andIdentifier:(id)fp12; +- (void)dealloc; +- (id)textAttributes; +- (void)drawRect:(struct _NSRect)fp8; +- (float)width; +- (struct _NSRect)closeButtonFrame; +- (BOOL)containsPoint:(struct _NSPoint)fp8; +- (BOOL)closeButtonContainsPoint:(struct _NSPoint)fp8; +- (struct _NSRect)frame; +- (void)setFrame:(struct _NSRect)fp8; +- (BOOL)isWindowKey; +- (void)setIsWindowKey:(BOOL)fp8; +- (BOOL)isModified; +- (void)setIsModified:(BOOL)fp8; +- (BOOL)hidden; +- (void)setHidden:(BOOL)fp8; +- (id)title; +- (id)identifier; +- (void)setTitle:(id)fp8; +- (void)setIdentifier:(id)fp8; +- (int)buttonState; +- (void)setButtonState:(int)fp8; +- (int)closeButtonState; +- (void)setCloseButtonState:(int)fp8; + +@end + +@interface OakTextView : NSView <NSTextInput> +{ + NSMutableArray *bindingObservers; + OakDocument *document; + // Error parsing type: ^{view={iterator_observer="_vptr$observer"^^?"storage""mirrors"{list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>,std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"previous_mirrors"{list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>,std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"notifications"{list<text::iterator_observer::subset,std::allocator<text::iterator_observer::subset> >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"previous_notifications"{list<text::iterator_observer::subset,std::allocator<text::iterator_observer::subset> >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"mirror_undo_map"{map<text::undo_key,std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > > >="_M_t"{_Rb_tree<text::undo_key,std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > >,std::_Select1st<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > > >="_M_impl"{_Rb_tree_impl<std::less<text::undo_key>,false>="_M_key_compare"{less<text::undo_key>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"notify_undo_map"{map<text::undo_key,std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > > >="_M_t"{_Rb_tree<text::undo_key,std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > >,std::_Select1st<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > > >="_M_impl"{_Rb_tree_impl<std::less<text::undo_key>,false>="_M_key_compare"{less<text::undo_key>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"pending_erases"{vector<text::iterator_observer::pending_erase,std::allocator<text::iterator_observer::pending_erase> >="_M_impl"{_Vector_impl="_M_start"^{pending_erase}"_M_finish"^{pending_erase}"_M_end_of_storage"^{pending_erase}}}"pending_inserts"{vector<text::iterator_observer::pending_insert,std::allocator<text::iterator_observer::pending_insert> >="_M_impl"{_Vector_impl="_M_start"^{pending_insert}"_M_finish"^{pending_insert}"_M_end_of_storage"^{pending_insert}}}"did_insert_data"{vector<text::char_t,std::allocator<text::char_t> >="_M_impl"{_Vector_impl="_M_start"^S"_M_finish"^S"_M_end_of_storage"^S}}"max_memento"I"updating_mirror"B"performing_undo"B"track_memento"B}{iterator_observer="_vptr$observer"^^?"storage""mirrors"{list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>,std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"previous_mirrors"{list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>,std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"notifications"{list<text::iterator_observer::subset,std::allocator<text::iterator_observer::subset> >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"previous_notifications"{list<text::iterator_observer::subset,std::allocator<text::iterator_observer::subset> >="_M_impl"{_List_impl="_M_node"{_List_node_base="_M_next"^{_List_node_base}"_M_prev"^{_List_node_base}}}}"mirror_undo_map"{map<text::undo_key,std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > > >="_M_t"{_Rb_tree<text::undo_key,std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > >,std::_Select1st<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<std::pair<text::iterator_observer::subset, text::iterator_observer::subset>, std::allocator<std::pair<text::iterator_observer::subset, text::iterator_observer::subset> > > > > >="_M_impl"{_Rb_tree_impl<std::less<text::undo_key>,false>="_M_key_compare"{less<text::undo_key>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"notify_undo_map"{map<text::undo_key,std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > > >="_M_t"{_Rb_tree<text::undo_key,std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > >,std::_Select1st<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, std::list<text::iterator_observer::subset, std::allocator<text::iterator_observer::subset> > > > >="_M_impl"{_Rb_tree_impl<std::less<text::undo_key>,false>="_M_key_compare"{less<text::undo_key>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"pending_erases"{vector<text::iterator_observer::pending_erase,std::allocator<text::iterator_observer::pending_erase> >="_M_impl"{_Vector_impl="_M_start"^{pending_erase}"_M_finish"^{pending_erase}"_M_end_of_storage"^{pending_erase}}}"pending_inserts"{vector<text::iterator_observer::pending_insert,std::allocator<text::iterator_observer::pending_insert> >="_M_impl"{_Vector_impl="_M_start"^{pending_insert}"_M_finish"^{pending_insert}"_M_end_of_storage"^{pending_insert}}}"did_insert_data"{vector<text::char_t,std::allocator<text::char_t> >="_M_impl"{_Vector_impl="_M_start"^S"_M_finish"^S"_M_end_of_storage"^S}}"max_memento"I"updating_mirror"B"performing_undo"B"track_memento"B}{snippet_observer_t="_vptr$observer"^^?"view""storage""insert_position"{iterator="line"I"column"I"storage"^{storage}}"current_snippet"^{snippet_t}"pending_insert"{vector<text::snippet_observer_t::insert_t,std::allocator<text::snippet_observer_t::insert_t> >="_M_impl"{_Vector_impl="_M_start"^{insert_t}"_M_finish"^{insert_t}"_M_end_of_storage"^{insert_t}}}"pending_erase"{vector<text::snippet_observer_t::erase_t,std::allocator<text::snippet_observer_t::erase_t> >="_M_impl"{_Vector_impl="_M_start"^{erase_t}"_M_finish"^{erase_t}"_M_end_of_storage"^{erase_t}}}}{selection="first_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"last_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"current_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"column_mode"B"data"{vector<text::char_t,std::allocator<text::char_t> >="_M_impl"{_Vector_impl="_M_start"^S"_M_finish"^S"_M_end_of_storage"^S}}}{selection="first_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"last_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"current_mark"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"column_mode"B"data"{vector<text::char_t,std::allocator<text::char_t> >="_M_impl"{_Vector_impl="_M_start"^S"_M_finish"^S"_M_end_of_storage"^S}}}IIIIIIIBBBBBBB{map<size_t,std::_List_iterator<text::iterator_observer::subset>,std::less<UniCharCount>,std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset> > > >="_M_t"{_Rb_tree<size_t,std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset> >,std::_Select1st<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset> > >,std::less<UniCharCount>,std::allocator<std::pair<const size_t, std::_List_iterator<text::iterator_observer::subset> > > >="_M_impl"{_Rb_tree_impl<std::less<UniCharCount>,false>="_M_key_compare"{less<UniCharCount>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}iBB{storage_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"view""observer_id"{_List_iterator<text::storage::observer*>="_M_node"^{_List_node_base}}}{tokenize_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"all_rules"^{__CFArray}"start_rule"I"lines"{vector<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage> > >,std::allocator<std::map<uint32_t, bit_stack::storage, std::less<uint32_t>, std::allocator<std::pair<const uint32_t, bit_stack::storage> > > > >="_M_impl"{_Vector_impl="_M_start"^{map<uint32_t,bit_stack::storage,std::less<uint32_t>,std::allocator<std::pair<const uint32_t, bit_stack::storage> > >}"_M_finish"^{map<uint32_t,bit_stack::storage,std::less<uint32_t>,std::allocator<std::pair<const uint32_t, bit_stack::storage> > >}"_M_end_of_storage"^{map<uint32_t,bit_stack::storage,std::less<uint32_t>,std::allocator<std::pair<const uint32_t, bit_stack::storage> > >}}}"back_references"{map<size_t,std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper> > >,std::less<UniCharCount>,std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper> > > > > >="_M_t"{_Rb_tree<size_t,std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper> > > >,std::_Select1st<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper> > > > >,std::less<UniCharCount>,std::allocator<std::pair<const size_t, std::stack<nfa_wrapper, std::deque<nfa_wrapper, std::allocator<nfa_wrapper> > > > > >="_M_impl"{_Rb_tree_impl<std::less<UniCharCount>,false>="_M_key_compare"{less<UniCharCount>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"thread"^{_opaque_pthread_t}"main_wait"{_opaque_pthread_cond_t="__sig"l"__opaque"[24C]}"worker_wait"{_opaque_pthread_cond_t="__sig"l"__opaque"[24C]}"first_dirty_line"I"last_dirty_line"I"requested_line"I"redraw_first"I"redraw_last"I"needs_to_redraw"B"worker_should"i"main_is"i"view""storage""textView"^v}{bookmark_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"view""nodes"{map<size_t,size_t,std::less<UniCharCount>,std::allocator<std::pair<const size_t, size_t> > >="_M_t"{_Rb_tree<size_t,std::pair<const size_t, size_t>,std::_Select1st<std::pair<const size_t, size_t> >,std::less<UniCharCount>,std::allocator<std::pair<const size_t, size_t> > >="_M_impl"{_Rb_tree_impl<std::less<UniCharCount>,false>="_M_key_compare"{less<UniCharCount>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}}{spellcheck_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"view""nodes"{vector<text::view::spellcheck_filter::node_t,std::allocator<text::view::spellcheck_filter::node_t> >="_M_impl"{_Vector_impl="_M_start"^{node_t}"_M_finish"^{node_t}"_M_end_of_storage"^{node_t}}}}{folding_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"storage""view""begin_pattern"^{ptrn_t}"end_pattern"^{ptrn_t}"markers"{set<text::view::folding_filter::marker_t,std::less<text::view::folding_filter::marker_t>,std::allocator<text::view::folding_filter::marker_t> >="_M_t"{_Rb_tree<text::view::folding_filter::marker_t,text::view::folding_filter::marker_t,std::_Identity<text::view::folding_filter::marker_t>,std::less<text::view::folding_filter::marker_t>,std::allocator<text::view::folding_filter::marker_t> >="_M_impl"{_Rb_tree_impl<std::less<text::view::folding_filter::marker_t>,false>="_M_key_compare"{less<text::view::folding_filter::marker_t>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"foldings"{set<text::view::folding_filter::folding_t,std::less<text::view::folding_filter::folding_t>,std::allocator<text::view::folding_filter::folding_t> >="_M_t"{_Rb_tree<text::view::folding_filter::folding_t,text::view::folding_filter::folding_t,std::_Identity<text::view::folding_filter::folding_t>,std::less<text::view::folding_filter::folding_t>,std::allocator<text::view::folding_filter::folding_t> >="_M_impl"{_Rb_tree_impl<std::less<text::view::folding_filter::folding_t>,false>="_M_key_compare"{less<text::view::folding_filter::folding_t>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}"needs_to_parse"B"last_valid_line"I}{soft_wrap_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"view""erase_first"{pos="line"I"column"I}"erase_last"{pos="line"I"column"I}"ranges"{vector<text::view::soft_wrap_filter::line_range,std::allocator<text::view::soft_wrap_filter::line_range> >="_M_impl"{_Vector_impl="_M_start"^{line_range}"_M_finish"^{line_range}"_M_end_of_storage"^{line_range}}}}{view_filter="_vptr$observer"^^?"toward_storage"^{filter}"toward_view"^{filter}"view""undo_map"{map<text::undo_key,text::selection,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, text::selection> > >="_M_t"{_Rb_tree<text::undo_key,std::pair<const text::undo_key, text::selection>,std::_Select1st<std::pair<const text::undo_key, text::selection> >,std::less<text::undo_key>,std::allocator<std::pair<const text::undo_key, text::selection> > >="_M_impl"{_Rb_tree_impl<std::less<text::undo_key>,false>="_M_key_compare"{less<text::undo_key>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}}{map<text::view::filter_index,text::filter*,std::less<text::view::filter_index>,std::allocator<std::pair<const text::view::filter_index, text::filter*> > >="_M_t"{_Rb_tree<text::view::filter_index,std::pair<const text::view::filter_index, text::filter*>,std::_Select1st<std::pair<const text::view::filter_index, text::filter*> >,std::less<text::view::filter_index>,std::allocator<std::pair<const text::view::filter_index, text::filter*> > >="_M_impl"{_Rb_tree_impl<std::less<text::view::filter_index>,false>="_M_key_compare"{less<text::view::filter_index>=}"_M_header"{_Rb_tree_node_base="_M_color"i"_M_parent"^{_Rb_tree_node_base}"_M_left"^{_Rb_tree_node_base}"_M_right"^{_Rb_tree_node_base}}"_M_node_count"I}}}{completion_helper="memento"I"offset"I"index"I"it"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"cur"{view_iterator="view"^{view}"base"{iterator="line"I"column"I"storage"^{storage}}"offset"I"desired_column"I}"words"{vector<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >,std::allocator<std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > > >="_M_impl"{_Vector_impl="_M_start"^{basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >}"_M_finish"^{basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >}"_M_end_of_storage"^{basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >}}}}}, name: view + struct map<bit_stack::storage, objc_ptr<objc_object*>, std::less<bit_stack::storage>, std::allocator<std::pair<const bit_stack::storage, objc_ptr<objc_object*>>>> *styleCache; + struct action_map *actions; + struct title_action_map *title_actions; + struct ATSUI_render *render; + NSMutableArray *macroRecordingBuffer; + unsigned int viewChangeNesting; + BOOL fillBackground; + BOOL hasMarkedTextBeingEdited; + BOOL didPressAlternateKey; + NSDate *didPressAlternateKeyAtTime; + unsigned int lastModifierFlags; + BOOL leftMouseDown; + BOOL isActivatingClick; + BOOL isShowingDragCursor; + NSTimer *initiateDragTimer; + NSTimer *dragScrollTimer; + NSEvent *activationEvent; + struct _NSPoint mouseDownPoint; + BOOL hasDragInside; + BOOL dragIsLocal; + NSTimer *blinkCaretTimer; + BOOL isCaretHidden; + struct _NSRect textFrame; + float lineNumbersOffset; + float bookmarksOffset; + float foldingsOffset; + NSTimer *showFoldedTextTimer; + struct _NSRect showFoldedTextTriggerRectangle; + OakTooltipWindow *showFoldedTextWindow; + unsigned int showFoldedTextFromLine; + unsigned int showFoldedTextToLine; + OakWebPreviewManager *webPreviewManager; + struct observer *webPreviewChangeObserver; + BOOL pendingUpdateFunctionPopUp; + NSTimer *updateFunctionPopUpTimer; + NSArray *functionPopUp; + id currentSymbol; + struct observer *functionPopupChangeObserver; + unsigned int clickCount; + unsigned int mouseDownAtPositionLine; + unsigned int mouseDownAtPositionColumn; + unsigned int lineNumberDigits; + OakISearchWindow *iSearchWindow; + NSFont *font; + _Bool hasCustomFont; + unsigned int rightMargin; + unsigned int tabSize; + _Bool openFilesFolded; + _Bool freehandedMode; + _Bool overwriteMode; + _Bool softWrap; + _Bool hardWrap; + _Bool autoIndent; + _Bool indentedPaste; + _Bool continuousSpellChecking; + _Bool treatsSpacesAsTabs; + _Bool smartTyping; + _Bool foldings; + _Bool lineNumbers; + _Bool showSoftWrapInGutter; + _Bool showBookmarksInGutter; + _Bool expandSnippetsOnTab; + _Bool antiAliasEnabled; + _Bool showInvisibles; + NSString *currentMode; + id currentStyleSheet; + id languageUUID; + _Bool highlightWrapMargin; + _Bool highlightCurrentLine; + _Bool showWrapMargin; +} + ++ (void)initialize; +- (void)undo:(id)fp8; +- (void)redo:(id)fp8; +- (void)toggleMacroRecording:(id)fp8; +- (void)recordMacroCommand:(SEL)fp8 argument:(id)fp12; +- (void)playMacroWithOptions:(id)fp8; +- (void)abortMacroRecording:(id)fp8; +- (id)toggleMacroRecordingMenuTitle; +- (BOOL)canAbortMacroRecording; +- (id)initWithFrame:(struct _NSRect)fp8; +- (void)dealloc; +- (void)applicationDidBecomeActiveNotification:(id)fp8; +- (void)userDefaultsDidChange:(id)fp8; +- (void)viewWillMoveToWindow:(id)fp8; +- (struct _NSRect)caretRefreshRectangle; +- (void)setSelectionNeedsDisplay:(BOOL)fp8; +- (BOOL)isOpaque; +- (BOOL)isFlipped; +- (BOOL)canBecomeKeyView; +- (BOOL)acceptsFirstResponder; +- (BOOL)resignFirstResponder; +- (id)document; +- (BOOL)becomeFirstResponder; +- (void)windowDidChangeKeyStatus:(id)fp8; +- (void)snapshotMetaData; +- (void)observeValueForKeyPath:(id)fp8 ofObject:(id)fp12 change:(id)fp16 context:(void *)fp20; +- (void)setDocument:(id)fp8; +- (void)myScrollRectToVisible:(id)fp8; +- (BOOL)validateMenuItem:(id)fp8; +- (id)performSelector:(SEL)fp8 withObject:(id)fp12; +- (BOOL)tryToPerform:(SEL)fp8 with:(id)fp12; +- (BOOL)respondsToSelector:(SEL)fp8; +- (void)keyDown:(id)fp8; +- (BOOL)hasMarkedText; +- (struct _NSRange)markedRange; +- (struct _NSRange)selectedRange; +- (id)validAttributesForMarkedText; +- (struct _NSRect)firstRectForCharacterRange:(struct _NSRange)fp8; +- (long)conversationIdentifier; +- (unsigned int)characterIndexForPoint:(struct _NSPoint)fp8; +- (id)attributedSubstringFromRange:(struct _NSRange)fp8; +- (void)doCommandBySelector:(SEL)fp8; +- (void)setMarkedText:(id)fp8 selectedRange:(struct _NSRange)fp12; +- (void)unmarkText; +- (void)insertText:(id)fp8; +- (void)pasteFromHistory:(id)fp8; +- (void)deleteBackward:(id)fp8; +- (void)deleteForward:(id)fp8; +- (void)deleteToEndOfParagraph:(id)fp8; +- (void)flagsChanged:(id)fp8; +- (void)centerSelectionInVisibleArea:(id)fp8; +- (void)setFont:(id)fp8; +- (void)makeTextLarger:(id)fp8; +- (void)makeTextSmaller:(id)fp8; +- (BOOL)canMakeFontBigger; +- (BOOL)canMakeFontSmaller; +- (BOOL)hasSelection; +- (unsigned long)internalReplaceAll:(id)fp8 error:(id *)fp12; +- (void)replaceAll:(id)fp8; +- (void)replaceAllInSelection:(id)fp8; +- (id)findWithOptions:(id)fp8; +- (id)validRequestorForSendType:(id)fp8 returnType:(id)fp12; +- (BOOL)writeSelectionToPasteboard:(id)fp8 types:(id)fp12; +- (BOOL)readSelectionFromPasteboard:(id)fp8; +- (void)setupBlinkCaretTimer; +- (void)blinkCaret:(id)fp8; +- (void)showCaret; +- (void)centerCaretInDisplay:(id)fp8; +- (struct pos)eventPosition:(id)fp8; +- (void)changeToDragPointer:(id)fp8; +- (void)resetCursorRects; +- (BOOL)acceptsFirstMouse:(id)fp8; +- (BOOL)shouldDelayWindowOrderingForEvent:(id)fp8; +- (int)dragDelay; +- (void)rightMouseDown:(id)fp8; +- (void)mouseDown:(id)fp8; +- (void)mouseUp:(id)fp8; +- (void)startDragForEvent:(id)fp8; +- (void)autoscrollTimerFired:(id)fp8; +- (void)mouseDragged:(id)fp8; +- (void)scrollViewByX:(float)fp8 byY:(long)fp12; +- (void)scrollLineUp:(id)fp8; +- (void)scrollLineDown:(id)fp8; +- (void)scrollColumnLeft:(id)fp8; +- (void)scrollColumnRight:(id)fp8; +- (void)setHasDragInside:(BOOL)fp8; +- (unsigned int)draggingSourceOperationMaskForLocal:(BOOL)fp8; +- (unsigned int)dragOperationForInfo:(id)fp8; +- (unsigned int)draggingEntered:(id)fp8; +- (unsigned int)draggingUpdated:(id)fp8; +- (void)draggingExited:(id)fp8; +- (BOOL)prepareForDragOperation:(id)fp8; +- (BOOL)performDragOperation:(id)fp8; +- (void)concludeDragOperation:(id)fp8; +- (void)changeSpelling:(id)fp8; +- (void)movePageUp:(id)fp8; +- (void)movePageDown:(id)fp8; +- (void)movePageUpAndModifySelection:(id)fp8; +- (void)movePageDownAndModifySelection:(id)fp8; +- (BOOL)canReopenWithEncoding; +- (BOOL)reopenWithEncodingIsChecked:(id)fp8; +- (void)reopenWithEncoding:(id)fp8; +- (void)fillSelectionWithString:(id)fp8; +- (void)performFillSelectionWithAction:(id)fp8; +- (void)fillSelectionWith:(id)fp8; +- (void)recalcFrameSize; +- (void)setFrame:(struct _NSRect)fp8; +- (void)updateScreenWidth; +- (void)scrollPageUp:(id)fp8; +- (void)scrollPageDown:(id)fp8; +- (void)scrollToBeginningOfDocument:(id)fp8; +- (void)scrollToEndOfDocument:(id)fp8; +- (id)stringValue; +- (id)currentMode; +- (void)setCurrentMode:(id)fp8; +- (id)_getOakTextViewInstance:(id)fp8; + +@end + +@interface OakTextView (bindings) +- (void)bind:(id)fp8 toObject:(id)fp12 withKeyPath:(id)fp16 options:(id)fp20; +- (void)unbind:(id)fp8; +- (void)updateValue:(id)fp8 forKey:(id)fp12; +- (void)setMacroRecordingBuffer:(id)fp8; +@end + +@interface OakTextView (Bookmarks) +- (void)toggleCurrentBookmark:(id)fp8; +- (id)toggleCurrentBookmarkMenuTitle; +- (void)goToNextBookmark:(id)fp8; +- (void)goToPreviousBookmark:(id)fp8; +@end + +@interface OakTextView (drawRect) +- (struct _NSPoint)iteratorPosition:; +- (void)toggleShowInvisibles:(id)fp8; +- (id)toggleShowInvisiblesMenuTitle; +- (void)drawRect:(struct _NSRect)fp8; +- (void)setupTextFrame; +- (unsigned int)typeForLine:(id)fp8 withPatterns:(id [4])fp12; +- (int)currentIndentForContent:(id)fp8 atLine:(unsigned long)fp12; +- (int)indentForCurrentLine; +- (unsigned long)currentIndent; +- (unsigned long)indentLine:(unsigned long)fp8; +- (id)indentMenuTitle; +- (void)indent:(id)fp8; +@end + +@interface OakTextView (ExecuteSelection) +- (void)executeSelectionInsertingOutput:(id)fp8; +- (void)executeSelectionAppendingOutput:(id)fp8; +- (void)executeSelectionReplacingSelection:(id)fp8; +@end + +@interface OakTextView (Extension) ++ (void)load; ++ (void)populateWrapColumnMenu:(id)fp8; +- (void)selectFollowingKeyView:(id)fp8; +- (void)selectPrecedingKeyView:(id)fp8; +- (BOOL)takeRightMarginFromIsChecked:(id)fp8; +- (void)setContinuousSpellCheckingEnabled:(BOOL)fp8; +- (void)setExpandSnippetsOnTab:(BOOL)fp8; +- (void)setSoftWrap:(BOOL)fp8; +- (void)setFreehandedEdit:(BOOL)fp8; +- (void)setTabSize:(unsigned long)fp8; +- (void)setRightMargin:(unsigned long)fp8; +- (void)setOverwriteMode:(BOOL)fp8; +- (void)setOpenFilesFolded:(BOOL)fp8; +- (void)setShowSoftWrapInGutter:(BOOL)fp8; +- (void)setShowBookmarksInGutter:(BOOL)fp8; +- (unsigned long)tabSize; +- (BOOL)freehandedEdit; +- (void)toggleFreehandedEdit:(id)fp8; +- (BOOL)isContinuousSpellCheckingEnabled; +- (void)toggleContinuousSpellChecking:(id)fp8; +- (BOOL)toggleContinuousSpellCheckingIsChecked:(id)fp8; +- (BOOL)expandSnippetsOnTab; +- (void)toggleExpandSnippetsOnTab:(id)fp8; +- (BOOL)toggleExpandSnippetsOnTabIsChecked:(id)fp8; +- (BOOL)canToggleHardWrap; +- (BOOL)overwriteMode; +- (void)toggleOverwriteMode:(id)fp8; +- (BOOL)softWrap; +- (void)toggleSoftWrap:(id)fp8; +- (BOOL)autoIndent; +- (BOOL)hardWrap; +- (BOOL)indentedPaste; +- (void)setAutoIndent:(BOOL)fp8; +- (void)setHardWrap:(BOOL)fp8; +- (void)setIndentedPaste:(BOOL)fp8; +- (void)toggleAutoIndent:(id)fp8; +- (void)toggleHardWrap:(id)fp8; +- (void)toggleIndentedPaste:(id)fp8; +- (BOOL)openFilesFolded; +- (void)toggleOpenFilesFolded:(id)fp8; +- (BOOL)toggleOpenFilesFoldedIsChecked:(id)fp8; +- (BOOL)canToggleOpenFilesFolded; +- (BOOL)showSoftWrapInGutter; +- (void)toggleShowSoftWrapInGutter:(id)fp8; +- (BOOL)toggleShowSoftWrapInGutterIsChecked:(id)fp8; +- (BOOL)showBookmarksInGutter; +- (void)toggleShowBookmarksInGutter:(id)fp8; +- (BOOL)toggleShowBookmarksInGutterIsChecked:(id)fp8; +- (void)takeTabSizeFrom:(id)fp8; +- (BOOL)takeTabSizeFromIsChecked:(id)fp8; +- (void)takeRightMarginFrom:(id)fp8; +- (void)insertNewline:(id)fp8; +- (void)setSoftTabs:(BOOL)fp8; +- (BOOL)softTabs; +- (BOOL)treatsSpacesAsTabs; +- (void)setSmartTyping:(BOOL)fp8; +- (BOOL)smartTyping; +- (void)toggleSmartTyping:(id)fp8; +- (void)setAntiAliasEnabled:(BOOL)fp8; +- (BOOL)antiAliasEnabled; +- (void)toggleAntiAliasEnabled:(id)fp8; +- (void)setLineNumbers:(BOOL)fp8; +- (BOOL)lineNumbers; +- (void)toggleLineNumbers:(id)fp8; +- (void)insertTab:(id)fp8; +- (void)goToLineNumber:(id)fp8; +- (void)goToColumnNumber:(id)fp8; +- (void)selectToLine:(id)fp8 andColumn:(id)fp12; +- (void)setFoldingsEnabled:(BOOL)fp8; +- (BOOL)foldingsEnabled; +- (void)toggleFoldingsEnabled:(id)fp8; +- (id)toggleFoldingMenuTitle; +- (BOOL)canToggleFolding; +- (BOOL)canFoldAllAtLevel; +- (BOOL)canUnfoldAllAtLevel; +- (void)foldAllAtLevel:(id)fp8; +- (void)foldSelection:(id)fp8; +- (void)toggleFolding:(id)fp8; +- (BOOL)toggleFreehandedEditIsChecked:(id)fp8; +- (BOOL)toggleOverwriteModeIsChecked:(id)fp8; +- (BOOL)toggleSoftWrapIsChecked:(id)fp8; +- (BOOL)toggleTreatsSpacesAsTabsIsChecked:(id)fp8; +- (BOOL)toggleSmartTypingIsChecked:(id)fp8; +- (BOOL)toggleFoldingsEnabledIsChecked:(id)fp8; +- (BOOL)toggleHardWrapIsChecked:(id)fp8; +- (BOOL)toggleIndentedPasteIsChecked:(id)fp8; +- (BOOL)toggleLineNumbersIsChecked:(id)fp8; +- (BOOL)toggleAntiAliasEnabledIsChecked:(id)fp8; +- (void)selectBlock:(id)fp8; +- (BOOL)canNextCompletion; +- (BOOL)canPreviousCompletion; +@end + +@interface OakTextView (ScopedSettings) +- (void)setScopedValue:(id)fp8 forKey:(id)fp12 inDomain:(id)fp16; +- (id)scopedValueForKey:(id)fp8 inDomain:(id)fp12; +@end + +@interface OakTextView (FoldingTooltip) +- (void)viewDidMoveToWindow; +- (void)showFoldedText:(id)fp8; +- (BOOL)abortShowingFoldedText:(id)fp8; +- (void)mouseMoved:(id)fp8; +- (void)orderFrontWebPreview:(id)fp8; +@end + +@interface OakISearchWindow : NSPanel +{ + OakTextView *textView; + NSTextField *textField; + BOOL reverseSearch; +} + +- (id)initWithContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24 backing:(int)fp28 defer:(BOOL)fp32 screen:(id)fp36; +- (void)dealloc; +- (void)setTextView:(id)fp8; +- (BOOL)canBecomeKeyWindow; +- (void)cleanupAndClose:(id)fp8; +- (void)sendEvent:(id)fp8; +- (id)incrementalSearchString; +- (void)setIncrementalSearchString:(id)fp8; + +@end + +@interface OakTextView (ISearch) +- (id)incrementalSearchWindow; +- (void)ISIM_incrementalSearch:(id)fp8; +- (void)ISIM_reverseIncrementalSearch:(id)fp8; +- (BOOL)findNextIncrementalSearchString:(BOOL)fp8; +- (BOOL)findPreviousIncrementalSearchString:(BOOL)fp8; +@end + +@interface OakTextView (OakTextViewPageUpDown) +- (void)pageUp:(id)fp8; +- (void)pageDown:(id)fp8; +- (void)pageUpAndModifySelection:(id)fp8; +- (void)pageDownAndModifySelection:(id)fp8; +@end + +@interface OakTextViewPrinting : NSView +{ + OakTextView *textView; + NSMatrix *paperOrnaments; + unsigned int linesPerPage; + unsigned int numberOfPages; + struct vector<std::vector<text::char_t, std::allocator<text::char_t>>, std::allocator<std::vector<text::char_t, std::allocator<text::char_t>>>> *lines; + struct ATSUI_render *render; +} + +- (id)initWithTextView:(id)fp8; +- (void)dealloc; +- (id)printJobTitle; +- (BOOL)knowsPageRange:(struct _NSRange *)fp8; +- (void)beginPageInRect:(struct _NSRect)fp8 atPlacement:(struct _NSPoint)fp24; +- (void)drawPageBorderWithSize:(struct _NSSize)fp8; +- (void)drawRect:(struct _NSRect)fp8; +- (BOOL)isFlipped; +- (struct _NSRect)rectForPage:(int)fp8; +- (float)calculatePrintWidth; +- (float)calculatePrintHeight; + +@end + +@interface OakTextView (OakTextViewPrinting) +- (void)printOperationDidRun:(id)fp8 success:(BOOL)fp12 contextInfo:(id)fp16; +- (void)printDocument:(id)fp8; +@end + +@interface OakTextView (SpellChecking) +- (void)ignoreSpelling:(id)fp8; +- (void)contextMenuIgnoreSpelling:(id)fp8; +- (void)contextMenuLearnSpelling:(id)fp8; +- (void)checkSpelling:(id)fp8; +- (void)showGuessPanel:(id)fp8; +- (void)correctWord:(id)fp8; +- (void)selectMisspelledWordAt:; +- (id)contextMenu; +- (id)menuForEvent:(id)fp8; +- (void)showContextMenu:(id)fp8; +@end + +@interface OakSymbolChooser : OakTableViewController +{ + NSSearchField *filterStringTextField; + NSArrayController *arrayController; + NSArray *displaySymbols; + NSArray *symbols; +} + ++ (id)sharedInstance; +- (id)init; +- (void)functionPopUpDidChange:(id)fp8; +- (void)currentFunctionDidChange:(id)fp8; +- (void)search:(id)fp8; +- (void)accept:(id)fp8; +- (void)cancel:(id)fp8; +- (void)windowDidLoad; +- (void)selectFromList:(id)fp8 withSelection:(id)fp12; + +@end + +@interface OakTextView (StyleSheet) ++ (void)load; +- (void)goToSymbol:(id)fp8; +- (id)currentStyleSheet; +- (void)themeDidChange:(id)fp8; +- (void)setCurrentStyleSheet:(id)fp8; +- (id)scopeForContext:; +- (id)stylesForContext:; +- // Error parsing type: 12@0:48, name: graphPathForIterator: +- // Error parsing type: 12@0:4c8, name: graphPathForCaretWait: +- (id)currentContext; +- (id)currentContext:(id)fp8; +- (id)stylesForCaretWait:(BOOL)fp8; +- (id)stylesForCaret; +- (void)resetDisplay:(id)fp8; +- (id)languageForUUID:(id)fp8; +- (id)languageChoiceForFile:(id)fp8 withFirstLine:(id)fp12; +- (id)languageChoiceForCurrentFile; +- (id)suggestedExtensionForDocument; +- (BOOL)storedSoftWrapSetting; +- (int)storedTabSizeSetting; +- (BOOL)storedSoftTabsSetting; +- (BOOL)storedContinuousSpellCheckingSetting; +- (void)initializeSettings; +- (void)learnFileAssociation:(id)fp8; +- (void)changeLanguageTo:(id)fp8 andLearn:(BOOL)fp12; +- (void)changeLanguageToAndLearn:(id)fp8; +- (void)languagesDidChange:(id)fp8; +- (void)preferencesDidChange:(id)fp8; +- (void)setCurrentSymbol:(id)fp8; +- (void)buildFunctionPopUp; +- (id)functionPopUp; +- (void)delayedUpdateFunctionPopUp:(id)fp8; +- (void)updateFunctionPopUp:(BOOL)fp8; +@end + +@interface NSArray (OakArray2) +- (id)arrayByRemovingObject:(id)fp8; +@end + +@interface OakThemeManager : NSObject +{ + NSMutableArray *settingsFiles; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (id)init; +- (id)allThemes; +- (id)currentTheme:(id)fp8; + +@end + +@interface OakTipOfTheDay : NSObject +{ + NSWindow *window; + NSArray *allTips; + NSString *tipOfTheDay; + BOOL hasPreviousTip; + BOOL hasNextTip; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (id)init; +- (void)applicationDidFinishLaunching:(id)fp8; +- (void)setup; +- (void)orderFrontTipOfTheDay:(id)fp8; +- (void)showPreviousTip:(id)fp8; +- (void)showNextTip:(id)fp8; + +@end + +@interface OakTooltipWindow : NSWindow +{ + NSTextField *field; + NSTimer *animationTimer; + NSDate *animationStart; + NSDate *didOpenAtDate; + struct _NSPoint mousePositionWhenOpened; + BOOL enforceMouseThreshold; +} + ++ (void)initialize; +- (id)initWithScreen:(id)fp8; +- (void)stopAnimation:(id)fp8; +- (void)dealloc; +- (void)setFont:(id)fp8; +- (void)setStringValue:(id)fp8; +- (void)showAtLocation:(struct _NSPoint)fp8 forScreen:(id)fp16; +- (void)setEnforceMouseThreshold:(BOOL)fp8; +- (BOOL)shouldCloseForMousePosition:(struct _NSPoint)fp8; +- (void)animationTick:(id)fp8; +- (void)orderOut:(id)fp8; + +@end + +@interface OakWebPreviewManager : NSResponder +{ + NSWindow *webPreviewWindow; + WebView *webView; + NSTimer *automaticRefreshTimer; + BOOL filterText; + BOOL automaticRefresh; + NSString *filterTextCommand; + float automaticRefreshDelay; + NSString *baseURL; + id delegate; + BOOL pendingRefresh; + struct _NSRect pendingVisibleRect; + NSNib *webPreviewNib; + NSArray *topLevelNibObjects; +} + ++ (void)initialize; +- (id)init; +- (void)dealloc; +- (void)orderFrontWebPreview:(id)fp8; +- (void)progressFinishedNotification:(id)fp8; +- (void)setDelegate:(id)fp8; +- (void)setBaseURL:(id)fp8; +- (void)performRefresh:(id)fp8; +- (void)actualRefresh:(id)fp8; +- (void)goBack:(id)fp8; +- (void)goForward:(id)fp8; +- (void)reload:(id)fp8; +- (BOOL)performKeyEquivalent:(id)fp8; +- (void)webView:(id)fp8 didFinishLoadForFrame:(id)fp12; +- (void)scrollWebView:(id)fp8; +- (void)setAutomaticRefresh:(BOOL)fp8; +- (void)setFilterText:(BOOL)fp8; +- (void)setFilterTextCommand:(id)fp8; +- (void)resetRefreshTimer; +- (void)printDocument:(id)fp8; + +@end + +@interface OakWindow : NSWindow +{ +} + +- (BOOL)respondsToSelector:(SEL)fp8; + +@end + +@interface OakWordCharacters : NSObject +{ + NSString *wordCharacters; + struct set<unichar, std::less<unichar>, std::allocator<unichar>> *set; +} + ++ (id)sharedInstance; ++ (void)initialize; +- (BOOL)isWordCharacter:(unsigned short)fp8; +- (void)setup; +- (id)init; +- (void)userDefaultsDidChange:(id)fp8; + +@end + +@interface OakInternalProtocol : NSURLProtocol +{ + NSFileHandle *fileHandle; + NSString *key; +} + ++ (void)load; ++ (BOOL)canInitWithRequest:(id)fp8; ++ (id)canonicalRequestForRequest:(id)fp8; ++ (BOOL)requestIsCacheEquivalent:(id)fp8 toRequest:(id)fp12; +- (void)cleanup; +- (void)dealloc; +- (void)dataAvailable:(id)fp8; +- (void)startLoading; +- (void)stopLoading; + +@end + +@interface OakBorderlessPanel : NSPanel +{ +} + +- (id)initWithContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24 backing:(int)fp28 defer:(BOOL)fp32; +- (void)sendEvent:(id)fp8; +- (BOOL)canBecomeMainWindow; +- (BOOL)canBecomeKeyWindow; + +@end + +@interface OakCompletionManager : NSObject <OakKeyObserver> +{ + NSPanel *window; + NSTableView *tableView; + NSArray *methods; +} + ++ (id)sharedInstance; +- (id)init; +- (BOOL)shouldSwallowEvent:(id)fp8; +- (void)textDidChangeFor:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; + +@end + +@interface OakTextView (DictionaryInput) +- (id)accessibilityHitTest:(struct _NSPoint)fp8; +- (id)accessibilityAttributeNames; +- (id)accessibilityAttributeValue:(id)fp8; +- (id)accessibilityAttributeValue:(id)fp8 forParameter:(id)fp12; +@end + +@interface OakSelfUpdate : NSWindowController +{ + NSTextField *statusText; + NSProgressIndicator *progressBar; + NSButton *cancelButton; + NSButton *restartButton; + NSURLDownload *urlDownload; + BOOL inactive; + BOOL isDownloadAuthenticated; + NSString *archivePath; + NSData *archiveSignature; + unsigned int current; + unsigned int total; +} + ++ (void)restart; +- (void)dealloc; +- (void)setInfoText:(const char *)fp8; +- (void)showError:(id)fp8; +- (void)downloadDidBegin:(id)fp8; +- (void)download:(id)fp8 didReceiveResponse:(id)fp12; +- (void)download:(id)fp8 decideDestinationWithSuggestedFilename:(id)fp12; +- (void)download:(id)fp8 didReceiveDataOfLength:(unsigned int)fp12; +- (void)downloadDidFinish:(id)fp8; +- (void)download:(id)fp8 didFailWithError:(id)fp12; +- (void)showInstallAndRestartButton; +- (void)installAndRestart:(id)fp8; +- (void)cancel:(id)fp8; + +@end + +@interface OakCreateSymbolicLinkWizard : NSObject +{ + NSWindow *createSymbolicLinkWindow; + NSPopUpButton *destinationPopUp; + NSMutableArray *destinationPaths; + unsigned int selectedDestination; +} + ++ (id)sharedInstance; +- (BOOL)setupDestinationPaths; +- (id)init; +- (id)toolPath; +- (BOOL)alreadyHasLink; +- (BOOL)canCreateLink; +- (void)askUserAboutSymbolicLink; +- (void)showHelp:(id)fp8; +- (void)cancel:(id)fp8; +- (void)accept:(id)fp8; +- (void)destinationChanged:(id)fp8; +- (void)openPanelDidEnd:(id)fp8 returnCode:(int)fp12 contextInfo:(void *)fp16; + +@end + +@interface TMPlugInController : NSObject +{ + NSMutableArray *loadedPlugIns; + NSMutableSet *plugInBundleIdentifiers; + BOOL didLoadAllPlugIns; +} + ++ (id)sharedInstance; +- (id)init; +- (float)version; +- (void)loadPlugIn:(id)fp8; +- (id)installPath; +- (void)installPlugIn:(id)fp8; +- (void)loadAllPlugIns:(id)fp8; + +@end + +@interface TMPlugIn : NSObject +{ + NSBundle *plugInBundle; + id instance; +} + ++ (id)plugInWithPath:(id)fp8; +- (id)initWithPath:(id)fp8; +- (void)dealloc; +- (id)name; +- (id)bundleIdentifier; +- (id)instance; + +@end + +@interface OakSelectBundleItem : OakTableViewController +{ + NSSearchField *filterStringTextField; + NSTableColumn *bundleItemsTableColumn; + NSMenu *filterCriteriaMenu; + NSString *filterString; + NSString *scope; + NSArray *bundleItems; + BOOL isSearchingKeyEquivalents; +} + +- (void)windowDidLoad; +- (void)setSearchCriterion:(id)fp8; +- (id)shouldInterceptKeyEquvalent:(id)fp8; +- (void)showKeyEquivalent:(id)fp8 withResults:(id)fp12; +- (BOOL)validateMenuItem:(id)fp8; +- (void)refresh; +- (void)search:(id)fp8; +- (void)setScope:(id)fp8; +- (void)accept:(id)fp8; +- (void)cancel:(id)fp8; +- (int)numberOfRowsInTableView:(id)fp8; +- (void)tableView:(id)fp8 willDisplayCell:(id)fp12 forTableColumn:(id)fp16 row:(int)fp20; +- (id)tableView:(id)fp8 objectValueForTableColumn:(id)fp12 row:(int)fp16; + +@end + +@interface BundleManager : NSObject <OakKeyObserver> +{ + NSMutableDictionary *bundles; + NSMutableDictionary *bundleItems; + NSMutableArray *languages; + BOOL isModified; + NSMutableArray *bundleItemsStack; + NSMutableDictionary *bundleItemsOfKind; + OakSelectBundleItem *selectBundleItemController; +} + ++ (id)sharedInstance; +- (id)init; +- (void)dealloc; +- (void)setModified:(BOOL)fp8; +- (void)saveChanges:(id)fp8; +- (id)bundleNamesAtPath:(id)fp8; +- (void)loadBundles; +- (id)bundlesOnDiskExcluding:(id)fp8; +- (id)allBundlesOnDisk; +- (void)reloadBundles; +- (void)addBundle:(id)fp8; +- (void)addBundleItem:(id)fp8; +- (void)removeBundle:(id)fp8; +- (void)removeBundleItem:(id)fp8; +- (id)bundleForUUID:(id)fp8; +- (id)bundleItemForUUID:(id)fp8; +- (id)bundles; +- (id)bundleItems; +- (id)languages; +- (id)bundleItemsOfKind:(id)fp8; +- (id)bundleItemsOfKinds:(id)fp8; +- (id)bundlesWithItemsOfKind:(id)fp8; +- (id)bundlesWithItemsOfKinds:(id)fp8; +- (id)filterItems:(id)fp8 usingString:(id)fp12; +- (id)filterItems:(id)fp8 inScope:(id)fp12; +- (id)sortItems:(id)fp8 accordingToScope:(id)fp12; +- (id)bundleItemsForKeyString:(id)fp8; +- (id)bundleItemsForKeyString:(id)fp8 inScope:(id)fp12; +- (id)bundleItemsForTabTrigger:(id)fp8 inScope:(id)fp12; +- (id)bundleItemsForMouseGesture:(id)fp8 inScope:(id)fp12; +- (id)bundleItemsForFileDrop:(id)fp8 inScope:(id)fp12; +- (id)defaultBundle; +- (void)setDefaultBundle:(id)fp8; +- (BOOL)canExecuteItem:(id)fp8; +- (id)currentBundleItem; +- (void)pushBundleItem:(id)fp8; +- (void)popBundleItem; +- (void)executeItem:(id)fp8; +- (id)showMenuForBundleItems:(id)fp8 usingTextView:(id)fp12; +- (id)showMenuForBundleItems:(id)fp8 usingTextView:(id)fp12 atLocation:(struct _NSPoint)fp16; +- (BOOL)shouldSwallowEvent:(id)fp8; +- (void)selectBundleItemFromList:(id)fp8; +- (BOOL)installBundle:(id)fp8; +- (BOOL)installBundleItem:(id)fp8 ofKind:(id)fp12; +- (BOOL)canHandleFile:(id)fp8; + +@end + +@interface TemplateFile : NSObject +{ + NSString *name; + NSString *path; + NSString *bundleItemUUID; + BOOL isModified; + NSString *content; +} + ++ (id)templateFileWithBundleItemUUID:(id)fp8; ++ (id)templateFileWithPath:(id)fp8 andBundleItemUUID:(id)fp12; +- (id)initWithBundleItemUUID:(id)fp8; +- (id)initWithPath:(id)fp8 andBundleItemUUID:(id)fp12; +- (void)dealloc; +- (int)caseInsensitiveCompare:(id)fp8; +- (id)createDuplicate; +- (BOOL)isModified; +- (id)name; +- (id)kind; +- (id)bundleItemUUID; +- (id)bundleItem; +- (id)content; +- (void)setModified:(BOOL)fp8; +- (void)setName:(id)fp8; +- (void)setContent:(id)fp8; +- (id)writeToDirectory:(id)fp8; +- (void)removeTemplateFile; + +@end + +@interface BundleItem : BaseItem +{ + NSString *scopeSelector; + struct basic_string<char, std::char_traits<char>, std::allocator<char>> *scopeSelectorCString; + NSString *keyEquivalent; + NSString *tabTrigger; + NSString *mouseGesture; + NSArray *draggedFileExtensions; + NSString *bundleUUID; + NSMutableArray *sourcePaths; + NSString *pristineCopyPlistPath; + NSMutableDictionary *content; + NSMutableArray *templateFiles; +} + ++ (id)bundleItemWithContent:(id)fp8 andKind:(id)fp12; ++ (id)bundleWithContent:(id)fp8 kind:(id)fp12 bundleUUID:(id)fp16 sourcePaths:(id)fp20; +- (id)initWithContent:(id)fp8 andKind:(id)fp12; +- (id)initWithContent:(id)fp8 kind:(id)fp12 bundleUUID:(id)fp16 sourcePaths:(id)fp20; +- (void)dealloc; +- (void)prepareForSaving; +- (id)createDuplicate; +- (id)writeToDirectory:(id)fp8; +- (id)bundleUUID; +- (id)bundle; +- (id)sourcePath; +- (id)sourcePaths; +- (id)localPath; +- (id)bundlePath; +- (id)scopeSelector; +- (id)keyEquivalent; +- (id)tabTrigger; +- (id)mouseGesture; +- (id)draggedFileExtensions; +- (void)setScopeSelector:(id)fp8; +- // Error parsing type: 8@0:4, name: scopeSelectorCString +- (void)setKeyEquivalent:(id)fp8; +- (void)setTabTrigger:(id)fp8; +- (void)setMouseGesture:(id)fp8; +- (void)setDraggedFileExtensions:(id)fp8; +- (void)setContentValue:(id)fp8 forKey:(id)fp12; +- (void)setBundle:(id)fp8; +- (id)content; +- (void)saveChanges; +- (id)supportPath; +- (id)titleWithSelection:(BOOL)fp8 showTabTrigger:(BOOL)fp12; +- (id)titleWithSelection:(BOOL)fp8; +- (void)setKeyEquivalentForMenuItemIndex:(unsigned short)fp8 inMenu:(struct OpaqueMenuRef *)fp12; +- (id)templateFiles; +- (id)newTemplateFile; +- (void)removeTemplateFile:(id)fp8; + +@end + +@interface Bundle : BaseItem +{ + NSMutableDictionary *mainMenu; + NSMutableArray *bundlePaths; + NSString *pristineCopyPlistPath; + NSMutableDictionary *content; +} + ++ (id)bundleWithName:(id)fp8; ++ (id)bundleWithPaths:(id)fp8; +- (id)initWithName:(id)fp8; +- (id)initWithPaths:(id)fp8; +- (void)dealloc; +- (void)prepareForSaving; +- (void)saveChanges; +- (id)supportPath; +- (id)writeToDirectory:(id)fp8; +- (id)localPath; +- (void)filterArray:(id)fp8 allowingItems:(id)fp12 groups:(id)fp16; +- (id)menuStructure; +- (void)setMenuStructure:(id)fp8; +- (void)populateArray:(id)fp8 withItems:(id)fp12; +- (void)addItem:(id)fp8 toArray:(id)fp12; +- (id)flatMenu; +- (id)bundleItemInstallPath; +- (id)bundleItemsOnDisk; +- (id)bundlePaths; +- (id)ordering; +- (id)disabled; +- (id)deleted; +- (void)removeBundleItem:(id)fp8; +- (void)registerBundleItem:(id)fp8; +- (void)enableUUID:(id)fp8; +- (void)undeleteUUID:(id)fp8; +- (id)bundleItems; +- (void)place:(id)fp8 after:(id)fp12; +- (id)bundleItemsOfKind:(id)fp8; + +@end + +@interface BaseItem : NSObject +{ + NSString *name; + NSString *kind; + NSString *UUID; + BOOL isModified; +} + +- (id)initWithName:(id)fp8 kind:(id)fp12 UUID:(id)fp16; +- (id)init; +- (id)initWithCoder:(id)fp8; +- (void)encodeWithCoder:(id)fp8; +- (void)dealloc; +- (id)description; +- (BOOL)isEqual:(id)fp8; +- (int)compare:(id)fp8; +- (int)caseInsensitiveCompare:(id)fp8; +- (id)name; +- (id)kind; +- (id)UUID; +- (BOOL)isModified; +- (void)setName:(id)fp8; +- (void)setModified:(BOOL)fp8; +- (id)writeToDirectory:(id)fp8; +- (void)saveChanges; + +@end + +@interface BundleItemStub : NSObject +{ + NSString *path; + NSDictionary *contents; +} + ++ (id)bundleItemStubWithPath:(id)fp8; +- (id)initWithPath:(id)fp8; +- (id)initWithCoder:(id)fp8; +- (void)dealloc; +- (void)encodeWithCoder:(id)fp8; +- (id)UUID; +- (id)path; +- (id)contents; +- (id)description; + +@end + +@interface BundleStub : NSObject +{ + NSString *UUID; + NSString *path; +} + ++ (id)bundleStubWithPath:(id)fp8; +- (id)initWithPath:(id)fp8; +- (id)initWithCoder:(id)fp8; +- (void)dealloc; +- (void)encodeWithCoder:(id)fp8; +- (id)UUID; +- (id)path; +- (id)description; + +@end + +@interface OakBundleMenuManager : NSObject +{ + OakBundleMenuHelper *bundleMenuHelper; + OakTemplateMenuHelper *templateMenuHelper; +} + ++ (id)sharedInstance; +- (id)init; +- (unsigned int)addBundleItems:(id)fp8 toMenu:(id)fp12 withDelegate:(id)fp16 andReturnIndexOf:(id)fp20; +- (unsigned int)populateMenuWithBundles:(id)fp8 andReturnIndexOf:(id)fp12; +- (void)editCommands:(id)fp8; +- (void)editMacros:(id)fp8; +- (void)editSnippets:(id)fp8; +- (void)editLanguages:(id)fp8; +- (void)editTemplates:(id)fp8; +- (void)reloadBundlesIgnoringCache:(id)fp8; +- (void)reloadBundles:(id)fp8; +- (void)orderFrontBundleEditor:(id)fp8; +- (void)selectBundleItemFromList:(id)fp8; +- (void)menuNeedsUpdate:(id)fp8; +- (BOOL)menuHasKeyEquivalent:(id)fp8 forEvent:(id)fp12 target:(id *)fp16 action:(SEL *)fp20; + +@end + +@interface OakTemplateMenuHelper : OakMenuHelperBase +{ +} + +- (void)menuNeedsUpdate:(id)fp8; + +@end + +@interface OakBundleMenuHelper : OakMenuHelperBase +{ + short fontID; + unsigned short fontSize; + BOOL hasSelection; +} + +- (void)addItem:(id)fp8 toMenu:(id)fp12 usingGroups:(id)fp16; +- (void)populateMenu:(id)fp8 withItems:(id)fp12 usingGroups:(id)fp16; +- (void)menuNeedsUpdate:(id)fp8; + +@end + +@interface OakMenuHelperBase : NSObject +{ + NSMutableArray *menus; + NSMutableArray *tabTriggers; +} + +- (id)init; +- (void)cleanMenu:(id)fp8; +- (void)dummy:(id)fp8; +- (void)menuDidClose:(id)fp8; +- (id)addBundleItem:(id)fp8 withSelection:(BOOL)fp12 toMenu:(id)fp16; +- (void)performMenuChoice:(id)fp8; +- (BOOL)menuHasKeyEquivalent:(id)fp8 forEvent:(id)fp12 target:(id *)fp16 action:(SEL *)fp20; + +@end + +@interface BackgroundReader : NSObject +{ + int fd; + BOOL doneReading; + BOOL isShowingBusyCursor; + NSString *result; + NSWindow *window; +} + +- (BOOL)isAbortEvent:(id)fp8; +- (void)terminateProcess:(int)fp8; +- (id)initWithFileDescriptor:(int)fp8 processID:(int)fp12 forWindow:(id)fp16; +- (void)dealloc; +- (void)bringUpProgressBar:(id)fp8; +- (id)result; +- (void)readInBackground:(id)fp8; +- (void)didReadString:(id)fp8; + +@end + +@interface NSObject (RunCommand) +- (id)allEnvironmentVariables; +- (id)executeShellCommand:(id)fp8; +- (id)executeShellCommand:(id)fp8 variables:(id)fp12; +- (id)executeShellCommand:(id)fp8 input:(id)fp12; +- (id)executeShellCommand:(id)fp8 input:(id)fp12 variables:(id)fp16; +- (id)executeShellCommand:(id)fp8 input:(id)fp12 variables:(id)fp16 returnCode:(int *)fp20; +- (void)writeInBackground:(id)fp8; +- (id)runCommand:(id)fp8 input:(id)fp12 variables:(id)fp16 returnCode:(int *)fp20 async:(BOOL)fp24; +- (id)executeShellCommand:(id)fp8 input:(id)fp12 variables:(id)fp16 returnCode:(int *)fp20 async:(BOOL)fp24; +@end + +@interface CacheManager : NSObject +{ + NSMutableDictionary *pathContents; + NSMutableDictionary *pathLastChanged; + NSMutableSet *didAccess; + BOOL isModified; +} + ++ (id)sharedInstance; ++ (id)lastDirectoryUpdateForPath:(id)fp8; +- (id)init; +- (void)applicationWillTerminate:(id)fp8; +- (void)dealloc; +- (id)contentsForPath:(id)fp8; +- (void)setContents:(id)fp8 forPath:(id)fp12; +- (void)invalidateCacheForPath:(id)fp8; +- (id)cacheFile; +- (id)cacheFormatVersion; +- (void)loadCache; +- (void)saveCache; +- (void)flush; + +@end + +@interface OakMenuItemCell : NSTextFieldCell +{ + NSString *keyEquivalent; + NSString *tabTrigger; +} + +- (void)dealloc; +- (id)copyWithZone:(struct _NSZone *)fp8; +- (id)keyEquivalent; +- (id)tabTrigger; +- (void)setKeyEquivalent:(id)fp8; +- (void)setTabTrigger:(id)fp8; +- (void)editWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 event:(id)fp36; +- (void)selectWithFrame:(struct _NSRect)fp8 inView:(id)fp24 editor:(id)fp28 delegate:(id)fp32 start:(int)fp36 length:(int)fp40; +- (void)drawWithFrame:(struct _NSRect)fp8 inView:(id)fp24; +- (struct _NSSize)cellSize; + +@end +
orbitz/glitter
598afe0cc431ac6fca93e065e4369179fd37aebb
Adding third order markov model (doesn't work) and updated to use the org bounding technique (appears to have no effect)
diff --git a/bin/make.sh b/bin/make.sh index 2173329..2ff93f1 100755 --- a/bin/make.sh +++ b/bin/make.sh @@ -1,27 +1,27 @@ #!/bin/sh -OCAMLC="ocamlc" +OCAMLC="ocamlopt" if [ $OCAMLC = "ocamlc" ] then SUFFIX=cmo LIB_SUFFIX=cma else SUFFIX=cmx LIB_SUFFIX=cmxa fi -BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX orf_bounding.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" mkdir -p ../output for i in *.ml; do $OCAMLC -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done -# $OCAMLC -g -o ../output/gb_to_genelist $BASE_OBJECTS gb_to_genelist.$SUFFIX +$OCAMLC -g -o ../output/gb_to_genelist $BASE_OBJECTS gb_to_genelist.$SUFFIX -# $OCAMLC -g -o ../output/glitter_2 $BASE_OBJECTS glitter_2.$SUFFIX -# $OCAMLC -g -o ../output/glitter_4 $BASE_OBJECTS glitter_4.$SUFFIX -# $OCAMLC -g -o ../output/glitter_7 $BASE_OBJECTS glitter_7.$SUFFIX -# $OCAMLC -g -o ../output/glitter_10 $BASE_OBJECTS glitter_10.$SUFFIX -# $OCAMLC -g -o ../output/glitter_3_4 $BASE_OBJECTS glitter_3_4.$SUFFIX +$OCAMLC -g -o ../output/glitter_2 $BASE_OBJECTS glitter_2.$SUFFIX +$OCAMLC -g -o ../output/glitter_4 $BASE_OBJECTS glitter_4.$SUFFIX +$OCAMLC -g -o ../output/glitter_7 $BASE_OBJECTS glitter_7.$SUFFIX +$OCAMLC -g -o ../output/glitter_10 $BASE_OBJECTS glitter_10.$SUFFIX +$OCAMLC -g -o ../output/glitter_3_4 $BASE_OBJECTS glitter_3_4.$SUFFIX diff --git a/bin/run.sh b/bin/run.sh index 1ff4599..2161984 100755 --- a/bin/run.sh +++ b/bin/run.sh @@ -1,8 +1,8 @@ #!/bin/sh SUFFIX=cmo LIB_SUFFIX=cma -BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX orf_bounding.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" ocaml $BASE_OBJECTS diff --git a/lib/gene_prediction_10.ml b/lib/gene_prediction_10.ml index 72d4721..d0f4d9f 100644 --- a/lib/gene_prediction_10.ml +++ b/lib/gene_prediction_10.ml @@ -1,67 +1,72 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | Start1 | Start2 | Start3 | C1 | C2 | C3 | Stop1 | Stop2 | Stop3 -module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct + type s = coding_state + type a = char + let scompare = compare + let acompare = compare + end) let to_stream l = Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l) let rec label_start d fin = if String_ext.length d >= 3 then match Hmm.labeled_of_string [Start1; Start2; Start3] d with Some (l, d') -> (to_stream l, d') | _ -> raise (Failure "Labeling start condons failed") else match Seq.next fin with Some (Gene_prediction_2.Gene, d') -> label_start (d ^ d') fin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "Looking for start codon but got NotGene") | Some (Gene_prediction_2.Q0, _) | None -> raise (Failure "Looking for start codon but got EOF") let rec consume_notgenes f fin = match Seq.next fin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); consume_notgenes f fin>] | Some (Gene_prediction_2.Gene, d) -> let (l, d') = label_start d fin in [< l; f d' fin >] | Some (Gene_prediction_2.Q0, _) | None -> [< >] let label_codons d fin = let (l, d') = Hmm.labeled_of_string_all [C1; C2; C3] d in (to_stream l, d') let rec consume_gene d fin = let dl = String_ext.length d in if dl > 6 then let start = String_ext.sub d 0 (dl - 3) in let last_3 = String_ext.sub d (dl - 3) 3 in let (l, d') = label_codons start fin in [< l; consume_gene (d' ^ last_3) fin >] else match Seq.next fin with Some (Gene_prediction_2.NotGene, d') when dl = 3 -> let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in [< to_stream l; '(NotGene, d'); consume_notgenes consume_gene fin >] | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "This should never happen") | Some (Gene_prediction_2.Q0, _) | None -> let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in [< to_stream l >] | Some (Gene_prediction_2.Gene, d') -> consume_gene (d ^ d') fin let create_training_data gene_boundaries fin = let sin = Gene_prediction_2.create_training_data gene_boundaries fin in consume_notgenes consume_gene sin let predict training_fname fasta_fname = Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene Start1 diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index 1505789..90a3c7d 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,133 +1,138 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene -module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct + type s = coding_state + type a = char + let scompare = compare + let acompare = compare + end) let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> Some ((oe, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> (* If there are no gene boundaries left, all of the remaining values aren't genes *) [< '(NotGene, d); read_next (ctd []) e >] | (gs, ge)::_gbs when gs <= s && ge >= e -> (* If the gene spands all of the range we have, return the gene *) [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::gbs when gs <= s && ge < e -> (* If the gene starts at s or before s it means we are currently inside the gene. If the gene ends before the ending here we pull out the beginning and return that as a gene and recurse weith the rest *) let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, _ge)::_gbs when e < gs -> (* If teh start of the next gene is after the end of this, return as not a gene *) [< '(NotGene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when s <= gs && gs <= e -> (* If the gene boundaries is in side the boundary that we currently have, return the first as NotGene and recursively call the next piece *) let subd = String_ext.sub d 0 (gs - s) in let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in read_next (ctd gene_boundaries) 0 (* * We verify that the training data looks like we expect it. In this case, * the length of genes are a multiple of 3 and start with a start codon and * end with stop codon *) let verify_training_data td = let match_start_codon s = List.mem s ["ATG"; "GTG"; "TTG"] in let match_stop_codon s = List.mem s ["TAA"; "TAG"; "TGA"] in let verify_gene start_pos gene = let start_codon = String_ext.sub gene 0 3 in let stop_codon = String_ext.sub gene (String_ext.length gene - 3) 3 in if match_start_codon start_codon && match_stop_codon stop_codon && String_ext.length gene mod 3 = 0 then () else Printf.printf "Unknown codons, start_pos: %d start: %s stop: %s length: %d sequence \"%s\"" start_pos start_codon stop_codon (String_ext.length gene) gene in let rec vtd count acc = let sl = String_ext.length in match Seq.next td with Some (NotGene, d) -> if acc <> "" then begin verify_gene (1 + count - sl acc) acc; vtd (count + sl d) "" end else vtd (count + sl d) "" | Some (Gene, d) -> vtd (count + sl d) (acc ^ d) | Some (Q0, d) -> vtd (count + sl d) "" | None -> () in vtd 0 "" (* * We work in strings for some of this stuff for ease of use but viterbi wants a list * of states. this is a simple wrapper to make our training data that on the fly *) let map_td_to_list f gb fasta = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (f gb fasta) let predict training_fname fasta_fname = Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (map_td_to_list create_training_data) Misc_lib.identity NotGene Gene diff --git a/lib/gene_prediction_3_4.ml b/lib/gene_prediction_3_4.ml index 53c4911..a358027 100644 --- a/lib/gene_prediction_3_4.ml +++ b/lib/gene_prediction_3_4.ml @@ -1,76 +1,89 @@ (* A 3rd order HMM with 4 states *) type coding_state = Q0 | NotGene | Start | Codon | Stop -module H = Hmm.Make(struct type s = coding_state type a = string let compare = compare end) +module H = Hmm.Make(struct + type s = coding_state + type a = string + let scompare = compare + let acompare = compare + end) let join (c1, c2, c3) = String_ext.concat "" (List.map snd [c1; c2; c3]) let consume_next f (c1, c2, c3) sin = match Seq.next sin with Some c4 -> f (c2, c3, c4) sin | None -> [< >] let rec consume_intragene cont ((c1, _, _) as cs) sin = let joined = join cs in match fst c1 with Gene_prediction_10.Start2 | Gene_prediction_10.Start3 | Gene_prediction_10.C1 | Gene_prediction_10.C2 | Gene_prediction_10.C3 -> [< '(Codon, joined); consume_next (consume_intragene cont) cs sin >] | Gene_prediction_10.Stop1 -> [< '(Stop, joined); consume_next cont cs sin >] | _ -> raise (Failure "Not sure what I got in intragene...") let rec consume_notgene ((c1, _, _) as cs) sin = match fst c1 with Gene_prediction_10.NotGene | Gene_prediction_10.Stop2 | Gene_prediction_10.Stop3 -> let joined = join cs in [< '(NotGene, joined); consume_next consume_notgene cs sin >] | Gene_prediction_10.Start1 -> let joined = join cs in [< '(Start, joined); consume_next (consume_intragene consume_notgene) cs sin >] | _ -> raise (Failure "Waiting for NotGene | Start1 | Start2, dunno what I got...") let create_training_data gene_boundaries fin = - let sin = Gene_prediction_10.create_training_data gene_boundaries fin in + let rec make_single sin = + match Seq.next sin with + Some (l, v) when String_ext.length v > 1 -> + let string_seq = Seq.map (fun c -> (l, String_ext.make 1 c)) (Seq.of_string v) in + [< string_seq; make_single sin >] + | Some (l, v) -> + [< '(l, v); make_single sin >] + | None -> + [< >] + in + let sin = make_single (Gene_prediction_10.create_training_data gene_boundaries fin) in match Seq.take 3 sin with [c1; c2; c3] -> consume_notgene (c1, c2, c3) sin | _ -> raise (Failure "Expecting at least 3 values") let map_td_to_list f gb fasta = Seq.map (fun (s, v) -> (s, [v])) (f gb fasta) let convert fin = let rec f = function [] -> raise (Failure "An empty entry in convert should never happen") | x::xs as xss -> begin let str = String_ext.concat "" (List.map (String_ext.make 1) xss) in match Seq.next fin with Some v -> [< 'str; f (xs @ [v]) >] | None -> [< 'str >] end in f (Seq.take 3 fin) let predict training_fname fasta_fname = Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (map_td_to_list create_training_data) convert NotGene Start - - diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml index 51239a9..cfb5a9a 100644 --- a/lib/gene_prediction_4.ml +++ b/lib/gene_prediction_4.ml @@ -1,50 +1,55 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | C1 | C2 | C3 -module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct + type s = coding_state + type a = char + let scompare = compare + let acompare = compare + end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = split_gene d in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin let predict training_fname fasta_fname = Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene C1 diff --git a/lib/gene_prediction_7.ml b/lib/gene_prediction_7.ml index 62c5039..2dd91fe 100644 --- a/lib/gene_prediction_7.ml +++ b/lib/gene_prediction_7.ml @@ -1,63 +1,68 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | A | T | G | C1 | C2 | C3 -module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct + type s = coding_state + type a = char + let scompare = compare + let acompare = compare + end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let rec gene_start d sin = if String_ext.length d < 3 then match Seq.next sin with Some (Gene_prediction_2.Gene, d') -> gene_start (d ^ d') sin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "At start of gene and gene end, wuuut?") | _ -> raise (Failure "At start of gene and sequence end, wuuuut?") else let (l, d) = Hmm.labeled_of_string_all [A; T; G;] d in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = gene_start d sin in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin let predict training_fname fasta_fname = Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene A diff --git a/lib/gene_predictor.ml b/lib/gene_predictor.ml index 3ab6272..82c2446 100644 --- a/lib/gene_predictor.ml +++ b/lib/gene_predictor.ml @@ -1,31 +1,37 @@ (* * Functions for prediction genes *) -let min_gene_length = 500 +let min_gene_length = 100 let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) let predict training_fname fasta_fname start_end train viterbi create_training_data fasta_converter ng sg = let fasta = Fasta.read_file ~chunk_size:10000 fasta_fname in (* Limit out training data to those ORFs that are min_gene_length+ nt in length *) let gene_boundaries = List.filter (fun (s, e) -> e - s > min_gene_length) (Genbank.read training_fname) in let training_data = create_training_data gene_boundaries fasta in let hmm = train start_end training_data in let (total, path, prob) = viterbi (fasta_converter (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 fasta_fname))) hmm in let gene_list = List.map (fun (_, b) -> b) (List.filter (fun (s, _) -> s <> ng) (Misc_lib.boundaries (genes ng sg path))) in + let orf_bounds = Orf_bounding.create_orf_bounds Orf_bounding.common_start_codons Orf_bounding.common_stop_codons fasta_fname in + let new_gene_list = List.map (Orf_bounding.find_nearest_bound 1000 orf_bounds) gene_list in let count = List.length gene_list in let training_count = List.length gene_boundaries in - ((total, path, prob), hmm, gene_list, count, training_count) + ((total, path, prob), hmm, new_gene_list, count, training_count) let write_gene_list gene_list fout = List.iter (fun (s, e) -> Printf.fprintf fout "%d\t%d\n" s e) gene_list +let print_data fout ((total, path, prob), _hmm, gene_list, count, training_count) = + write_gene_list gene_list stdout; + Printf.fprintf stdout "Total: %f\n Probability: %f\n Count: %d\nTraining Count: %d\n" total prob count training_count; + Printf.fprintf stdout "Mean Length: %f\n" (List.fold_left (+.) 0.0 (List.map (fun (s, e) -> float (e - s)) gene_list) /. float count) diff --git a/lib/glitter_10.ml b/lib/glitter_10.ml index 9e32833..4c6114c 100644 --- a/lib/glitter_10.ml +++ b/lib/glitter_10.ml @@ -1,8 +1,6 @@ -let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_10.predict Sys.argv.(2) Sys.argv.(1) +let data = Gene_prediction_10.predict Sys.argv.(2) Sys.argv.(1) -let () = - Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; - Gene_predictor.write_gene_list gene_list stdout +let () = Gene_predictor.print_data stdout data diff --git a/lib/glitter_2.ml b/lib/glitter_2.ml index 368607f..b20d37f 100644 --- a/lib/glitter_2.ml +++ b/lib/glitter_2.ml @@ -1,8 +1,6 @@ -let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_2.predict Sys.argv.(2) Sys.argv.(1) +let data = Gene_prediction_2.predict Sys.argv.(2) Sys.argv.(1) -let () = - Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; - Gene_predictor.write_gene_list gene_list stdout +let () = Gene_predictor.print_data stdout data diff --git a/lib/glitter_3_4.ml b/lib/glitter_3_4.ml new file mode 100644 index 0000000..17a97fc --- /dev/null +++ b/lib/glitter_3_4.ml @@ -0,0 +1,6 @@ + +let data = Gene_prediction_3_4.predict Sys.argv.(2) Sys.argv.(1) + +let () = Gene_predictor.print_data stdout data + + diff --git a/lib/glitter_4.ml b/lib/glitter_4.ml index 8924e25..09c2db1 100644 --- a/lib/glitter_4.ml +++ b/lib/glitter_4.ml @@ -1,8 +1,6 @@ -let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_4.predict Sys.argv.(2) Sys.argv.(1) +let data = Gene_prediction_4.predict Sys.argv.(2) Sys.argv.(1) -let () = - Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; - Gene_predictor.write_gene_list gene_list stdout +let () = Gene_predictor.print_data stdout data diff --git a/lib/glitter_7.ml b/lib/glitter_7.ml index 20c4339..e90ccac 100644 --- a/lib/glitter_7.ml +++ b/lib/glitter_7.ml @@ -1,8 +1,6 @@ -let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) +let data = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) -let () = - Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; - Gene_predictor.write_gene_list gene_list stdout +let () = Gene_predictor.print_data stdout data diff --git a/lib/hmm.ml b/lib/hmm.ml index 9e8782a..3b753f6 100644 --- a/lib/hmm.ml +++ b/lib/hmm.ml @@ -1,282 +1,333 @@ (* * Tools to construct and HMM and perform calculations on it *) module type Hmm_type = sig type s type a - val compare: s -> s -> int + val scompare: s -> s -> int + val acompare: a -> a -> int end module Make = functor (Elt : Hmm_type) -> struct + type state = Elt.s type alphabet = Elt.a + + module StateMap = Map.Make(struct type t = state let compare = Elt.scompare end) + module EmissionMap = Map.Make(struct type t = alphabet let compare = Elt.acompare end) + type probability = float type transition = state * (state * probability) list + type transition_map = probability StateMap.t StateMap.t type emission = state * (alphabet * probability) list + type emission_map = probability EmissionMap.t StateMap.t + - module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) - type hmm_state = { transitions : transition list + ; transitions_map : transition_map ; emissions : emission list + ; emissions_map : emission_map ; start_end : state + ; states : state list } + + let list_of_statemap (m : 'v StateMap.t) = StateMap.fold (fun k v acc -> (k, v)::acc) m [] + let statemap_of_list : (StateMap.key * 'v) list -> 'v StateMap.t = List.fold_left (fun m (k, v) -> StateMap.add k v m) StateMap.empty + + let list_of_emissionmap (m : 'v EmissionMap.t) = EmissionMap.fold (fun k v acc -> (k, v)::acc) m [] + let emissionmap_of_list : (EmissionMap.key * 'v) list -> 'v EmissionMap.t = List.fold_left (fun m (k, v) -> EmissionMap.add k v m) EmissionMap.empty + (* misc function for calculating a random weight *) let random_by_weight l = let rec get_random a v = function [] -> raise (Failure "You didn't represent all your base....") | (s, x)::xs -> let a = a + int_of_float (x *. 1000.0) in if v <= a then s else get_random a v xs in get_random 0 (Random.int 1001) l (* a misc funciton to work on lists *) - let rec drop_while f = + let rec drop_until f = function [] -> [] | x::xs when f x -> x::xs - | _::xs -> drop_while f xs + | _::xs -> drop_until f xs let get_transitions hmm s = - List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) + StateMap.find s hmm.transitions_map let get_transition hmm s1 s2 = - List.assoc s2 (get_transitions hmm s1) + StateMap.find s2 (get_transitions hmm s1) let get_transition_def hmm s1 s2 def = try get_transition hmm s1 s2 with Not_found -> def let get_states_by_emission hmm e = List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) let get_emissions hmm s = - List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) + StateMap.find s hmm.emissions_map - let get_emission hmm s1 s2 = - List.assoc s2 (get_emissions hmm s1) + let get_emission hmm s1 obs = + EmissionMap.find obs (get_emissions hmm s1) - let get_emission_def hmm s1 s2 def = + let get_emission_def hmm s1 obs def = try - List.assoc s2 (get_emissions hmm s1) + get_emission hmm s1 obs with Not_found -> def let get_random_transition hmm s = - random_by_weight (get_transitions hmm s) + random_by_weight (list_of_statemap (get_transitions hmm s)) let get_random_emission hmm s = - random_by_weight (get_emissions hmm s) + random_by_weight (list_of_emissionmap (get_emissions hmm s)) let get_states hmm = - List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) + hmm.states + let make t e se = { transitions = t + ; transitions_map = + List.fold_left + (fun acc (s, e) -> + StateMap.add + s + (statemap_of_list (List.filter (fun (_, p) -> p > 0.0) e)) + acc) + StateMap.empty + t ; emissions = e + ; emissions_map = + List.fold_left + (fun acc (s, e) -> + StateMap.add + s + (emissionmap_of_list (List.filter (fun (_, p) -> p > 0.0) e)) acc) + StateMap.empty + e ; start_end = se + ; states = List.filter ((<>) se) (List.map fst t) } let sample_emission hmm = let rec samp acc s = let ns = get_random_transition hmm s in if ns = hmm.start_end then acc else samp ((get_random_emission hmm ns)::acc) ns in samp [] hmm.start_end let sample_emission_seq hmm = let rec samp s = let ns = get_random_transition hmm s in if ns = hmm.start_end then [< >] else let o = get_random_emission hmm ns in [< 'o; samp ns >] in samp hmm.start_end let prob_of_sequence hmm seq = let rec p_of_s s = function [] -> - snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) + snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (list_of_statemap (get_transitions hmm s)))) | x::xs -> let trans = get_transitions hmm s in let (ts, tp) = List.hd - (drop_while + (drop_until (fun s -> List.mem_assoc x - (get_emissions hmm (fst s))) - trans) + (list_of_emissionmap (get_emissions hmm (fst s)))) + (list_of_statemap trans)) in let ep = get_emission hmm ts x in tp *. ep *. p_of_s ts xs in p_of_s hmm.start_end seq (* * Calculates viterbi path + probabilities * returns (total probability, path, probability of path) *) let forward_viterbi obs hmm = let logsum x y = x +. log (1. +. exp (y -. x)) in let calc_max t ob ns (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let p = log (get_emission_def hmm s ob 0.0) +. log (get_transition_def hmm s ns 0.0) in let prob = prob +. p in let v_prob = v_prob +. p in (* This line might be a problem *) let total = if total = neg_infinity then prob else logsum total prob in if v_prob > valmax then (total, ns :: v_path, v_prob) else (total, argmax, valmax) in let accum_stats t ob u ns = let states = get_states hmm in StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u in let walk_states t ob = List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) in let walk_obs t = Seq.fold_left walk_states t obs in let make_t = List.fold_left (fun t s -> let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in StateMap.add s (start_p, [s], start_p) t) StateMap.empty (get_states hmm) in let find_max t (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let total = logsum total prob in if v_prob > valmax then (total, v_path, v_prob) else (total, argmax, valmax) in let t = walk_obs make_t in let states = get_states hmm in let (total, v_path, v_prob) = List.fold_left (find_max t) (StateMap.find (List.hd states) t) (List.tl states) in (total, List.rev v_path, v_prob) (* * Train an HMM given an input sequence. Sequence is lazy * this also needs to know the start_end state for training *) - type hmm_builder = { trans : (state * int32) list StateMap.t - ; emiss : (alphabet * int32) list StateMap.t + type hmm_builder = { trans : int32 StateMap.t StateMap.t + ; emiss : int32 EmissionMap.t StateMap.t ; se : state } - let update_m m ss vk = + let update_sm m ss vk = + let statemap_of_list : (StateMap.key * 'v) list -> 'v StateMap.t = List.fold_left (fun m (k, v) -> StateMap.add k v m) StateMap.empty in + try + let v = StateMap.find ss m in + try + let c = StateMap.find vk v in + StateMap.add ss (StateMap.add vk (Int32.succ c) v) m + with + Not_found -> + StateMap.add ss (StateMap.add vk Int32.one v) m + with + Not_found -> + StateMap.add ss (statemap_of_list [(vk, Int32.one)]) m + + let update_em m ss vk = + let emissionmap_of_list : (EmissionMap.key * 'v) list -> 'v EmissionMap.t = List.fold_left (fun m (k, v) -> EmissionMap.add k v m) EmissionMap.empty in try let v = StateMap.find ss m in try - let c = List.assoc vk v in - StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m + let c = EmissionMap.find vk v in + StateMap.add ss (EmissionMap.add vk (Int32.succ c) v) m with Not_found -> - StateMap.add ss ((vk, Int32.of_int 1)::v) m + StateMap.add ss (EmissionMap.add vk Int32.one v) m with Not_found -> - StateMap.add ss [(vk, Int32.of_int 1)] m + StateMap.add ss (emissionmap_of_list [(vk, Int32.one)]) m let train start_end seq = let rec train' ps cs hmm_b = function [] -> begin match Seq.next seq with Some (s, d) when s = cs -> train' ps cs hmm_b d | Some (s, d) -> train' cs s hmm_b d | None -> - {hmm_b with trans = update_m hmm_b.trans cs start_end} + {hmm_b with trans = update_sm hmm_b.trans cs start_end} end | x::xs -> train' cs cs {hmm_b with - trans = update_m hmm_b.trans ps cs - ; emiss = update_m hmm_b.emiss cs x + trans = update_sm hmm_b.trans ps cs + ; emiss = update_em hmm_b.emiss cs x } xs in - let make_probabilities trans = + let make_probabilities trans to_list = StateMap.fold (fun k v a -> - let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in - (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) + let sum = List.fold_left (Int32.add) (Int32.zero) (List.map snd (to_list v)) in + (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) (to_list v)))::a) trans [] in let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in - make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end + make (make_probabilities hmm_b.trans list_of_statemap) (make_probabilities hmm_b.emiss list_of_emissionmap) start_end end (* * These are HMM related functions but do not depend on the functor data as they are more general. *) (* * Because it is common to be working with strings (especially for DNA/Protein sequences where every char is an element) * this is a simple function to apply training data to each element in the string * This takes a string and a list of labels to apply. It will only apply labels if the string is large enough for all * of the labels to be applied. * a Some (labeled, rest) is returned on success, None otherwise. This does not apply it recursively. use '_all' * variant of the function for that *) let labeled_of_string labels s = if List.length labels <= String_ext.length s then let ll = List.length labels in Some (Misc_lib.zip labels (Misc_lib.list_of_string (String_ext.sub s 0 ll)), String_ext.sub s ll (String_ext.length s - ll)) else None (* * This is labeled_of_string, but it will consume * as much of the string as it can *) let labeled_of_string_all labels s = let rec f acc s = match labeled_of_string labels s with Some (l, s) -> f (l @ acc) s | None -> (acc, s) in f [] s diff --git a/lib/orf_bounding.ml b/lib/orf_bounding.ml new file mode 100644 index 0000000..7d4ae7b --- /dev/null +++ b/lib/orf_bounding.ml @@ -0,0 +1,93 @@ +(* + * This implements ORF-bounding, a term I made up. It means taking the boundaries of a + * predicted gene and looking for ORFs in an n-nucleotide surrounding area of it for exactly + * matching start/stop codons. + *) + + +let common_start_codons = ["ATG"; "GTG"; "TTG"] +let common_stop_codons = ["TAA"; "TAG"; "TGA"] + +let read_by_codons fin = + let rec f = + function + [] -> + raise (Failure "An empty entry in convert should never happen") + | x::xs as xss -> begin + let str = String_ext.concat "" (List.map (String_ext.make 1) xss) in + match Seq.next fin with + Some v -> + [< 'str; f (xs @ [v]) >] + | None -> + [< 'str >] + end + in + f (Seq.take 3 fin) + + +let orf_bounds_from_stream starts stops sin = + let f (start, stop) (idx, codon) = + if List.mem codon starts then + (idx::start, stop) + else if List.mem codon stops then + (start, idx::stop) + else + (start, stop) + in + let (start, stop) = Seq.fold_left f ([], []) (Seq.enumerate sin) in + (* This is not necessary but just doing it for visual debugging purposes *) + (List.rev start, List.rev stop) + + +let create_orf_bounds starts stops fasta_fname = + let sin = read_by_codons (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 fasta_fname)) in + orf_bounds_from_stream starts stops sin + + +(* + * This takes a tuple containg the start/stop of a predicted gene + * and a tuple from the output of create_orf_bounds and a cut off for + * how far in both directions of the gene to look for bounds. + * If no acceptable bound can be found in the vicinity, the gene + * is returned as is + * + * An acceptable bounds is defined as being close to the gene start + * and stop given (on the gene start and stop is preferred) and + * the length must be a multiple of 3 + *) +let find_nearest_bound cutoff (starts, stops) (gs, ge) = + let pstarts = List.filter (fun v -> v > gs - cutoff && v < gs + cutoff) starts in + let pstops = List.filter (fun v -> v > ge - cutoff && v < ge + cutoff) stops in + let local_orfs = + List.fold_left + (fun acc s -> + List.fold_left (fun acc e -> + if e - s mod 3 == 0 then + (s, e)::acc + else + acc) acc pstops) + [] + pstarts + in + let compare (s1, e1) (s2, e2) = + let ldiff = abs (s1 - gs) + abs (e1 - ge) in + let rdiff = abs (s2 - gs) + abs (e2 - ge) in + if ldiff < rdiff then + -1 + else if ldiff = rdiff then + 0 + else + 1 + in + if local_orfs = [] then + (gs, ge) + else + List.hd (List.sort compare local_orfs) + + +let test fname = + let _ = create_orf_bounds common_start_codons common_stop_codons fname in + if find_nearest_bound 20 ([1; 100], [10; 200]) (0, 9) <> (0, 9) then + raise (Failure "Found wrong nearest neighbor...") + else + ()
orbitz/glitter
0353cdb04b92b3673da01582d285756fb653d1cd
Version prior to significant optimizations on HMM
diff --git a/bin/make.sh b/bin/make.sh index 1662db0..2173329 100755 --- a/bin/make.sh +++ b/bin/make.sh @@ -1,26 +1,27 @@ #!/bin/sh OCAMLC="ocamlc" if [ $OCAMLC = "ocamlc" ] then SUFFIX=cmo LIB_SUFFIX=cma else SUFFIX=cmx LIB_SUFFIX=cmxa fi -BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX " +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" mkdir -p ../output for i in *.ml; do $OCAMLC -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done -$OCAMLC -g -o ../output/gb_to_genelist $BASE_OBJECTS gb_to_genelist.$SUFFIX +# $OCAMLC -g -o ../output/gb_to_genelist $BASE_OBJECTS gb_to_genelist.$SUFFIX -$OCAMLC -g -o ../output/glitter_2 $BASE_OBJECTS glitter_2.$SUFFIX -$OCAMLC -g -o ../output/glitter_4 $BASE_OBJECTS glitter_4.$SUFFIX -$OCAMLC -g -o ../output/glitter_7 $BASE_OBJECTS glitter_7.$SUFFIX -$OCAMLC -g -o ../output/glitter_10 $BASE_OBJECTS glitter_10.$SUFFIX +# $OCAMLC -g -o ../output/glitter_2 $BASE_OBJECTS glitter_2.$SUFFIX +# $OCAMLC -g -o ../output/glitter_4 $BASE_OBJECTS glitter_4.$SUFFIX +# $OCAMLC -g -o ../output/glitter_7 $BASE_OBJECTS glitter_7.$SUFFIX +# $OCAMLC -g -o ../output/glitter_10 $BASE_OBJECTS glitter_10.$SUFFIX +# $OCAMLC -g -o ../output/glitter_3_4 $BASE_OBJECTS glitter_3_4.$SUFFIX diff --git a/bin/run.sh b/bin/run.sh index 933e85e..1ff4599 100755 --- a/bin/run.sh +++ b/bin/run.sh @@ -1,8 +1,8 @@ #!/bin/sh SUFFIX=cmo LIB_SUFFIX=cma -BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX " +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX gene_prediction_3_4.$SUFFIX" ocaml $BASE_OBJECTS diff --git a/lib/gene_prediction_10.ml b/lib/gene_prediction_10.ml index 38b91cf..72d4721 100644 --- a/lib/gene_prediction_10.ml +++ b/lib/gene_prediction_10.ml @@ -1,67 +1,67 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | Start1 | Start2 | Start3 | C1 | C2 | C3 | Stop1 | Stop2 | Stop3 module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) let to_stream l = Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l) let rec label_start d fin = if String_ext.length d >= 3 then match Hmm.labeled_of_string [Start1; Start2; Start3] d with Some (l, d') -> (to_stream l, d') | _ -> raise (Failure "Labeling start condons failed") else match Seq.next fin with Some (Gene_prediction_2.Gene, d') -> label_start (d ^ d') fin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "Looking for start codon but got NotGene") | Some (Gene_prediction_2.Q0, _) | None -> raise (Failure "Looking for start codon but got EOF") let rec consume_notgenes f fin = match Seq.next fin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); consume_notgenes f fin>] | Some (Gene_prediction_2.Gene, d) -> let (l, d') = label_start d fin in [< l; f d' fin >] | Some (Gene_prediction_2.Q0, _) | None -> [< >] let label_codons d fin = let (l, d') = Hmm.labeled_of_string_all [C1; C2; C3] d in (to_stream l, d') let rec consume_gene d fin = let dl = String_ext.length d in if dl > 6 then let start = String_ext.sub d 0 (dl - 3) in let last_3 = String_ext.sub d (dl - 3) 3 in let (l, d') = label_codons start fin in [< l; consume_gene (d' ^ last_3) fin >] else match Seq.next fin with Some (Gene_prediction_2.NotGene, d') when dl = 3 -> let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in [< to_stream l; '(NotGene, d'); consume_notgenes consume_gene fin >] | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "This should never happen") | Some (Gene_prediction_2.Q0, _) | None -> let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in [< to_stream l >] | Some (Gene_prediction_2.Gene, d') -> consume_gene (d ^ d') fin let create_training_data gene_boundaries fin = let sin = Gene_prediction_2.create_training_data gene_boundaries fin in consume_notgenes consume_gene sin let predict training_fname fasta_fname = - Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Start1 + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene Start1 diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index 165c55a..1505789 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,127 +1,133 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> Some ((oe, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> (* If there are no gene boundaries left, all of the remaining values aren't genes *) [< '(NotGene, d); read_next (ctd []) e >] | (gs, ge)::_gbs when gs <= s && ge >= e -> (* If the gene spands all of the range we have, return the gene *) [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::gbs when gs <= s && ge < e -> (* If the gene starts at s or before s it means we are currently inside the gene. If the gene ends before the ending here we pull out the beginning and return that as a gene and recurse weith the rest *) let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, _ge)::_gbs when e < gs -> (* If teh start of the next gene is after the end of this, return as not a gene *) [< '(NotGene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when s <= gs && gs <= e -> (* If the gene boundaries is in side the boundary that we currently have, return the first as NotGene and recursively call the next piece *) let subd = String_ext.sub d 0 (gs - s) in let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in read_next (ctd gene_boundaries) 0 (* * We verify that the training data looks like we expect it. In this case, * the length of genes are a multiple of 3 and start with a start codon and * end with stop codon *) let verify_training_data td = let match_start_codon s = List.mem s ["ATG"; "GTG"; "TTG"] in let match_stop_codon s = List.mem s ["TAA"; "TAG"; "TGA"] in let verify_gene start_pos gene = let start_codon = String_ext.sub gene 0 3 in let stop_codon = String_ext.sub gene (String_ext.length gene - 3) 3 in if match_start_codon start_codon && match_stop_codon stop_codon && String_ext.length gene mod 3 = 0 then () else Printf.printf "Unknown codons, start_pos: %d start: %s stop: %s length: %d sequence \"%s\"" start_pos start_codon stop_codon (String_ext.length gene) gene in let rec vtd count acc = let sl = String_ext.length in match Seq.next td with Some (NotGene, d) -> if acc <> "" then begin verify_gene (1 + count - sl acc) acc; vtd (count + sl d) "" end else vtd (count + sl d) "" | Some (Gene, d) -> vtd (count + sl d) (acc ^ d) | Some (Q0, d) -> vtd (count + sl d) "" | None -> () in vtd 0 "" +(* + * We work in strings for some of this stuff for ease of use but viterbi wants a list + * of states. this is a simple wrapper to make our training data that on the fly + *) +let map_td_to_list f gb fasta = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (f gb fasta) + let predict training_fname fasta_fname = - Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Gene + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (map_td_to_list create_training_data) Misc_lib.identity NotGene Gene diff --git a/lib/gene_prediction_3_4.ml b/lib/gene_prediction_3_4.ml index c718713..53c4911 100644 --- a/lib/gene_prediction_3_4.ml +++ b/lib/gene_prediction_3_4.ml @@ -1,58 +1,76 @@ (* A 3rd order HMM with 4 states *) type coding_state = Q0 | NotGene | Start | Codon | Stop module H = Hmm.Make(struct type s = coding_state type a = string let compare = compare end) let join (c1, c2, c3) = String_ext.concat "" (List.map snd [c1; c2; c3]) let consume_next f (c1, c2, c3) sin = match Seq.next sin with Some c4 -> f (c2, c3, c4) sin | None -> [< >] let rec consume_intragene cont ((c1, _, _) as cs) sin = let joined = join cs in match fst c1 with Gene_prediction_10.Start2 | Gene_prediction_10.Start3 | Gene_prediction_10.C1 | Gene_prediction_10.C2 | Gene_prediction_10.C3 -> [< '(Codon, joined); consume_next (consume_intragene cont) cs sin >] | Gene_prediction_10.Stop1 -> [< '(Stop, joined); consume_next cont cs sin >] | _ -> raise (Failure "Not sure what I got in intragene...") let rec consume_notgene ((c1, _, _) as cs) sin = match fst c1 with Gene_prediction_10.NotGene | Gene_prediction_10.Stop2 | Gene_prediction_10.Stop3 -> let joined = join cs in [< '(NotGene, joined); consume_next consume_notgene cs sin >] | Gene_prediction_10.Start1 -> let joined = join cs in [< '(Start, joined); consume_next (consume_intragene consume_notgene) cs sin >] | _ -> raise (Failure "Waiting for NotGene | Start1 | Start2, dunno what I got...") let create_training_data gene_boundaries fin = let sin = Gene_prediction_10.create_training_data gene_boundaries fin in match Seq.take 3 sin with [c1; c2; c3] -> consume_notgene (c1, c2, c3) sin | _ -> raise (Failure "Expecting at least 3 values") +let map_td_to_list f gb fasta = Seq.map (fun (s, v) -> (s, [v])) (f gb fasta) + +let convert fin = + let rec f = + function + [] -> + raise (Failure "An empty entry in convert should never happen") + | x::xs as xss -> begin + let str = String_ext.concat "" (List.map (String_ext.make 1) xss) in + match Seq.next fin with + Some v -> + [< 'str; f (xs @ [v]) >] + | None -> + [< 'str >] + end + in + f (Seq.take 3 fin) + let predict training_fname fasta_fname = - Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Start + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (map_td_to_list create_training_data) convert NotGene Start diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml index 4deff3d..51239a9 100644 --- a/lib/gene_prediction_4.ml +++ b/lib/gene_prediction_4.ml @@ -1,50 +1,50 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | C1 | C2 | C3 module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = split_gene d in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin let predict training_fname fasta_fname = - Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene C1 + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene C1 diff --git a/lib/gene_prediction_7.ml b/lib/gene_prediction_7.ml index 5514160..62c5039 100644 --- a/lib/gene_prediction_7.ml +++ b/lib/gene_prediction_7.ml @@ -1,63 +1,63 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | A | T | G | C1 | C2 | C3 module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let rec gene_start d sin = if String_ext.length d < 3 then match Seq.next sin with Some (Gene_prediction_2.Gene, d') -> gene_start (d ^ d') sin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "At start of gene and gene end, wuuut?") | _ -> raise (Failure "At start of gene and sequence end, wuuuut?") else let (l, d) = Hmm.labeled_of_string_all [A; T; G;] d in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = gene_start d sin in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin let predict training_fname fasta_fname = - Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene A + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi (Gene_prediction_2.map_td_to_list create_training_data) Misc_lib.identity NotGene A diff --git a/lib/gene_predictor.ml b/lib/gene_predictor.ml index 985db0f..3ab6272 100644 --- a/lib/gene_predictor.ml +++ b/lib/gene_predictor.ml @@ -1,32 +1,31 @@ (* * Functions for prediction genes *) let min_gene_length = 500 let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) -let predict training_fname fasta_fname start_end train viterbi create_training_data ng sg = +let predict training_fname fasta_fname start_end train viterbi create_training_data fasta_converter ng sg = let fasta = Fasta.read_file ~chunk_size:10000 fasta_fname in (* Limit out training data to those ORFs that are min_gene_length+ nt in length *) let gene_boundaries = List.filter (fun (s, e) -> e - s > min_gene_length) (Genbank.read training_fname) in - let td = Seq.to_list (create_training_data gene_boundaries fasta) in - let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) in + let training_data = create_training_data gene_boundaries fasta in let hmm = train start_end training_data in - let (total, path, prob) = viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 fasta_fname)) hmm in + let (total, path, prob) = viterbi (fasta_converter (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 fasta_fname))) hmm in let gene_list = List.map (fun (_, b) -> b) (List.filter (fun (s, _) -> s <> ng) (Misc_lib.boundaries (genes ng sg path))) in let count = List.length gene_list in let training_count = List.length gene_boundaries in - ((total, path, prob), gene_list, count, training_count) + ((total, path, prob), hmm, gene_list, count, training_count) let write_gene_list gene_list fout = List.iter (fun (s, e) -> Printf.fprintf fout "%d\t%d\n" s e) gene_list diff --git a/lib/glitter.ml b/lib/glitter.ml index 4ca0d19..20c4339 100644 --- a/lib/glitter.ml +++ b/lib/glitter.ml @@ -1,8 +1,8 @@ -let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) +let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) let () = Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; Gene_predictor.write_gene_list gene_list stdout diff --git a/lib/glitter_10.ml b/lib/glitter_10.ml index 5b20672..9e32833 100644 --- a/lib/glitter_10.ml +++ b/lib/glitter_10.ml @@ -1,8 +1,8 @@ -let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_10.predict Sys.argv.(2) Sys.argv.(1) +let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_10.predict Sys.argv.(2) Sys.argv.(1) let () = Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; Gene_predictor.write_gene_list gene_list stdout diff --git a/lib/glitter_2.ml b/lib/glitter_2.ml index a2046f6..368607f 100644 --- a/lib/glitter_2.ml +++ b/lib/glitter_2.ml @@ -1,8 +1,8 @@ -let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_2.predict Sys.argv.(2) Sys.argv.(1) +let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_2.predict Sys.argv.(2) Sys.argv.(1) let () = Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; Gene_predictor.write_gene_list gene_list stdout diff --git a/lib/glitter_4.ml b/lib/glitter_4.ml index 787f29b..8924e25 100644 --- a/lib/glitter_4.ml +++ b/lib/glitter_4.ml @@ -1,8 +1,8 @@ -let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_4.predict Sys.argv.(2) Sys.argv.(1) +let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_4.predict Sys.argv.(2) Sys.argv.(1) let () = Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; Gene_predictor.write_gene_list gene_list stdout diff --git a/lib/glitter_7.ml b/lib/glitter_7.ml index 4ca0d19..20c4339 100644 --- a/lib/glitter_7.ml +++ b/lib/glitter_7.ml @@ -1,8 +1,8 @@ -let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) +let ((total, path, prob), _hmm, gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) let () = Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; Gene_predictor.write_gene_list gene_list stdout diff --git a/lib/hmm.ml b/lib/hmm.ml index 198259d..9e8782a 100644 --- a/lib/hmm.ml +++ b/lib/hmm.ml @@ -1,282 +1,282 @@ (* * Tools to construct and HMM and perform calculations on it *) module type Hmm_type = sig type s type a val compare: s -> s -> int end module Make = functor (Elt : Hmm_type) -> struct type state = Elt.s type alphabet = Elt.a type probability = float type transition = state * (state * probability) list type emission = state * (alphabet * probability) list module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) type hmm_state = { transitions : transition list ; emissions : emission list ; start_end : state } (* misc function for calculating a random weight *) let random_by_weight l = let rec get_random a v = function [] -> raise (Failure "You didn't represent all your base....") | (s, x)::xs -> let a = a + int_of_float (x *. 1000.0) in if v <= a then s else get_random a v xs in get_random 0 (Random.int 1001) l (* a misc funciton to work on lists *) let rec drop_while f = function [] -> [] | x::xs when f x -> x::xs | _::xs -> drop_while f xs let get_transitions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) let get_transition hmm s1 s2 = List.assoc s2 (get_transitions hmm s1) let get_transition_def hmm s1 s2 def = try get_transition hmm s1 s2 with Not_found -> def let get_states_by_emission hmm e = List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) let get_emissions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) let get_emission hmm s1 s2 = List.assoc s2 (get_emissions hmm s1) let get_emission_def hmm s1 s2 def = try List.assoc s2 (get_emissions hmm s1) with Not_found -> def let get_random_transition hmm s = random_by_weight (get_transitions hmm s) let get_random_emission hmm s = random_by_weight (get_emissions hmm s) let get_states hmm = List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) let make t e se = { transitions = t ; emissions = e ; start_end = se } let sample_emission hmm = let rec samp acc s = let ns = get_random_transition hmm s in if ns = hmm.start_end then acc else samp ((get_random_emission hmm ns)::acc) ns in samp [] hmm.start_end let sample_emission_seq hmm = let rec samp s = let ns = get_random_transition hmm s in if ns = hmm.start_end then [< >] else let o = get_random_emission hmm ns in [< 'o; samp ns >] in samp hmm.start_end let prob_of_sequence hmm seq = let rec p_of_s s = function [] -> snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) | x::xs -> let trans = get_transitions hmm s in let (ts, tp) = List.hd (drop_while (fun s -> List.mem_assoc x (get_emissions hmm (fst s))) trans) in - let ep = List.assoc x (get_emissions hmm ts) in + let ep = get_emission hmm ts x in tp *. ep *. p_of_s ts xs in p_of_s hmm.start_end seq (* * Calculates viterbi path + probabilities * returns (total probability, path, probability of path) *) let forward_viterbi obs hmm = let logsum x y = x +. log (1. +. exp (y -. x)) in let calc_max t ob ns (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let p = log (get_emission_def hmm s ob 0.0) +. log (get_transition_def hmm s ns 0.0) in let prob = prob +. p in let v_prob = v_prob +. p in (* This line might be a problem *) let total = if total = neg_infinity then prob else logsum total prob in if v_prob > valmax then (total, ns :: v_path, v_prob) else (total, argmax, valmax) in let accum_stats t ob u ns = let states = get_states hmm in StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u in let walk_states t ob = List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) in let walk_obs t = Seq.fold_left walk_states t obs in let make_t = List.fold_left (fun t s -> let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in StateMap.add s (start_p, [s], start_p) t) StateMap.empty (get_states hmm) in let find_max t (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let total = logsum total prob in if v_prob > valmax then (total, v_path, v_prob) else (total, argmax, valmax) in let t = walk_obs make_t in let states = get_states hmm in let (total, v_path, v_prob) = List.fold_left (find_max t) (StateMap.find (List.hd states) t) (List.tl states) in (total, List.rev v_path, v_prob) (* * Train an HMM given an input sequence. Sequence is lazy * this also needs to know the start_end state for training *) type hmm_builder = { trans : (state * int32) list StateMap.t ; emiss : (alphabet * int32) list StateMap.t ; se : state } let update_m m ss vk = try let v = StateMap.find ss m in try let c = List.assoc vk v in StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m with Not_found -> StateMap.add ss ((vk, Int32.of_int 1)::v) m with Not_found -> StateMap.add ss [(vk, Int32.of_int 1)] m let train start_end seq = let rec train' ps cs hmm_b = function [] -> begin match Seq.next seq with Some (s, d) when s = cs -> train' ps cs hmm_b d | Some (s, d) -> train' cs s hmm_b d | None -> {hmm_b with trans = update_m hmm_b.trans cs start_end} end | x::xs -> train' cs cs {hmm_b with trans = update_m hmm_b.trans ps cs ; emiss = update_m hmm_b.emiss cs x } xs in let make_probabilities trans = StateMap.fold (fun k v a -> let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) trans [] in let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end end (* * These are HMM related functions but do not depend on the functor data as they are more general. *) (* * Because it is common to be working with strings (especially for DNA/Protein sequences where every char is an element) * this is a simple function to apply training data to each element in the string * This takes a string and a list of labels to apply. It will only apply labels if the string is large enough for all * of the labels to be applied. * a Some (labeled, rest) is returned on success, None otherwise. This does not apply it recursively. use '_all' * variant of the function for that *) let labeled_of_string labels s = if List.length labels <= String_ext.length s then let ll = List.length labels in Some (Misc_lib.zip labels (Misc_lib.list_of_string (String_ext.sub s 0 ll)), String_ext.sub s ll (String_ext.length s - ll)) else None (* * This is labeled_of_string, but it will consume * as much of the string as it can *) let labeled_of_string_all labels s = let rec f acc s = match labeled_of_string labels s with Some (l, s) -> f (l @ acc) s | None -> (acc, s) in f [] s diff --git a/lib/misc_lib.ml b/lib/misc_lib.ml index 19ba09a..fbe2c7c 100644 --- a/lib/misc_lib.ml +++ b/lib/misc_lib.ml @@ -1,36 +1,38 @@ (* Very expensive function for what it does, but easy implementation *) let list_of_string s = Seq.to_list (Seq.of_string s) +let identity x = x + let uniq l = List.rev (List.fold_left (fun acc e -> match acc with [] -> [e] | x::_xs when e = x -> acc | x::_xs -> e::acc) [] l) let boundaries l = List.rev (Seq.fold_left (fun acc (idx, e) -> match acc with [] -> [(e, (idx, idx))] | (s, (x, y))::accs when s = e -> (s, (x, idx))::accs | (s, (x, y))::accs -> (e, (idx, idx))::(s, (x, idx))::accs) [] (Seq.enumerate (Seq.of_list l))) let rec zip l1 l2 = match (l1, l2) with (x1::x1s, x2::x2s) -> (x1, x2)::zip x1s x2s | _ -> []
orbitz/glitter
70e655b5cc833ec536a156bd93360e9f191897f7
Added several single order HMMs + wrapper scripts
diff --git a/bin/make.sh b/bin/make.sh index 70b38ad..1662db0 100755 --- a/bin/make.sh +++ b/bin/make.sh @@ -1,5 +1,26 @@ #!/bin/sh -OCAMLC=ocamlc +OCAMLC="ocamlc" + +if [ $OCAMLC = "ocamlc" ] +then + SUFFIX=cmo + LIB_SUFFIX=cma +else + SUFFIX=cmx + LIB_SUFFIX=cmxa +fi + +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX " + +mkdir -p ../output for i in *.ml; do $OCAMLC -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done + +$OCAMLC -g -o ../output/gb_to_genelist $BASE_OBJECTS gb_to_genelist.$SUFFIX + +$OCAMLC -g -o ../output/glitter_2 $BASE_OBJECTS glitter_2.$SUFFIX +$OCAMLC -g -o ../output/glitter_4 $BASE_OBJECTS glitter_4.$SUFFIX +$OCAMLC -g -o ../output/glitter_7 $BASE_OBJECTS glitter_7.$SUFFIX +$OCAMLC -g -o ../output/glitter_10 $BASE_OBJECTS glitter_10.$SUFFIX + diff --git a/bin/run.sh b/bin/run.sh index cd8221a..933e85e 100755 --- a/bin/run.sh +++ b/bin/run.sh @@ -1,3 +1,8 @@ #!/bin/sh -ocaml str.cma seq.cmo lazy_io.cmo misc_lib.cmo string_ext.cmo fasta.cmo genbank.cmo hmm.cmo gene_prediction_2.cmo gene_prediction_4.cmo gene_prediction_7.cmo +SUFFIX=cmo +LIB_SUFFIX=cma + +BASE_OBJECTS="str.$LIB_SUFFIX seq.$SUFFIX lazy_io.$SUFFIX misc_lib.$SUFFIX string_ext.$SUFFIX fasta.$SUFFIX genbank.$SUFFIX hmm.$SUFFIX gene_predictor.$SUFFIX gene_prediction_2.$SUFFIX gene_prediction_4.$SUFFIX gene_prediction_7.$SUFFIX gene_prediction_10.$SUFFIX " + +ocaml $BASE_OBJECTS diff --git a/lib/gb_to_genelist.ml b/lib/gb_to_genelist.ml new file mode 100644 index 0000000..d651268 --- /dev/null +++ b/lib/gb_to_genelist.ml @@ -0,0 +1,4 @@ + +let gene_boundaries = Genbank.read Sys.argv.(1) + +let () = Gene_predictor.write_gene_list gene_boundaries stdout diff --git a/lib/gene_prediction_10.ml b/lib/gene_prediction_10.ml index 0db1573..38b91cf 100644 --- a/lib/gene_prediction_10.ml +++ b/lib/gene_prediction_10.ml @@ -1,58 +1,67 @@ (* 4 state hmm *) -type coding_states = +type coding_state = Q0 | NotGene | Start1 | Start2 | Start3 | C1 | C2 | C3 | Stop1 | Stop2 | Stop3 +module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) + let to_stream l = Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l) let rec label_start d fin = if String_ext.length d >= 3 then match Hmm.labeled_of_string [Start1; Start2; Start3] d with Some (l, d') -> (to_stream l, d') | _ -> raise (Failure "Labeling start condons failed") else match Seq.next fin with Some (Gene_prediction_2.Gene, d') -> label_start (d ^ d') fin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "Looking for start codon but got NotGene") | Some (Gene_prediction_2.Q0, _) | None -> raise (Failure "Looking for start codon but got EOF") let rec consume_notgenes f fin = match Seq.next fin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); consume_notgenes f fin>] | Some (Gene_prediction_2.Gene, d) -> let (l, d') = label_start d fin in - [< 'l; f d' fin >] + [< l; f d' fin >] | Some (Gene_prediction_2.Q0, _) | None -> [< >] let label_codons d fin = let (l, d') = Hmm.labeled_of_string_all [C1; C2; C3] d in (to_stream l, d') let rec consume_gene d fin = let dl = String_ext.length d in if dl > 6 then let start = String_ext.sub d 0 (dl - 3) in let last_3 = String_ext.sub d (dl - 3) 3 in let (l, d') = label_codons start fin in - [< l; consume_gene f (d' ^ last_3) fin >] + [< l; consume_gene (d' ^ last_3) fin >] else match Seq.next fin with Some (Gene_prediction_2.NotGene, d') when dl = 3 -> - let (l, _) = Hmm.labeled_of_string [Stop1; Stop2; Stop3] d in + let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in [< to_stream l; '(NotGene, d'); consume_notgenes consume_gene fin >] + | Some (Gene_prediction_2.NotGene, _) -> + raise (Failure "This should never happen") | Some (Gene_prediction_2.Q0, _) | None -> - let (l, _) = Hmm.labeled_of_string [Stop1; Stop2; Stop3] d in - [< Seq.of_list l >] + let (l, _) = Hmm.labeled_of_string_all [Stop1; Stop2; Stop3] d in + [< to_stream l >] | Some (Gene_prediction_2.Gene, d') -> consume_gene (d ^ d') fin let create_training_data gene_boundaries fin = let sin = Gene_prediction_2.create_training_data gene_boundaries fin in consume_notgenes consume_gene sin + + +let predict training_fname fasta_fname = + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Start1 + diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index c4d06e1..165c55a 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,111 +1,127 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene +module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) + +let genes ng sg l = + Seq.to_list (Seq.map + (fun s -> + if s <> sg && s <> ng then + sg + else + s) + (Seq.of_list l)) + + (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> Some ((oe, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> (* If there are no gene boundaries left, all of the remaining values aren't genes *) [< '(NotGene, d); read_next (ctd []) e >] | (gs, ge)::_gbs when gs <= s && ge >= e -> (* If the gene spands all of the range we have, return the gene *) [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::gbs when gs <= s && ge < e -> (* If the gene starts at s or before s it means we are currently inside the gene. If the gene ends before the ending here we pull out the beginning and return that as a gene and recurse weith the rest *) let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, _ge)::_gbs when e < gs -> (* If teh start of the next gene is after the end of this, return as not a gene *) [< '(NotGene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when s <= gs && gs <= e -> (* If the gene boundaries is in side the boundary that we currently have, return the first as NotGene and recursively call the next piece *) let subd = String_ext.sub d 0 (gs - s) in let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in read_next (ctd gene_boundaries) 0 (* * We verify that the training data looks like we expect it. In this case, * the length of genes are a multiple of 3 and start with a start codon and * end with stop codon *) let verify_training_data td = let match_start_codon s = List.mem s ["ATG"; "GTG"; "TTG"] in let match_stop_codon s = List.mem s ["TAA"; "TAG"; "TGA"] in let verify_gene start_pos gene = let start_codon = String_ext.sub gene 0 3 in let stop_codon = String_ext.sub gene (String_ext.length gene - 3) 3 in if match_start_codon start_codon && match_stop_codon stop_codon && String_ext.length gene mod 3 = 0 then () else Printf.printf "Unknown codons, start_pos: %d start: %s stop: %s length: %d sequence \"%s\"" start_pos start_codon stop_codon (String_ext.length gene) gene in let rec vtd count acc = let sl = String_ext.length in match Seq.next td with Some (NotGene, d) -> if acc <> "" then begin verify_gene (1 + count - sl acc) acc; vtd (count + sl d) "" end else vtd (count + sl d) "" | Some (Gene, d) -> vtd (count + sl d) (acc ^ d) | Some (Q0, d) -> vtd (count + sl d) "" | None -> () in vtd 0 "" + + +let predict training_fname fasta_fname = + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Gene diff --git a/lib/gene_prediction_3_4.ml b/lib/gene_prediction_3_4.ml new file mode 100644 index 0000000..c718713 --- /dev/null +++ b/lib/gene_prediction_3_4.ml @@ -0,0 +1,58 @@ +(* A 3rd order HMM with 4 states *) + +type coding_state = Q0 | NotGene | Start | Codon | Stop + +module H = Hmm.Make(struct type s = coding_state type a = string let compare = compare end) + +let join (c1, c2, c3) = String_ext.concat "" (List.map snd [c1; c2; c3]) + +let consume_next f (c1, c2, c3) sin = + match Seq.next sin with + Some c4 -> + f (c2, c3, c4) sin + | None -> + [< >] + + +let rec consume_intragene cont ((c1, _, _) as cs) sin = + let joined = join cs in + match fst c1 with + Gene_prediction_10.Start2 + | Gene_prediction_10.Start3 + | Gene_prediction_10.C1 + | Gene_prediction_10.C2 + | Gene_prediction_10.C3 -> + [< '(Codon, joined); consume_next (consume_intragene cont) cs sin >] + | Gene_prediction_10.Stop1 -> + [< '(Stop, joined); consume_next cont cs sin >] + | _ -> + raise (Failure "Not sure what I got in intragene...") + +let rec consume_notgene ((c1, _, _) as cs) sin = + match fst c1 with + Gene_prediction_10.NotGene + | Gene_prediction_10.Stop2 + | Gene_prediction_10.Stop3 -> + let joined = join cs in + [< '(NotGene, joined); consume_next consume_notgene cs sin >] + | Gene_prediction_10.Start1 -> + let joined = join cs in + [< '(Start, joined); consume_next (consume_intragene consume_notgene) cs sin >] + | _ -> + raise (Failure "Waiting for NotGene | Start1 | Start2, dunno what I got...") + + +let create_training_data gene_boundaries fin = + let sin = Gene_prediction_10.create_training_data gene_boundaries fin in + match Seq.take 3 sin with + [c1; c2; c3] -> + consume_notgene (c1, c2, c3) sin + | _ -> + raise (Failure "Expecting at least 3 values") + + +let predict training_fname fasta_fname = + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene Start + + + diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml index 04c45e4..4deff3d 100644 --- a/lib/gene_prediction_4.ml +++ b/lib/gene_prediction_4.ml @@ -1,46 +1,50 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | C1 | C2 | C3 +module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = split_gene d in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin + +let predict training_fname fasta_fname = + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene C1 diff --git a/lib/gene_prediction_7.ml b/lib/gene_prediction_7.ml index 61c5adc..5514160 100644 --- a/lib/gene_prediction_7.ml +++ b/lib/gene_prediction_7.ml @@ -1,59 +1,63 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | A | T | G | C1 | C2 | C3 +module H = Hmm.Make(struct type s = coding_state type a = char let compare = compare end) (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let rec gene_start d sin = if String_ext.length d < 3 then match Seq.next sin with Some (Gene_prediction_2.Gene, d') -> gene_start (d ^ d') sin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "At start of gene and gene end, wuuut?") | _ -> raise (Failure "At start of gene and sequence end, wuuuut?") else let (l, d) = Hmm.labeled_of_string_all [A; T; G;] d in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = gene_start d sin in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin + +let predict training_fname fasta_fname = + Gene_predictor.predict training_fname fasta_fname Q0 H.train H.forward_viterbi create_training_data NotGene A diff --git a/lib/gene_predictor.ml b/lib/gene_predictor.ml new file mode 100644 index 0000000..985db0f --- /dev/null +++ b/lib/gene_predictor.ml @@ -0,0 +1,32 @@ +(* + * Functions for prediction genes + *) + +let min_gene_length = 500 + +let genes ng sg l = + Seq.to_list (Seq.map + (fun s -> + if s <> sg && s <> ng then + sg + else + s) + (Seq.of_list l)) + +let predict training_fname fasta_fname start_end train viterbi create_training_data ng sg = + let fasta = Fasta.read_file ~chunk_size:10000 fasta_fname in + (* Limit out training data to those ORFs that are min_gene_length+ nt in length *) + let gene_boundaries = List.filter (fun (s, e) -> e - s > min_gene_length) (Genbank.read training_fname) in + let td = Seq.to_list (create_training_data gene_boundaries fasta) in + let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) in + let hmm = train start_end training_data in + let (total, path, prob) = viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 fasta_fname)) hmm in + let gene_list = List.map (fun (_, b) -> b) (List.filter (fun (s, _) -> s <> ng) (Misc_lib.boundaries (genes ng sg path))) in + let count = List.length gene_list in + let training_count = List.length gene_boundaries in + ((total, path, prob), gene_list, count, training_count) + + +let write_gene_list gene_list fout = + List.iter (fun (s, e) -> Printf.fprintf fout "%d\t%d\n" s e) gene_list + diff --git a/lib/glitter.ml b/lib/glitter.ml new file mode 100644 index 0000000..4ca0d19 --- /dev/null +++ b/lib/glitter.ml @@ -0,0 +1,8 @@ + +let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) + +let () = + Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; + Gene_predictor.write_gene_list gene_list stdout + + diff --git a/lib/glitter_10.ml b/lib/glitter_10.ml new file mode 100644 index 0000000..5b20672 --- /dev/null +++ b/lib/glitter_10.ml @@ -0,0 +1,8 @@ + +let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_10.predict Sys.argv.(2) Sys.argv.(1) + +let () = + Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; + Gene_predictor.write_gene_list gene_list stdout + + diff --git a/lib/glitter_2.ml b/lib/glitter_2.ml new file mode 100644 index 0000000..a2046f6 --- /dev/null +++ b/lib/glitter_2.ml @@ -0,0 +1,8 @@ + +let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_2.predict Sys.argv.(2) Sys.argv.(1) + +let () = + Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; + Gene_predictor.write_gene_list gene_list stdout + + diff --git a/lib/glitter_4.ml b/lib/glitter_4.ml new file mode 100644 index 0000000..787f29b --- /dev/null +++ b/lib/glitter_4.ml @@ -0,0 +1,8 @@ + +let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_4.predict Sys.argv.(2) Sys.argv.(1) + +let () = + Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; + Gene_predictor.write_gene_list gene_list stdout + + diff --git a/lib/glitter_7.ml b/lib/glitter_7.ml new file mode 100644 index 0000000..4ca0d19 --- /dev/null +++ b/lib/glitter_7.ml @@ -0,0 +1,8 @@ + +let ((total, path, prob), gene_list, count, training_count) = Gene_prediction_7.predict Sys.argv.(2) Sys.argv.(1) + +let () = + Printf.fprintf stdout "%f\n%f\n%d\n%d\n" total prob count training_count; + Gene_predictor.write_gene_list gene_list stdout + + diff --git a/lib/hmm.ml b/lib/hmm.ml index 59e6b65..198259d 100644 --- a/lib/hmm.ml +++ b/lib/hmm.ml @@ -1,278 +1,282 @@ (* * Tools to construct and HMM and perform calculations on it *) module type Hmm_type = sig type s type a val compare: s -> s -> int end module Make = functor (Elt : Hmm_type) -> struct type state = Elt.s type alphabet = Elt.a type probability = float type transition = state * (state * probability) list type emission = state * (alphabet * probability) list module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) type hmm_state = { transitions : transition list ; emissions : emission list ; start_end : state } (* misc function for calculating a random weight *) let random_by_weight l = let rec get_random a v = function [] -> raise (Failure "You didn't represent all your base....") | (s, x)::xs -> let a = a + int_of_float (x *. 1000.0) in if v <= a then s else get_random a v xs in get_random 0 (Random.int 1001) l (* a misc funciton to work on lists *) let rec drop_while f = function [] -> [] | x::xs when f x -> x::xs | _::xs -> drop_while f xs let get_transitions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) let get_transition hmm s1 s2 = List.assoc s2 (get_transitions hmm s1) let get_transition_def hmm s1 s2 def = try get_transition hmm s1 s2 with Not_found -> def let get_states_by_emission hmm e = List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) let get_emissions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) let get_emission hmm s1 s2 = List.assoc s2 (get_emissions hmm s1) let get_emission_def hmm s1 s2 def = - List.assoc s2 (get_emissions hmm s1) + try + List.assoc s2 (get_emissions hmm s1) + with + Not_found -> def let get_random_transition hmm s = random_by_weight (get_transitions hmm s) let get_random_emission hmm s = random_by_weight (get_emissions hmm s) let get_states hmm = List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) let make t e se = { transitions = t ; emissions = e ; start_end = se } let sample_emission hmm = let rec samp acc s = let ns = get_random_transition hmm s in if ns = hmm.start_end then acc else samp ((get_random_emission hmm ns)::acc) ns in samp [] hmm.start_end let sample_emission_seq hmm = let rec samp s = let ns = get_random_transition hmm s in if ns = hmm.start_end then [< >] else let o = get_random_emission hmm ns in [< 'o; samp ns >] in samp hmm.start_end let prob_of_sequence hmm seq = let rec p_of_s s = function [] -> snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) | x::xs -> let trans = get_transitions hmm s in let (ts, tp) = List.hd (drop_while (fun s -> List.mem_assoc x (get_emissions hmm (fst s))) trans) in let ep = List.assoc x (get_emissions hmm ts) in tp *. ep *. p_of_s ts xs in p_of_s hmm.start_end seq (* * Calculates viterbi path + probabilities * returns (total probability, path, probability of path) *) let forward_viterbi obs hmm = let logsum x y = x +. log (1. +. exp (y -. x)) in let calc_max t ob ns (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let p = log (get_emission_def hmm s ob 0.0) +. log (get_transition_def hmm s ns 0.0) in let prob = prob +. p in let v_prob = v_prob +. p in + (* This line might be a problem *) let total = if total = neg_infinity then prob else logsum total prob in if v_prob > valmax then (total, ns :: v_path, v_prob) else (total, argmax, valmax) in let accum_stats t ob u ns = let states = get_states hmm in StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u in let walk_states t ob = List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) in let walk_obs t = Seq.fold_left walk_states t obs in let make_t = List.fold_left (fun t s -> let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in StateMap.add s (start_p, [s], start_p) t) StateMap.empty (get_states hmm) in let find_max t (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let total = logsum total prob in if v_prob > valmax then (total, v_path, v_prob) else (total, argmax, valmax) in let t = walk_obs make_t in let states = get_states hmm in let (total, v_path, v_prob) = List.fold_left (find_max t) (StateMap.find (List.hd states) t) (List.tl states) in - (exp total, List.rev v_path, exp v_prob) + (total, List.rev v_path, v_prob) (* * Train an HMM given an input sequence. Sequence is lazy * this also needs to know the start_end state for training *) type hmm_builder = { trans : (state * int32) list StateMap.t ; emiss : (alphabet * int32) list StateMap.t ; se : state } let update_m m ss vk = try let v = StateMap.find ss m in try let c = List.assoc vk v in StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m with Not_found -> StateMap.add ss ((vk, Int32.of_int 1)::v) m with Not_found -> StateMap.add ss [(vk, Int32.of_int 1)] m let train start_end seq = let rec train' ps cs hmm_b = function [] -> begin match Seq.next seq with Some (s, d) when s = cs -> train' ps cs hmm_b d | Some (s, d) -> train' cs s hmm_b d | None -> {hmm_b with trans = update_m hmm_b.trans cs start_end} end | x::xs -> train' cs cs {hmm_b with trans = update_m hmm_b.trans ps cs ; emiss = update_m hmm_b.emiss cs x } xs in let make_probabilities trans = StateMap.fold (fun k v a -> let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) trans [] in let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end end (* * These are HMM related functions but do not depend on the functor data as they are more general. *) (* * Because it is common to be working with strings (especially for DNA/Protein sequences where every char is an element) * this is a simple function to apply training data to each element in the string * This takes a string and a list of labels to apply. It will only apply labels if the string is large enough for all * of the labels to be applied. * a Some (labeled, rest) is returned on success, None otherwise. This does not apply it recursively. use '_all' * variant of the function for that *) let labeled_of_string labels s = if List.length labels <= String_ext.length s then let ll = List.length labels in Some (Misc_lib.zip labels (Misc_lib.list_of_string (String_ext.sub s 0 ll)), String_ext.sub s ll (String_ext.length s - ll)) else None (* * This is labeled_of_string, but it will consume * as much of the string as it can *) let labeled_of_string_all labels s = let rec f acc s = match labeled_of_string labels s with Some (l, s) -> f (l @ acc) s | None -> (acc, s) in f [] s diff --git a/lib/test.ml b/lib/test.ml deleted file mode 100644 index 5fe2089..0000000 --- a/lib/test.ml +++ /dev/null @@ -1,90 +0,0 @@ - -(* type states = Q0 | Q1 | Q2 *) - -(* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) -(* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) -(* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) -(* ] *) - - -(* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) -(* ; (Q2, [ ('R', 1.0) ]) *) -(* ] *) - -(* type states = Q0 | Rainy | Sunny *) - -(* type alphabet = Walk | Shop | Clean *) - -(* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) -(* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) -(* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) -(* ] *) - - -(* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) -(* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) -(* ] *) - - -(* let observations = [ Walk; Shop; Clean ] *) - - -(* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) - -(* let hmm = H.make transitions emissions Q0 *) - -(* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) - - -(* type states = Q0 | One | Two *) - -(* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) - -(* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) -(* ; (Two, Misc_lib.list_of_string "CGATTCT") *) -(* ; (One, Misc_lib.list_of_string "ACGCGC") *) -(* ; (Two, Misc_lib.list_of_string "GTAT") *) -(* ; (One, Misc_lib.list_of_string "ACTAGCT") *) -(* ; (Two, Misc_lib.list_of_string "TATC") *) -(* ; (One, Misc_lib.list_of_string "TGATC") *) -(* ] *) - - -(* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) -(* ; (One, Misc_lib.list_of_string "ATT") *) -(* ; (Two, Misc_lib.list_of_string "CGATTCT") *) -(* ; (One, Misc_lib.list_of_string "ACGCGC") *) -(* ; (Two, Misc_lib.list_of_string "GTAT") *) -(* ; (One, Misc_lib.list_of_string "ACTAGCT") *) -(* ; (Two, Misc_lib.list_of_string "TATC") *) -(* ; (One, Misc_lib.list_of_string "TGATC") *) -(* ] *) - - -let genes ng sg l = - Seq.to_list (Seq.map - (fun s -> - if s <> sg && s <> ng then - sg - else - s) - (Seq.of_list l)) - - - -module H = Hmm.Make(struct type s = Gene_prediction_7.coding_state type a = char let compare = compare end) - -let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" -let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" -let td = Seq.to_list (Gene_prediction_7.create_training_data gene_boundaries fasta) - -(* let () = Gene_prediction_7.verify_training_data (Seq.of_list td) *) - -let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) -let hmm = H.train Gene_prediction_7.Q0 training_data -let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm - -let gene_list = genes Gene_prediction_7.NotGene Gene_prediction_7.Start1 path - -let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_7.NotGene) (Misc_lib.boundaries gene_list)) -
orbitz/glitter
2b6a1f393df0b7fdef1ab142bccb5333f569bcbc
Adding new HMM code (partially broken)
diff --git a/bin/make.sh b/bin/make.sh index b826e86..70b38ad 100755 --- a/bin/make.sh +++ b/bin/make.sh @@ -1,2 +1,5 @@ #!/bin/sh -for i in *.ml; do ocamlc -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done + +OCAMLC=ocamlc + +for i in *.ml; do $OCAMLC -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done diff --git a/bin/run.sh b/bin/run.sh index 9b08ef0..cd8221a 100755 --- a/bin/run.sh +++ b/bin/run.sh @@ -1,2 +1,3 @@ #!/bin/sh + ocaml str.cma seq.cmo lazy_io.cmo misc_lib.cmo string_ext.cmo fasta.cmo genbank.cmo hmm.cmo gene_prediction_2.cmo gene_prediction_4.cmo gene_prediction_7.cmo diff --git a/lib/gene_prediction_10.ml b/lib/gene_prediction_10.ml new file mode 100644 index 0000000..0db1573 --- /dev/null +++ b/lib/gene_prediction_10.ml @@ -0,0 +1,58 @@ +(* 4 state hmm *) + +type coding_states = + Q0 | NotGene + | Start1 | Start2 | Start3 | C1 | C2 | C3 | Stop1 | Stop2 | Stop3 + +let to_stream l = Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l) + +let rec label_start d fin = + if String_ext.length d >= 3 then + match Hmm.labeled_of_string [Start1; Start2; Start3] d with + Some (l, d') -> + (to_stream l, d') + | _ -> raise (Failure "Labeling start condons failed") + else + match Seq.next fin with + Some (Gene_prediction_2.Gene, d') -> + label_start (d ^ d') fin + | Some (Gene_prediction_2.NotGene, _) -> + raise (Failure "Looking for start codon but got NotGene") + | Some (Gene_prediction_2.Q0, _) | None -> + raise (Failure "Looking for start codon but got EOF") + +let rec consume_notgenes f fin = + match Seq.next fin with + Some (Gene_prediction_2.NotGene, d) -> + [< '(NotGene, d); consume_notgenes f fin>] + | Some (Gene_prediction_2.Gene, d) -> + let (l, d') = label_start d fin in + [< 'l; f d' fin >] + | Some (Gene_prediction_2.Q0, _) | None -> + [< >] + +let label_codons d fin = + let (l, d') = Hmm.labeled_of_string_all [C1; C2; C3] d in + (to_stream l, d') + +let rec consume_gene d fin = + let dl = String_ext.length d in + if dl > 6 then + let start = String_ext.sub d 0 (dl - 3) in + let last_3 = String_ext.sub d (dl - 3) 3 in + let (l, d') = label_codons start fin in + [< l; consume_gene f (d' ^ last_3) fin >] + else + match Seq.next fin with + Some (Gene_prediction_2.NotGene, d') when dl = 3 -> + let (l, _) = Hmm.labeled_of_string [Stop1; Stop2; Stop3] d in + [< to_stream l; '(NotGene, d'); consume_notgenes consume_gene fin >] + | Some (Gene_prediction_2.Q0, _) | None -> + let (l, _) = Hmm.labeled_of_string [Stop1; Stop2; Stop3] d in + [< Seq.of_list l >] + | Some (Gene_prediction_2.Gene, d') -> + consume_gene (d ^ d') fin + +let create_training_data gene_boundaries fin = + let sin = Gene_prediction_2.create_training_data gene_boundaries fin in + consume_notgenes consume_gene sin diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index 88e63d6..c4d06e1 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,72 +1,111 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> Some ((oe, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> + (* If there are no gene boundaries left, all of the remaining values aren't genes *) [< '(NotGene, d); read_next (ctd []) e >] - | (gs, _ge)::_gbs when s < gs && gs <= e -> - let subd = String_ext.sub d 0 (gs - s) in - let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in - [< '(NotGene, subd); ctd gb (gs, e) restd >] + | (gs, ge)::_gbs when gs <= s && ge >= e -> + (* If the gene spands all of the range we have, return the gene *) + [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::gbs when gs <= s && ge < e -> + (* If the gene starts at s or before s it means we are currently inside + the gene. If the gene ends before the ending here we pull out the + beginning and return that as a gene and recurse weith the rest *) let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] - | (gs, ge)::gbs when s = gs && ge = e -> - [< '(Gene, d); read_next (ctd gbs) e >] - | (gs, ge)::_gbs when s = gs && e < ge -> - [< '(Gene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when e < gs -> + (* If teh start of the next gene is after the end of this, return as not a gene *) [< '(NotGene, d); read_next (ctd gb) e >] - | (gs, ge)::_gbs when gs < s && e < ge -> - [< '(Gene, d); read_next (ctd gb) e >] + | (gs, _ge)::_gbs when s <= gs && gs <= e -> + (* If the gene boundaries is in side the boundary that we currently have, + return the first as NotGene and recursively call the next piece *) + let subd = String_ext.sub d 0 (gs - s) in + let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in + [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in read_next (ctd gene_boundaries) 0 + +(* + * We verify that the training data looks like we expect it. In this case, + * the length of genes are a multiple of 3 and start with a start codon and + * end with stop codon + *) +let verify_training_data td = + let match_start_codon s = List.mem s ["ATG"; "GTG"; "TTG"] in + let match_stop_codon s = List.mem s ["TAA"; "TAG"; "TGA"] in + let verify_gene start_pos gene = + let start_codon = String_ext.sub gene 0 3 in + let stop_codon = String_ext.sub gene (String_ext.length gene - 3) 3 in + if match_start_codon start_codon && match_stop_codon stop_codon && String_ext.length gene mod 3 = 0 then + () + else + Printf.printf "Unknown codons, start_pos: %d start: %s stop: %s length: %d sequence \"%s\"" start_pos start_codon stop_codon (String_ext.length gene) gene + in + let rec vtd count acc = + let sl = String_ext.length in + match Seq.next td with + Some (NotGene, d) -> + if acc <> "" then begin + verify_gene (1 + count - sl acc) acc; + vtd (count + sl d) "" + end + else + vtd (count + sl d) "" + | Some (Gene, d) -> + vtd (count + sl d) (acc ^ d) + | Some (Q0, d) -> + vtd (count + sl d) "" + | None -> + () + in + vtd 0 "" diff --git a/lib/gene_prediction_20.ml b/lib/gene_prediction_20.ml new file mode 100644 index 0000000..2f7bc32 --- /dev/null +++ b/lib/gene_prediction_20.ml @@ -0,0 +1,7 @@ +(* 4 state hmm *) + +type coding_states = + Q0 | NotGene + | Start1 | Start2 | Start3 | C1 | C2 | C3 | Stop1 | Stop2 | Stop3 + | RStart1 | RStart2 | RStart3 | RC1 | RC2 | RC3 | RStop1 | RStop2 | RStop3 + diff --git a/lib/test.ml b/lib/test.ml index 8f74eb6..5fe2089 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,85 +1,90 @@ + (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) (* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) (* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) (* ; (One, Misc_lib.list_of_string "ATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) -module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct type s = Gene_prediction_7.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" -let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) +let td = Seq.to_list (Gene_prediction_7.create_training_data gene_boundaries fasta) + +(* let () = Gene_prediction_7.verify_training_data (Seq.of_list td) *) + let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) -let hmm = H.train Gene_prediction_4.Q0 training_data +let hmm = H.train Gene_prediction_7.Q0 training_data let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm -let gene_list = genes Gene_prediction_4.NotGene Gene_prediction_4.C1 path +let gene_list = genes Gene_prediction_7.NotGene Gene_prediction_7.Start1 path + +let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_7.NotGene) (Misc_lib.boundaries gene_list)) -let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_4.NotGene) (Misc_lib.boundaries gene_list))
orbitz/glitter
e6b21143475683dba8f1d4af709bac907d341d6e
Had a line in there that shouldn't have been
diff --git a/lib/test.ml b/lib/test.ml index 2582f9a..8f74eb6 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,88 +1,85 @@ (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) (* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) (* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) (* ; (One, Misc_lib.list_of_string "ATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) let hmm = H.train Gene_prediction_4.Q0 training_data let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm let gene_list = genes Gene_prediction_4.NotGene Gene_prediction_4.C1 path let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_4.NotGene) (Misc_lib.boundaries gene_list)) - - -List.map (fun (_, s) -> String.length s mod 3) (List.filter (fun (s, _) -> s <> Gene_prediction_2.NotGene) td)
orbitz/glitter
664836f066be86def68568b698847eb0536b3199
Silly scripts that need to be replaced with make files
diff --git a/bin/make.sh b/bin/make.sh new file mode 100755 index 0000000..b826e86 --- /dev/null +++ b/bin/make.sh @@ -0,0 +1,2 @@ +#!/bin/sh +for i in *.ml; do ocamlc -pp "camlp4o pa_extend.cmo" -I +camlp4 -g -c $i; done diff --git a/bin/run.sh b/bin/run.sh new file mode 100755 index 0000000..9b08ef0 --- /dev/null +++ b/bin/run.sh @@ -0,0 +1,2 @@ +#!/bin/sh +ocaml str.cma seq.cmo lazy_io.cmo misc_lib.cmo string_ext.cmo fasta.cmo genbank.cmo hmm.cmo gene_prediction_2.cmo gene_prediction_4.cmo gene_prediction_7.cmo diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index a3b8cdb..88e63d6 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,73 +1,72 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> - let oe' = oe + 1 in - Some ((oe', oe' + String_ext.length d), d) + Some ((oe, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with - Some ((0, 0), _h) -> read_next f (-1) + Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> [< '(NotGene, d); read_next (ctd []) e >] | (gs, _ge)::_gbs when s < gs && gs <= e -> let subd = String_ext.sub d 0 (gs - s) in let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::gbs when gs <= s && ge < e -> let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, ge)::gbs when s = gs && ge = e -> [< '(Gene, d); read_next (ctd gbs) e >] | (gs, ge)::_gbs when s = gs && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when e < gs -> [< '(NotGene, d); read_next (ctd gb) e >] | (gs, ge)::_gbs when gs < s && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in - read_next (ctd gene_boundaries) (-1) + read_next (ctd gene_boundaries) 0 diff --git a/lib/test.ml b/lib/test.ml index 543996c..2582f9a 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,86 +1,88 @@ (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) (* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) (* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) (* ; (One, Misc_lib.list_of_string "ATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) let genes ng sg l = Seq.to_list (Seq.map (fun s -> if s <> sg && s <> ng then sg else s) (Seq.of_list l)) -module H = Hmm.Make(struct type s = Gene_prediction_2.coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" -let td = Seq.to_list (Gene_prediction_2.create_training_data gene_boundaries fasta) -(* let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) *) -(* let hmm = H.train Gene_prediction_4.Q0 training_data *) -(* let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm *) +let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) +let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) +let hmm = H.train Gene_prediction_4.Q0 training_data +let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm -(* let gene_list = genes Gene_prediction_4.NotGene Gene_prediction_4.C1 path *) +let gene_list = genes Gene_prediction_4.NotGene Gene_prediction_4.C1 path -(* let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_4.NotGene) (Misc_lib.boundaries gene_list)) *) +let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_4.NotGene) (Misc_lib.boundaries gene_list)) + +List.map (fun (_, s) -> String.length s mod 3) (List.filter (fun (s, _) -> s <> Gene_prediction_2.NotGene) td)
orbitz/glitter
2191d306539f31a780b61436aa273aec5ae65cc0
Broken, but making progress in the right direction
diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index 08b2f41..a3b8cdb 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,71 +1,73 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with - Some (Fasta.Sequence d) -> Some ((oe + 1, oe + String_ext.length d), d) + Some (Fasta.Sequence d) -> + let oe' = oe + 1 in + Some ((oe', oe' + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with - Some ((0, 0), _h) -> read_next f 0 + Some ((0, 0), _h) -> read_next f (-1) | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> [< '(NotGene, d); read_next (ctd []) e >] | (gs, _ge)::_gbs when s < gs && gs <= e -> let subd = String_ext.sub d 0 (gs - s) in let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::gbs when gs <= s && ge < e -> let subd = String_ext.sub d 0 (ge - s) in let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, ge)::gbs when s = gs && ge = e -> [< '(Gene, d); read_next (ctd gbs) e >] | (gs, ge)::_gbs when s = gs && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when e < gs -> [< '(NotGene, d); read_next (ctd gb) e >] | (gs, ge)::_gbs when gs < s && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in - read_next (ctd gene_boundaries) 0 + read_next (ctd gene_boundaries) (-1) diff --git a/lib/gene_prediction_7.ml b/lib/gene_prediction_7.ml index fad312f..61c5adc 100644 --- a/lib/gene_prediction_7.ml +++ b/lib/gene_prediction_7.ml @@ -1,59 +1,59 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | A | T | G | C1 | C2 | C3 (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let rec gene_start d sin = if String_ext.length d < 3 then match Seq.next sin with Some (Gene_prediction_2.Gene, d') -> gene_start (d ^ d') sin | Some (Gene_prediction_2.NotGene, _) -> raise (Failure "At start of gene and gene end, wuuut?") - | None -> + | _ -> raise (Failure "At start of gene and sequence end, wuuuut?") else let (l, d) = Hmm.labeled_of_string_all [A; T; G;] d in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let split_gene gd = let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = gene_start d sin in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin diff --git a/lib/test.ml b/lib/test.ml index 72f1242..543996c 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,83 +1,86 @@ (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) (* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) (* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) (* ; (One, Misc_lib.list_of_string "ATT") *) (* ; (Two, Misc_lib.list_of_string "CGATTCT") *) (* ; (One, Misc_lib.list_of_string "ACGCGC") *) (* ; (Two, Misc_lib.list_of_string "GTAT") *) (* ; (One, Misc_lib.list_of_string "ACTAGCT") *) (* ; (Two, Misc_lib.list_of_string "TATC") *) (* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) -let genes ng sg = - List.map - (fun s -> - if s <> sg && s <> ng then - sg - else - s) +let genes ng sg l = + Seq.to_list (Seq.map + (fun s -> + if s <> sg && s <> ng then + sg + else + s) + (Seq.of_list l)) -module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) +module H = Hmm.Make(struct type s = Gene_prediction_2.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" -let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) -let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) -let hmm = H.train Gene_prediction_4.Q0 training_data -let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm +let td = Seq.to_list (Gene_prediction_2.create_training_data gene_boundaries fasta) +(* let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) *) +(* let hmm = H.train Gene_prediction_4.Q0 training_data *) +(* let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm *) +(* let gene_list = genes Gene_prediction_4.NotGene Gene_prediction_4.C1 path *) +(* let count = List.length (List.filter (fun (s, _) -> s <> Gene_prediction_4.NotGene) (Misc_lib.boundaries gene_list)) *)
orbitz/glitter
51ab51273c2468449870cd0109e90b54d3db57ec
Adding support to make it easier to constructs HMMs
diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml index 749c273..04c45e4 100644 --- a/lib/gene_prediction_4.ml +++ b/lib/gene_prediction_4.ml @@ -1,52 +1,46 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | C1 | C2 | C3 (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let split_gene gd = - let rec sg acc gd = - let l = String_ext.length gd in - if l < 3 then - (Seq.of_list (List.rev acc), gd) - else - sg ((C3, String_ext.make 1 gd.[2])::(C2, String_ext.make 1 gd.[1])::(C1, String_ext.make 1 gd.[0])::acc) (String_ext.sub gd 3 (l - 3)) - in - sg [] gd + let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in + (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) in let rec ctd d sin = if d = "" then begin match Seq.next sin with Some (Gene_prediction_2.NotGene, d) -> [< '(NotGene, d); ctd "" sin >] | Some (Gene_prediction_2.Gene, d) -> let (c, d') = split_gene d in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> [< >] end else begin match Seq.next sin with Some (Gene_prediction_2.NotGene, _) -> raise (Failure ("Expecting a gene: d: " ^ d)) | Some (Gene_prediction_2.Gene, v) -> let (c, d') = split_gene (d ^ v) in [< c; ctd d' sin >] | Some (Gene_prediction_2.Q0, _) -> raise (Failure "Not supposed to happen") | None -> raise (Failure "Expecting more gene data but got nothing") end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin diff --git a/lib/gene_prediction_7.ml b/lib/gene_prediction_7.ml new file mode 100644 index 0000000..fad312f --- /dev/null +++ b/lib/gene_prediction_7.ml @@ -0,0 +1,59 @@ +(* 4 state hmm *) + +type coding_state = Q0 | NotGene | A | T | G | C1 | C2 | C3 + + +(* + * This creates our training. The algorithm here uses + * the trainer for gene_prediction_2 and then takes the + * results and cuts them into 3 state pieces representing + * the codons + *) +let create_training_data gene_boundaries fin = + let rec gene_start d sin = + if String_ext.length d < 3 then + match Seq.next sin with + Some (Gene_prediction_2.Gene, d') -> + gene_start (d ^ d') sin + | Some (Gene_prediction_2.NotGene, _) -> + raise (Failure "At start of gene and gene end, wuuut?") + | None -> + raise (Failure "At start of gene and sequence end, wuuuut?") + else + let (l, d) = Hmm.labeled_of_string_all [A; T; G;] d in + (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) + in + let split_gene gd = + let (l, d) = Hmm.labeled_of_string_all [C1; C2; C3] gd in + (Seq.of_list (List.map (fun (label, c) -> (label, String_ext.make 1 c)) l), d) + in + let rec ctd d sin = + if d = "" then + begin + match Seq.next sin with + Some (Gene_prediction_2.NotGene, d) -> + [< '(NotGene, d); ctd "" sin >] + | Some (Gene_prediction_2.Gene, d) -> + let (c, d') = gene_start d sin in + [< c; ctd d' sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + [< >] + end + else + begin + match Seq.next sin with + Some (Gene_prediction_2.NotGene, _) -> + raise (Failure ("Expecting a gene: d: " ^ d)) + | Some (Gene_prediction_2.Gene, v) -> + let (c, d') = split_gene (d ^ v) in + [< c; ctd d' sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + raise (Failure "Expecting more gene data but got nothing") + end + in + let sin = Gene_prediction_2.create_training_data gene_boundaries fin in + ctd "" sin diff --git a/lib/hmm.ml b/lib/hmm.ml index 70084df..59e6b65 100644 --- a/lib/hmm.ml +++ b/lib/hmm.ml @@ -1,244 +1,278 @@ (* * Tools to construct and HMM and perform calculations on it *) -module type Ordered_type = +module type Hmm_type = sig type s type a val compare: s -> s -> int end module Make = - functor (Elt : Ordered_type) -> + functor (Elt : Hmm_type) -> struct type state = Elt.s type alphabet = Elt.a type probability = float type transition = state * (state * probability) list type emission = state * (alphabet * probability) list module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) type hmm_state = { transitions : transition list ; emissions : emission list ; start_end : state } (* misc function for calculating a random weight *) let random_by_weight l = let rec get_random a v = function [] -> raise (Failure "You didn't represent all your base....") | (s, x)::xs -> let a = a + int_of_float (x *. 1000.0) in if v <= a then s else get_random a v xs in get_random 0 (Random.int 1001) l (* a misc funciton to work on lists *) let rec drop_while f = function [] -> [] | x::xs when f x -> x::xs | _::xs -> drop_while f xs let get_transitions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) let get_transition hmm s1 s2 = List.assoc s2 (get_transitions hmm s1) let get_transition_def hmm s1 s2 def = try get_transition hmm s1 s2 with Not_found -> def let get_states_by_emission hmm e = List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) let get_emissions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) let get_emission hmm s1 s2 = List.assoc s2 (get_emissions hmm s1) let get_emission_def hmm s1 s2 def = List.assoc s2 (get_emissions hmm s1) let get_random_transition hmm s = random_by_weight (get_transitions hmm s) let get_random_emission hmm s = random_by_weight (get_emissions hmm s) let get_states hmm = List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) let make t e se = { transitions = t ; emissions = e ; start_end = se } let sample_emission hmm = let rec samp acc s = let ns = get_random_transition hmm s in if ns = hmm.start_end then acc else samp ((get_random_emission hmm ns)::acc) ns in samp [] hmm.start_end let sample_emission_seq hmm = let rec samp s = let ns = get_random_transition hmm s in if ns = hmm.start_end then [< >] else let o = get_random_emission hmm ns in [< 'o; samp ns >] in samp hmm.start_end let prob_of_sequence hmm seq = let rec p_of_s s = function [] -> snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) | x::xs -> let trans = get_transitions hmm s in let (ts, tp) = List.hd (drop_while (fun s -> List.mem_assoc x (get_emissions hmm (fst s))) trans) in let ep = List.assoc x (get_emissions hmm ts) in tp *. ep *. p_of_s ts xs in p_of_s hmm.start_end seq (* * Calculates viterbi path + probabilities * returns (total probability, path, probability of path) *) let forward_viterbi obs hmm = let logsum x y = x +. log (1. +. exp (y -. x)) in let calc_max t ob ns (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let p = log (get_emission_def hmm s ob 0.0) +. log (get_transition_def hmm s ns 0.0) in let prob = prob +. p in let v_prob = v_prob +. p in let total = if total = neg_infinity then prob else logsum total prob in if v_prob > valmax then (total, ns :: v_path, v_prob) else (total, argmax, valmax) in let accum_stats t ob u ns = let states = get_states hmm in StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u in let walk_states t ob = List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) in let walk_obs t = Seq.fold_left walk_states t obs in let make_t = List.fold_left (fun t s -> let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in StateMap.add s (start_p, [s], start_p) t) StateMap.empty (get_states hmm) in let find_max t (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let total = logsum total prob in if v_prob > valmax then (total, v_path, v_prob) else (total, argmax, valmax) in let t = walk_obs make_t in let states = get_states hmm in let (total, v_path, v_prob) = List.fold_left (find_max t) (StateMap.find (List.hd states) t) (List.tl states) in (exp total, List.rev v_path, exp v_prob) (* * Train an HMM given an input sequence. Sequence is lazy * this also needs to know the start_end state for training *) type hmm_builder = { trans : (state * int32) list StateMap.t ; emiss : (alphabet * int32) list StateMap.t ; se : state } let update_m m ss vk = try let v = StateMap.find ss m in try let c = List.assoc vk v in StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m with Not_found -> StateMap.add ss ((vk, Int32.of_int 1)::v) m with Not_found -> StateMap.add ss [(vk, Int32.of_int 1)] m let train start_end seq = let rec train' ps cs hmm_b = function [] -> begin match Seq.next seq with Some (s, d) when s = cs -> train' ps cs hmm_b d | Some (s, d) -> train' cs s hmm_b d | None -> {hmm_b with trans = update_m hmm_b.trans cs start_end} end | x::xs -> train' cs cs {hmm_b with trans = update_m hmm_b.trans ps cs ; emiss = update_m hmm_b.emiss cs x } xs in let make_probabilities trans = StateMap.fold (fun k v a -> let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) trans [] in let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end end + +(* + * These are HMM related functions but do not depend on the functor data as they are more general. + *) + + +(* + * Because it is common to be working with strings (especially for DNA/Protein sequences where every char is an element) + * this is a simple function to apply training data to each element in the string + * This takes a string and a list of labels to apply. It will only apply labels if the string is large enough for all + * of the labels to be applied. + * a Some (labeled, rest) is returned on success, None otherwise. This does not apply it recursively. use '_all' + * variant of the function for that + *) + +let labeled_of_string labels s = + if List.length labels <= String_ext.length s then + let ll = List.length labels in + Some (Misc_lib.zip labels (Misc_lib.list_of_string (String_ext.sub s 0 ll)), + String_ext.sub s ll (String_ext.length s - ll)) + else + None + +(* + * This is labeled_of_string, but it will consume + * as much of the string as it can + *) +let labeled_of_string_all labels s = + let rec f acc s = + match labeled_of_string labels s with + Some (l, s) -> f (l @ acc) s + | None -> (acc, s) + in + f [] s diff --git a/lib/misc_lib.ml b/lib/misc_lib.ml index cac435c..19ba09a 100644 --- a/lib/misc_lib.ml +++ b/lib/misc_lib.ml @@ -1,24 +1,36 @@ +(* Very expensive function for what it does, but easy implementation *) +let list_of_string s = Seq.to_list (Seq.of_string s) + let uniq l = List.rev (List.fold_left (fun acc e -> match acc with [] -> [e] | x::_xs when e = x -> acc | x::_xs -> e::acc) [] l) let boundaries l = List.rev (Seq.fold_left (fun acc (idx, e) -> match acc with [] -> [(e, (idx, idx))] | (s, (x, y))::accs when s = e -> (s, (x, idx))::accs | (s, (x, y))::accs -> (e, (idx, idx))::(s, (x, idx))::accs) [] (Seq.enumerate (Seq.of_list l))) + + +let rec zip l1 l2 = + match (l1, l2) with + (x1::x1s, x2::x2s) -> + (x1, x2)::zip x1s x2s + | _ -> + [] + diff --git a/lib/test.ml b/lib/test.ml index a65e3c9..72f1242 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,73 +1,83 @@ -let list_of_string s = Seq.to_list (Seq.of_string s) - (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) -(* let training_data = [ (One, list_of_string "CGATATT") *) -(* ; (Two, list_of_string "CGATTCT") *) -(* ; (One, list_of_string "ACGCGC") *) -(* ; (Two, list_of_string "GTAT") *) -(* ; (One, list_of_string "ACTAGCT") *) -(* ; (Two, list_of_string "TATC") *) -(* ; (One, list_of_string "TGATC") *) +(* let training_data = [ (One, Misc_lib.list_of_string "CGATATT") *) +(* ; (Two, Misc_lib.list_of_string "CGATTCT") *) +(* ; (One, Misc_lib.list_of_string "ACGCGC") *) +(* ; (Two, Misc_lib.list_of_string "GTAT") *) +(* ; (One, Misc_lib.list_of_string "ACTAGCT") *) +(* ; (Two, Misc_lib.list_of_string "TATC") *) +(* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) -(* let training_data = [ (One, list_of_string "CGAT") *) -(* ; (One, list_of_string "ATT") *) -(* ; (Two, list_of_string "CGATTCT") *) -(* ; (One, list_of_string "ACGCGC") *) -(* ; (Two, list_of_string "GTAT") *) -(* ; (One, list_of_string "ACTAGCT") *) -(* ; (Two, list_of_string "TATC") *) -(* ; (One, list_of_string "TGATC") *) +(* let training_data = [ (One, Misc_lib.list_of_string "CGAT") *) +(* ; (One, Misc_lib.list_of_string "ATT") *) +(* ; (Two, Misc_lib.list_of_string "CGATTCT") *) +(* ; (One, Misc_lib.list_of_string "ACGCGC") *) +(* ; (Two, Misc_lib.list_of_string "GTAT") *) +(* ; (One, Misc_lib.list_of_string "ACTAGCT") *) +(* ; (Two, Misc_lib.list_of_string "TATC") *) +(* ; (One, Misc_lib.list_of_string "TGATC") *) (* ] *) +let genes ng sg = + List.map + (fun s -> + if s <> sg && s <> ng then + sg + else + s) + + + module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) -let training_data = Seq.map (fun (s, v) -> (s, list_of_string v)) (Seq.of_list td) +let training_data = Seq.map (fun (s, v) -> (s, Misc_lib.list_of_string v)) (Seq.of_list td) let hmm = H.train Gene_prediction_4.Q0 training_data let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm + +
orbitz/glitter
1ad99528d38583a8121f731ef36fd7aed13daa3a
Adding new state functionality
diff --git a/lib/fasta.ml b/lib/fasta.ml index 7f64ede..c62f5b7 100644 --- a/lib/fasta.ml +++ b/lib/fasta.ml @@ -1,69 +1,69 @@ (* A fasta sequence has a header and a sequence *) type fasta = Header of string | Sequence of string let rec read_fasta_sequence f curdata sin = if curdata = "" then match Seq.next sin with Some d -> read_fasta_sequence f d sin | None -> [< >] else if String_ext.contains curdata '>' && String_ext.index curdata '>' > 0 then let idx = String_ext.index curdata '>' in let s = String_ext.sub curdata 0 (idx - 1) in let r = String_ext.sub curdata idx (String_ext.length curdata - idx) in [< 'Sequence s; f r sin >] else if String_ext.contains curdata '>' then - [< f curdata >] + [< f curdata sin >] else if String_ext.contains curdata '\n' then read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else [< 'Sequence curdata; read_fasta_sequence f "" sin >] let rec extract_header curdata sin = if String_ext.contains curdata '\n' then let idx = String_ext.index curdata '\n' in (String_ext.sub curdata 0 idx, String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) else match Seq.next sin with Some d -> extract_header (curdata ^ d) sin | None -> (curdata, "") (* * Expects to read either an empty line or a fasta header *) let rec read_fasta_header curdata sin = let tcurdata = String_ext.trim curdata in if tcurdata <> "" && tcurdata.[0] = '>' then let (header, rest) = extract_header curdata sin in [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] else match Seq.next sin with Some d -> read_fasta_header (curdata ^ d) sin | None -> raise (Failure ("Unknown data: " ^ curdata)) (* * Reads from a stream. It returns a lazy sequnece of * Header or Sequence elements. Throws an exception on bad input * The sequence will be returned in chunks until the stream is empty * or another Header is found *) let read sin = read_fasta_header "" sin let read_file ?(chunk_size = 1000) fname = read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) let rec to_seq sin = match Seq.next sin with Some (Sequence d) -> [< Seq.of_string d; to_seq sin >] - | Some (Header h) -> - [< >] + | Some (Header _) -> + to_seq sin | None -> [< >] diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml index 3608bb9..08b2f41 100644 --- a/lib/gene_prediction_2.ml +++ b/lib/gene_prediction_2.ml @@ -1,71 +1,71 @@ (* 2 state HMM *) type coding_state = Q0 | NotGene | Gene (* * If the next to read in the fasta file is a header it returns * Some ((0, 0), header value) * If a sequence * Some ((s, e), sequence data) * If the sequence is done * None *) let read_sequence_with_boundaries oe fin = match Seq.next fin with Some (Fasta.Sequence d) -> Some ((oe + 1, oe + String_ext.length d), d) | Some (Fasta.Header h) -> Some ((0, 0), h) | None -> None let remove_overlap l = let rec ro' acc = function [] -> acc | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> ro' acc gbs | xs::gbs -> ro' (xs::acc) gbs in List.rev (ro' [] l) (* * Returns a stream of training data *) let create_training_data gene_boundaries fin = let rec read_next f oe = match read_sequence_with_boundaries oe fin with Some ((0, 0), _h) -> read_next f 0 | Some ((s, e), d) -> f (s, e) d | None -> [< >] in let rec ctd gb (s, e) d = try match gb with [] -> [< '(NotGene, d); read_next (ctd []) e >] | (gs, _ge)::_gbs when s < gs && gs <= e -> let subd = String_ext.sub d 0 (gs - s) in - let restd = String_ext.sub d (gs - s + 1) (String_ext.length d - (gs - s + 1)) in - [< '(NotGene, subd); ctd gb (gs + 1, e) restd >] + let restd = String_ext.sub d (gs - s) (String_ext.length d - (gs - s)) in + [< '(NotGene, subd); ctd gb (gs, e) restd >] | (gs, ge)::gbs when gs <= s && ge < e -> let subd = String_ext.sub d 0 (ge - s) in - let restd = String_ext.sub d (ge - s + 1) (String_ext.length d - (ge - s + 1)) in - [< '(Gene, subd); ctd gbs (ge + 1, e) restd >] + let restd = String_ext.sub d (ge - s) (String_ext.length d - (ge - s)) in + [< '(Gene, subd); ctd gbs (ge, e) restd >] | (gs, ge)::gbs when s = gs && ge = e -> [< '(Gene, d); read_next (ctd gbs) e >] | (gs, ge)::_gbs when s = gs && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, _ge)::_gbs when e < gs -> [< '(NotGene, d); read_next (ctd gb) e >] | (gs, ge)::_gbs when gs < s && e < ge -> [< '(Gene, d); read_next (ctd gb) e >] | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) with Invalid_argument _ -> raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) in let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in read_next (ctd gene_boundaries) 0 diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml index 97b2057..749c273 100644 --- a/lib/gene_prediction_4.ml +++ b/lib/gene_prediction_4.ml @@ -1,51 +1,52 @@ (* 4 state hmm *) type coding_state = Q0 | NotGene | C1 | C2 | C3 (* * This creates our training. The algorithm here uses * the trainer for gene_prediction_2 and then takes the * results and cuts them into 3 state pieces representing * the codons *) let create_training_data gene_boundaries fin = let split_gene gd = let rec sg acc gd = let l = String_ext.length gd in if l < 3 then (Seq.of_list (List.rev acc), gd) else sg ((C3, String_ext.make 1 gd.[2])::(C2, String_ext.make 1 gd.[1])::(C1, String_ext.make 1 gd.[0])::acc) (String_ext.sub gd 3 (l - 3)) in sg [] gd in let rec ctd d sin = - match d with - "" -> - begin - match Seq.next sin with - Some (Gene_prediction_2.NotGene, d) -> - [< '(NotGene, d); ctd "" sin >] - | Some (Gene_prediction_2.Gene, d) -> - let (c, d) = split_gene d in - [< c; ctd d sin >] - | Some (Gene_prediction_2.Q0, _) -> - raise (Failure "Not supposed to happen") - | None -> - [< >] - end - | d -> - match Seq.next sin with - Some (Gene_prediction_2.NotGene, _) -> - raise (Failure ("Expecting a gene: d: " ^ d)) - | Some (Gene_prediction_2.Gene, v) -> - let (c, d) = split_gene (d ^ v) in - [< c; ctd d sin >] - | Some (Gene_prediction_2.Q0, _) -> - raise (Failure "Not supposed to happen") - | None -> - raise (Failure "Expecting more gene data but got nothing") + if d = "" then + begin + match Seq.next sin with + Some (Gene_prediction_2.NotGene, d) -> + [< '(NotGene, d); ctd "" sin >] + | Some (Gene_prediction_2.Gene, d) -> + let (c, d') = split_gene d in + [< c; ctd d' sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + [< >] + end + else + begin + match Seq.next sin with + Some (Gene_prediction_2.NotGene, _) -> + raise (Failure ("Expecting a gene: d: " ^ d)) + | Some (Gene_prediction_2.Gene, v) -> + let (c, d') = split_gene (d ^ v) in + [< c; ctd d' sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + raise (Failure "Expecting more gene data but got nothing") + end in let sin = Gene_prediction_2.create_training_data gene_boundaries fin in ctd "" sin diff --git a/lib/hmm.ml b/lib/hmm.ml index 054c718..70084df 100644 --- a/lib/hmm.ml +++ b/lib/hmm.ml @@ -1,244 +1,244 @@ (* * Tools to construct and HMM and perform calculations on it *) module type Ordered_type = sig type s type a val compare: s -> s -> int end module Make = functor (Elt : Ordered_type) -> struct type state = Elt.s type alphabet = Elt.a type probability = float type transition = state * (state * probability) list type emission = state * (alphabet * probability) list module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) type hmm_state = { transitions : transition list ; emissions : emission list ; start_end : state } (* misc function for calculating a random weight *) let random_by_weight l = let rec get_random a v = function [] -> raise (Failure "You didn't represent all your base....") | (s, x)::xs -> let a = a + int_of_float (x *. 1000.0) in if v <= a then s else get_random a v xs in get_random 0 (Random.int 1001) l (* a misc funciton to work on lists *) let rec drop_while f = function [] -> [] | x::xs when f x -> x::xs | _::xs -> drop_while f xs let get_transitions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) let get_transition hmm s1 s2 = List.assoc s2 (get_transitions hmm s1) let get_transition_def hmm s1 s2 def = try get_transition hmm s1 s2 with Not_found -> def let get_states_by_emission hmm e = List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) let get_emissions hmm s = List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) let get_emission hmm s1 s2 = List.assoc s2 (get_emissions hmm s1) let get_emission_def hmm s1 s2 def = List.assoc s2 (get_emissions hmm s1) let get_random_transition hmm s = random_by_weight (get_transitions hmm s) let get_random_emission hmm s = random_by_weight (get_emissions hmm s) let get_states hmm = List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) let make t e se = { transitions = t ; emissions = e ; start_end = se } let sample_emission hmm = let rec samp acc s = let ns = get_random_transition hmm s in if ns = hmm.start_end then acc else samp ((get_random_emission hmm ns)::acc) ns in samp [] hmm.start_end let sample_emission_seq hmm = let rec samp s = let ns = get_random_transition hmm s in if ns = hmm.start_end then [< >] else let o = get_random_emission hmm ns in [< 'o; samp ns >] in samp hmm.start_end let prob_of_sequence hmm seq = let rec p_of_s s = function [] -> snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) | x::xs -> let trans = get_transitions hmm s in let (ts, tp) = List.hd (drop_while (fun s -> List.mem_assoc x (get_emissions hmm (fst s))) trans) in let ep = List.assoc x (get_emissions hmm ts) in tp *. ep *. p_of_s ts xs in p_of_s hmm.start_end seq (* * Calculates viterbi path + probabilities * returns (total probability, path, probability of path) *) let forward_viterbi obs hmm = let logsum x y = x +. log (1. +. exp (y -. x)) in let calc_max t ob ns (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in - let p = log (get_emission hmm s ob) +. log (get_transition hmm s ns) in + let p = log (get_emission_def hmm s ob 0.0) +. log (get_transition_def hmm s ns 0.0) in let prob = prob +. p in let v_prob = v_prob +. p in let total = if total = neg_infinity then prob else logsum total prob in if v_prob > valmax then (total, ns :: v_path, v_prob) else (total, argmax, valmax) in let accum_stats t ob u ns = let states = get_states hmm in StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u in let walk_states t ob = List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) in let walk_obs t = Seq.fold_left walk_states t obs in let make_t = List.fold_left (fun t s -> let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in StateMap.add s (start_p, [s], start_p) t) StateMap.empty (get_states hmm) in let find_max t (total, argmax, valmax) s = let (prob, v_path, v_prob) = StateMap.find s t in let total = logsum total prob in if v_prob > valmax then (total, v_path, v_prob) else (total, argmax, valmax) in let t = walk_obs make_t in let states = get_states hmm in let (total, v_path, v_prob) = List.fold_left (find_max t) (StateMap.find (List.hd states) t) (List.tl states) in (exp total, List.rev v_path, exp v_prob) (* * Train an HMM given an input sequence. Sequence is lazy * this also needs to know the start_end state for training *) type hmm_builder = { trans : (state * int32) list StateMap.t ; emiss : (alphabet * int32) list StateMap.t ; se : state } let update_m m ss vk = try let v = StateMap.find ss m in try let c = List.assoc vk v in StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m with Not_found -> StateMap.add ss ((vk, Int32.of_int 1)::v) m with Not_found -> StateMap.add ss [(vk, Int32.of_int 1)] m let train start_end seq = let rec train' ps cs hmm_b = function [] -> begin match Seq.next seq with Some (s, d) when s = cs -> train' ps cs hmm_b d | Some (s, d) -> train' cs s hmm_b d | None -> {hmm_b with trans = update_m hmm_b.trans cs start_end} end | x::xs -> train' cs cs {hmm_b with trans = update_m hmm_b.trans ps cs ; emiss = update_m hmm_b.emiss cs x } xs in let make_probabilities trans = StateMap.fold (fun k v a -> let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) trans [] in let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end end diff --git a/lib/misc_lib.ml b/lib/misc_lib.ml index 220ac99..cac435c 100644 --- a/lib/misc_lib.ml +++ b/lib/misc_lib.ml @@ -1,12 +1,24 @@ let uniq l = List.rev (List.fold_left (fun acc e -> match acc with [] -> [e] | x::_xs when e = x -> acc | x::_xs -> e::acc) [] l) +let boundaries l = + List.rev (Seq.fold_left + (fun acc (idx, e) -> + match acc with + [] -> + [(e, (idx, idx))] + | (s, (x, y))::accs when s = e -> + (s, (x, idx))::accs + | (s, (x, y))::accs -> + (e, (idx, idx))::(s, (x, idx))::accs) + [] + (Seq.enumerate (Seq.of_list l))) diff --git a/lib/test.ml b/lib/test.ml index d2c128d..a65e3c9 100644 --- a/lib/test.ml +++ b/lib/test.ml @@ -1,76 +1,73 @@ let list_of_string s = Seq.to_list (Seq.of_string s) (* type states = Q0 | Q1 | Q2 *) (* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) (* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) (* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) (* ] *) (* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) (* ; (Q2, [ ('R', 1.0) ]) *) (* ] *) (* type states = Q0 | Rainy | Sunny *) (* type alphabet = Walk | Shop | Clean *) (* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) (* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) (* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) (* ] *) (* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) (* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) (* ] *) (* let observations = [ Walk; Shop; Clean ] *) (* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) (* let hmm = H.make transitions emissions Q0 *) (* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) -(* let () = let _ = fv in () *) - (* type states = Q0 | One | Two *) (* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) (* let training_data = [ (One, list_of_string "CGATATT") *) (* ; (Two, list_of_string "CGATTCT") *) (* ; (One, list_of_string "ACGCGC") *) (* ; (Two, list_of_string "GTAT") *) (* ; (One, list_of_string "ACTAGCT") *) (* ; (Two, list_of_string "TATC") *) (* ; (One, list_of_string "TGATC") *) (* ] *) (* let training_data = [ (One, list_of_string "CGAT") *) (* ; (One, list_of_string "ATT") *) (* ; (Two, list_of_string "CGATTCT") *) (* ; (One, list_of_string "ACGCGC") *) (* ; (Two, list_of_string "GTAT") *) (* ; (One, list_of_string "ACTAGCT") *) (* ; (Two, list_of_string "TATC") *) (* ; (One, list_of_string "TGATC") *) (* ] *) module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) let training_data = Seq.map (fun (s, v) -> (s, list_of_string v)) (Seq.of_list td) let hmm = H.train Gene_prediction_4.Q0 training_data -let viterbi_results = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm - +let (total, path, prob) = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm
orbitz/glitter
501a6f37465c088172acfd5e01398d0b2407b1b8
Fixing fasta support
diff --git a/lib/fasta.ml b/lib/fasta.ml index e359b51..7f64ede 100644 --- a/lib/fasta.ml +++ b/lib/fasta.ml @@ -1,67 +1,69 @@ (* A fasta sequence has a header and a sequence *) type fasta = Header of string | Sequence of string let rec read_fasta_sequence f curdata sin = if curdata = "" then match Seq.next sin with Some d -> read_fasta_sequence f d sin | None -> [< >] - else if String_ext.contains curdata '>' then + else if String_ext.contains curdata '>' && String_ext.index curdata '>' > 0 then let idx = String_ext.index curdata '>' in let s = String_ext.sub curdata 0 (idx - 1) in let r = String_ext.sub curdata idx (String_ext.length curdata - idx) in [< 'Sequence s; f r sin >] + else if String_ext.contains curdata '>' then + [< f curdata >] else if String_ext.contains curdata '\n' then read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else [< 'Sequence curdata; read_fasta_sequence f "" sin >] let rec extract_header curdata sin = if String_ext.contains curdata '\n' then let idx = String_ext.index curdata '\n' in (String_ext.sub curdata 0 idx, String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) else match Seq.next sin with Some d -> extract_header (curdata ^ d) sin | None -> (curdata, "") (* * Expects to read either an empty line or a fasta header *) let rec read_fasta_header curdata sin = let tcurdata = String_ext.trim curdata in if tcurdata <> "" && tcurdata.[0] = '>' then let (header, rest) = extract_header curdata sin in [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] else match Seq.next sin with Some d -> read_fasta_header (curdata ^ d) sin | None -> raise (Failure ("Unknown data: " ^ curdata)) (* * Reads from a stream. It returns a lazy sequnece of * Header or Sequence elements. Throws an exception on bad input * The sequence will be returned in chunks until the stream is empty * or another Header is found *) let read sin = read_fasta_header "" sin let read_file ?(chunk_size = 1000) fname = read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) let rec to_seq sin = match Seq.next sin with Some (Sequence d) -> [< Seq.of_string d; to_seq sin >] | Some (Header h) -> [< >] | None -> [< >]
orbitz/glitter
026199539cd6002d413dccd1ce89424e026cc9d0
Fixed newline issue
diff --git a/lib/fasta.ml b/lib/fasta.ml index 6de4984..e359b51 100644 --- a/lib/fasta.ml +++ b/lib/fasta.ml @@ -1,67 +1,67 @@ (* A fasta sequence has a header and a sequence *) type fasta = Header of string | Sequence of string let rec read_fasta_sequence f curdata sin = if curdata = "" then match Seq.next sin with Some d -> read_fasta_sequence f d sin | None -> [< >] else if String_ext.contains curdata '>' then let idx = String_ext.index curdata '>' in - let s = String_ext.sub curdata 0 idx in + let s = String_ext.sub curdata 0 (idx - 1) in let r = String_ext.sub curdata idx (String_ext.length curdata - idx) in [< 'Sequence s; f r sin >] else if String_ext.contains curdata '\n' then read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else [< 'Sequence curdata; read_fasta_sequence f "" sin >] let rec extract_header curdata sin = if String_ext.contains curdata '\n' then let idx = String_ext.index curdata '\n' in (String_ext.sub curdata 0 idx, String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) else match Seq.next sin with Some d -> extract_header (curdata ^ d) sin | None -> (curdata, "") (* * Expects to read either an empty line or a fasta header *) let rec read_fasta_header curdata sin = let tcurdata = String_ext.trim curdata in if tcurdata <> "" && tcurdata.[0] = '>' then let (header, rest) = extract_header curdata sin in [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] else match Seq.next sin with Some d -> read_fasta_header (curdata ^ d) sin | None -> raise (Failure ("Unknown data: " ^ curdata)) (* * Reads from a stream. It returns a lazy sequnece of * Header or Sequence elements. Throws an exception on bad input * The sequence will be returned in chunks until the stream is empty * or another Header is found *) let read sin = read_fasta_header "" sin let read_file ?(chunk_size = 1000) fname = read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) let rec to_seq sin = match Seq.next sin with Some (Sequence d) -> [< Seq.of_string d; to_seq sin >] | Some (Header h) -> [< >] | None -> [< >]
orbitz/glitter
7e684ff0bc6da8b12313043e0654c6e6306bfad3
Wrong order
diff --git a/lib/fasta.ml b/lib/fasta.ml index dac165b..6de4984 100644 --- a/lib/fasta.ml +++ b/lib/fasta.ml @@ -1,67 +1,67 @@ (* A fasta sequence has a header and a sequence *) type fasta = Header of string | Sequence of string let rec read_fasta_sequence f curdata sin = if curdata = "" then match Seq.next sin with Some d -> read_fasta_sequence f d sin | None -> [< >] - else if String_ext.contains curdata '\n' then - read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else if String_ext.contains curdata '>' then let idx = String_ext.index curdata '>' in let s = String_ext.sub curdata 0 idx in let r = String_ext.sub curdata idx (String_ext.length curdata - idx) in [< 'Sequence s; f r sin >] + else if String_ext.contains curdata '\n' then + read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else [< 'Sequence curdata; read_fasta_sequence f "" sin >] let rec extract_header curdata sin = if String_ext.contains curdata '\n' then let idx = String_ext.index curdata '\n' in (String_ext.sub curdata 0 idx, String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) else match Seq.next sin with Some d -> extract_header (curdata ^ d) sin | None -> (curdata, "") (* * Expects to read either an empty line or a fasta header *) let rec read_fasta_header curdata sin = let tcurdata = String_ext.trim curdata in if tcurdata <> "" && tcurdata.[0] = '>' then let (header, rest) = extract_header curdata sin in [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] else match Seq.next sin with Some d -> read_fasta_header (curdata ^ d) sin | None -> raise (Failure ("Unknown data: " ^ curdata)) (* * Reads from a stream. It returns a lazy sequnece of * Header or Sequence elements. Throws an exception on bad input * The sequence will be returned in chunks until the stream is empty * or another Header is found *) let read sin = read_fasta_header "" sin let read_file ?(chunk_size = 1000) fname = read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) let rec to_seq sin = match Seq.next sin with Some (Sequence d) -> [< Seq.of_string d; to_seq sin >] | Some (Header h) -> [< >] | None -> [< >]
orbitz/glitter
4854dd52ff06ab56e36c2d14a56da77943ef03f3
Didn't mean a +1 there
diff --git a/lib/fasta.ml b/lib/fasta.ml index ce45c4b..dac165b 100644 --- a/lib/fasta.ml +++ b/lib/fasta.ml @@ -1,67 +1,67 @@ (* A fasta sequence has a header and a sequence *) type fasta = Header of string | Sequence of string let rec read_fasta_sequence f curdata sin = if curdata = "" then match Seq.next sin with Some d -> read_fasta_sequence f d sin | None -> [< >] else if String_ext.contains curdata '\n' then read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin else if String_ext.contains curdata '>' then let idx = String_ext.index curdata '>' in let s = String_ext.sub curdata 0 idx in - let r = String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1)) in + let r = String_ext.sub curdata idx (String_ext.length curdata - idx) in [< 'Sequence s; f r sin >] else [< 'Sequence curdata; read_fasta_sequence f "" sin >] let rec extract_header curdata sin = if String_ext.contains curdata '\n' then let idx = String_ext.index curdata '\n' in (String_ext.sub curdata 0 idx, String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) else match Seq.next sin with Some d -> extract_header (curdata ^ d) sin | None -> (curdata, "") (* * Expects to read either an empty line or a fasta header *) let rec read_fasta_header curdata sin = let tcurdata = String_ext.trim curdata in if tcurdata <> "" && tcurdata.[0] = '>' then let (header, rest) = extract_header curdata sin in [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] else match Seq.next sin with Some d -> read_fasta_header (curdata ^ d) sin | None -> raise (Failure ("Unknown data: " ^ curdata)) (* * Reads from a stream. It returns a lazy sequnece of * Header or Sequence elements. Throws an exception on bad input * The sequence will be returned in chunks until the stream is empty * or another Header is found *) let read sin = read_fasta_header "" sin let read_file ?(chunk_size = 1000) fname = read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) let rec to_seq sin = match Seq.next sin with Some (Sequence d) -> [< Seq.of_string d; to_seq sin >] | Some (Header h) -> [< >] | None -> [< >]
orbitz/glitter
1312cfa6c4a7932fe184657e0850e1f9b587da46
Adding README
diff --git a/README b/README new file mode 100644 index 0000000..8645614 --- /dev/null +++ b/README @@ -0,0 +1 @@ +GLITTER is an implementation of GLIMMER the popular prokaryotic gene finding tool written in Ocaml \ No newline at end of file
orbitz/glitter
ccb21bae20d510577030fdd75a58999da66c8018
Adding code
diff --git a/lib/csv.ml b/lib/csv.ml new file mode 100644 index 0000000..f0065c7 --- /dev/null +++ b/lib/csv.ml @@ -0,0 +1,114 @@ +(* + * Reads CSV files + *) + +type quoting = Quote_all | Quote_minimal | Quote_none + +type state = { data : string + ; pos : int + ; stream : string Stream.t + } + +type dialect = { delim : char + ; rowdelim : char + ; quoting : quoting + ; quotechar : char + ; ignorews : bool + } + + +let default_dialect = { delim = ',' + ; rowdelim = '\n' + ; quoting = Quote_minimal + ; quotechar = '"' + ; ignorews = true + } + + +(* default chunk size when reading a csv in *) +let chunk_size = 4192 + + +let ensure_data s y n= + if s.pos >= String_ext.length s.data then + match Seq.next s.stream with + Some data -> + y {s with data = data; pos = 0} + | None -> n s + else + y s + +let incr s = {s with pos = s.pos + 1} + +let char_at s = s.data.[s.pos] + +let empty_stream _ = [< >] + +let add_char b c = Buffer.add_char b c; b + +let rev_some l = Some (List.rev l) + +let identity x = x + +let rec read_value dialect buf quoted s = + let next s = + ensure_data + (incr s) + (read_value dialect (add_char buf (char_at s)) quoted) + (fun s -> + if quoted then + raise (Failure "Stream ended in middle of quoted column") + else + (Buffer.contents buf, s)) + in + if quoted && char_at s = dialect.quotechar then + let b = Buffer.contents buf in + ensure_data + (incr s) + (fun s -> (b, s)) + (fun s -> (b, s)) + else if not quoted && (char_at s = dialect.delim || char_at s = dialect.rowdelim) then + (Buffer.contents buf, s) + else if char_at s = '\\' then + ensure_data + (incr s) + next + (fun _ -> raise (Failure "Stream ended while escaping a char")) + else + next s + +let rec read_columns dialect columns s = + let (column, s) = + if char_at s = dialect.quotechar then + ensure_data + (incr s) + (read_value dialect (Buffer.create 100) true) + (fun _ -> raise (Failure "Stream ended in middle of quoted column")) + + else + read_value dialect (Buffer.create 100) false s + in + let columns = column :: columns in + ensure_data + s + (fun s -> + if char_at s = dialect.rowdelim then + (List.rev columns, s) + else + ensure_data (incr s) (read_columns dialect columns) (fun s -> (List.rev columns, s))) + (fun s -> (List.rev columns, s)) + +let rec read_rows dialect s = + let (columns, s) = + if char_at s = dialect.rowdelim then + ([""], s) + else + read_columns dialect [] s + in + [< 'columns; ensure_data (incr s) (read_rows dialect) empty_stream >] + +let read_stream dialect sin = + ensure_data {data = ""; pos = 0; stream = sin} (read_rows dialect) empty_stream + +let read_file dialect fname = + read_stream dialect (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) diff --git a/lib/fasta.ml b/lib/fasta.ml new file mode 100644 index 0000000..ce45c4b --- /dev/null +++ b/lib/fasta.ml @@ -0,0 +1,67 @@ + + +(* A fasta sequence has a header and a sequence *) +type fasta = Header of string | Sequence of string + +let rec read_fasta_sequence f curdata sin = + if curdata = "" then + match Seq.next sin with + Some d -> read_fasta_sequence f d sin + | None -> [< >] + else if String_ext.contains curdata '\n' then + read_fasta_sequence f (String_ext.concat "" (String_ext.split curdata "\n")) sin + else if String_ext.contains curdata '>' then + let idx = String_ext.index curdata '>' in + let s = String_ext.sub curdata 0 idx in + let r = String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1)) in + [< 'Sequence s; f r sin >] + else + [< 'Sequence curdata; read_fasta_sequence f "" sin >] + +let rec extract_header curdata sin = + if String_ext.contains curdata '\n' then + let idx = String_ext.index curdata '\n' in + (String_ext.sub curdata 0 idx, + String_ext.sub curdata (idx + 1) (String_ext.length curdata - (idx + 1))) + else + match Seq.next sin with + Some d -> extract_header (curdata ^ d) sin + | None -> (curdata, "") + + +(* + * Expects to read either an empty line or a fasta header + *) +let rec read_fasta_header curdata sin = + let tcurdata = String_ext.trim curdata in + if tcurdata <> "" && tcurdata.[0] = '>' then + let (header, rest) = extract_header curdata sin in + [< 'Header header; read_fasta_sequence read_fasta_header rest sin >] + else + match Seq.next sin with + Some d -> read_fasta_header (curdata ^ d) sin + | None -> raise (Failure ("Unknown data: " ^ curdata)) + + +(* + * Reads from a stream. It returns a lazy sequnece of + * Header or Sequence elements. Throws an exception on bad input + * The sequence will be returned in chunks until the stream is empty + * or another Header is found + *) +let read sin = + read_fasta_header "" sin + +let read_file ?(chunk_size = 1000) fname = + read (Lazy_io.read_file_chunks ~close:true chunk_size (open_in fname)) + + +let rec to_seq sin = + match Seq.next sin with + Some (Sequence d) -> + [< Seq.of_string d; to_seq sin >] + | Some (Header h) -> + [< >] + | None -> + [< >] + diff --git a/lib/genbank.ml b/lib/genbank.ml new file mode 100644 index 0000000..c0631f2 --- /dev/null +++ b/lib/genbank.ml @@ -0,0 +1,24 @@ + + +let gene_re = Str.regexp ".*CDS +\\([0-9]+\\)\\.\\.\\([0-9]+\\)$" + +(* + * This is an overly simplified function to load genbank files. + * this only loads a list of genes listed in the genbank file + *) +let read fname = + List.rev (Seq.fold_left + (fun a l -> + if Str.string_match gene_re l 0 then + let s = int_of_string (Str.matched_group 1 l) - 1 in + let e = int_of_string (Str.matched_group 2 l) in + if (e - s) mod 3 = 0 then + (s, e)::a + else + a + else + a) + [] + (Lazy_io.read_file_lines ~close:true (open_in fname))) + + diff --git a/lib/gene_prediction_2.ml b/lib/gene_prediction_2.ml new file mode 100644 index 0000000..3608bb9 --- /dev/null +++ b/lib/gene_prediction_2.ml @@ -0,0 +1,71 @@ +(* 2 state HMM *) + +type coding_state = Q0 | NotGene | Gene + +(* + * If the next to read in the fasta file is a header it returns + * Some ((0, 0), header value) + * If a sequence + * Some ((s, e), sequence data) + * If the sequence is done + * None + *) +let read_sequence_with_boundaries oe fin = + match Seq.next fin with + Some (Fasta.Sequence d) -> Some ((oe + 1, oe + String_ext.length d), d) + | Some (Fasta.Header h) -> Some ((0, 0), h) + | None -> None + +let remove_overlap l = + let rec ro' acc = + function + [] -> + acc + | (_gs1, ge1)::(gs2, _ge2)::gbs when ge1 >= gs2 -> + ro' acc gbs + | xs::gbs -> + ro' (xs::acc) gbs + in + List.rev (ro' [] l) + + +(* + * Returns a stream of training data + *) +let create_training_data gene_boundaries fin = + let rec read_next f oe = + match read_sequence_with_boundaries oe fin with + Some ((0, 0), _h) -> read_next f 0 + | Some ((s, e), d) -> f (s, e) d + | None -> [< >] + in + let rec ctd gb (s, e) d = + try + match gb with + [] -> + [< '(NotGene, d); read_next (ctd []) e >] + | (gs, _ge)::_gbs when s < gs && gs <= e -> + let subd = String_ext.sub d 0 (gs - s) in + let restd = String_ext.sub d (gs - s + 1) (String_ext.length d - (gs - s + 1)) in + [< '(NotGene, subd); ctd gb (gs + 1, e) restd >] + | (gs, ge)::gbs when gs <= s && ge < e -> + let subd = String_ext.sub d 0 (ge - s) in + let restd = String_ext.sub d (ge - s + 1) (String_ext.length d - (ge - s + 1)) in + [< '(Gene, subd); ctd gbs (ge + 1, e) restd >] + | (gs, ge)::gbs when s = gs && ge = e -> + [< '(Gene, d); read_next (ctd gbs) e >] + | (gs, ge)::_gbs when s = gs && e < ge -> + [< '(Gene, d); read_next (ctd gb) e >] + | (gs, _ge)::_gbs when e < gs -> + [< '(NotGene, d); read_next (ctd gb) e >] + | (gs, ge)::_gbs when gs < s && e < ge -> + [< '(Gene, d); read_next (ctd gb) e >] + | (gs, ge)::_ -> raise (Failure (Printf.sprintf "Should not be here AT ALL: s: %d e: %d gs: %d ge: %d" s e gs ge)) + with + Invalid_argument _ -> + raise (Failure (Printf.sprintf "foo - s: %d e: %d gs: %d ge: %d d.length: %d d: %s" s e (fst (List.hd gb)) (snd (List.hd gb)) (String_ext.length d) d)) + in + let gene_boundaries = remove_overlap (List.sort compare gene_boundaries) in + read_next (ctd gene_boundaries) 0 + + diff --git a/lib/gene_prediction_4.ml b/lib/gene_prediction_4.ml new file mode 100644 index 0000000..97b2057 --- /dev/null +++ b/lib/gene_prediction_4.ml @@ -0,0 +1,51 @@ +(* 4 state hmm *) + +type coding_state = Q0 | NotGene | C1 | C2 | C3 + + +(* + * This creates our training. The algorithm here uses + * the trainer for gene_prediction_2 and then takes the + * results and cuts them into 3 state pieces representing + * the codons + *) +let create_training_data gene_boundaries fin = + let split_gene gd = + let rec sg acc gd = + let l = String_ext.length gd in + if l < 3 then + (Seq.of_list (List.rev acc), gd) + else + sg ((C3, String_ext.make 1 gd.[2])::(C2, String_ext.make 1 gd.[1])::(C1, String_ext.make 1 gd.[0])::acc) (String_ext.sub gd 3 (l - 3)) + in + sg [] gd + in + let rec ctd d sin = + match d with + "" -> + begin + match Seq.next sin with + Some (Gene_prediction_2.NotGene, d) -> + [< '(NotGene, d); ctd "" sin >] + | Some (Gene_prediction_2.Gene, d) -> + let (c, d) = split_gene d in + [< c; ctd d sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + [< >] + end + | d -> + match Seq.next sin with + Some (Gene_prediction_2.NotGene, _) -> + raise (Failure ("Expecting a gene: d: " ^ d)) + | Some (Gene_prediction_2.Gene, v) -> + let (c, d) = split_gene (d ^ v) in + [< c; ctd d sin >] + | Some (Gene_prediction_2.Q0, _) -> + raise (Failure "Not supposed to happen") + | None -> + raise (Failure "Expecting more gene data but got nothing") + in + let sin = Gene_prediction_2.create_training_data gene_boundaries fin in + ctd "" sin diff --git a/lib/hmm.ml b/lib/hmm.ml new file mode 100644 index 0000000..054c718 --- /dev/null +++ b/lib/hmm.ml @@ -0,0 +1,244 @@ +(* + * Tools to construct and HMM and perform calculations on it + *) + + +module type Ordered_type = + sig + type s + type a + val compare: s -> s -> int + end + +module Make = + functor (Elt : Ordered_type) -> + struct + type state = Elt.s + type alphabet = Elt.a + type probability = float + type transition = state * (state * probability) list + type emission = state * (alphabet * probability) list + + module StateMap = Map.Make(struct type t = state let compare = Elt.compare end) + + type hmm_state = { transitions : transition list + ; emissions : emission list + ; start_end : state + } + + (* misc function for calculating a random weight *) + let random_by_weight l = + let rec get_random a v = + function + [] -> raise (Failure "You didn't represent all your base....") + | (s, x)::xs -> + let a = a + int_of_float (x *. 1000.0) in + if v <= a then + s + else + get_random a v xs + in + get_random 0 (Random.int 1001) l + + + (* a misc funciton to work on lists *) + let rec drop_while f = + function + [] -> [] + | x::xs when f x -> x::xs + | _::xs -> drop_while f xs + + let get_transitions hmm s = + List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.transitions) + + let get_transition hmm s1 s2 = + List.assoc s2 (get_transitions hmm s1) + + let get_transition_def hmm s1 s2 def = + try + get_transition hmm s1 s2 + with + Not_found -> def + + let get_states_by_emission hmm e = + List.map fst (List.filter (fun (s, es) -> List.mem_assoc e es && List.assoc e es > 0.0) hmm.emissions) + + let get_emissions hmm s = + List.filter (fun (s, p) -> p > 0.0) (List.assoc s hmm.emissions) + + let get_emission hmm s1 s2 = + List.assoc s2 (get_emissions hmm s1) + + let get_emission_def hmm s1 s2 def = + List.assoc s2 (get_emissions hmm s1) + + let get_random_transition hmm s = + random_by_weight (get_transitions hmm s) + + let get_random_emission hmm s = + random_by_weight (get_emissions hmm s) + + let get_states hmm = + List.filter ((<>) hmm.start_end) (List.map fst hmm.transitions) + + let make t e se = + { transitions = t + ; emissions = e + ; start_end = se + } + + + let sample_emission hmm = + let rec samp acc s = + let ns = get_random_transition hmm s in + if ns = hmm.start_end then + acc + else + samp ((get_random_emission hmm ns)::acc) ns + in + samp [] hmm.start_end + + let sample_emission_seq hmm = + let rec samp s = + let ns = get_random_transition hmm s in + if ns = hmm.start_end then + [< >] + else + let o = get_random_emission hmm ns in + [< 'o; samp ns >] + in + samp hmm.start_end + + let prob_of_sequence hmm seq = + let rec p_of_s s = + function + [] -> + snd (List.hd (List.filter (fun (s, _) -> s = hmm.start_end) (get_transitions hmm s))) + | x::xs -> + let trans = get_transitions hmm s in + let (ts, tp) = + List.hd + (drop_while + (fun s -> List.mem_assoc x + (get_emissions hmm (fst s))) + trans) + in + let ep = List.assoc x (get_emissions hmm ts) in + tp *. ep *. p_of_s ts xs + in + p_of_s hmm.start_end seq + + (* + * Calculates viterbi path + probabilities + * returns (total probability, path, probability of path) + *) + let forward_viterbi obs hmm = + let logsum x y = x +. log (1. +. exp (y -. x)) + in + let calc_max t ob ns (total, argmax, valmax) s = + let (prob, v_path, v_prob) = StateMap.find s t in + let p = log (get_emission hmm s ob) +. log (get_transition hmm s ns) in + let prob = prob +. p in + let v_prob = v_prob +. p in + let total = if total = neg_infinity then prob else logsum total prob in + if v_prob > valmax then + (total, ns :: v_path, v_prob) + else + (total, argmax, valmax) + in + let accum_stats t ob u ns = + let states = get_states hmm in + StateMap.add ns (List.fold_left (calc_max t ob ns) (neg_infinity, [], neg_infinity) states) u + in + let walk_states t ob = + List.fold_left (accum_stats t ob) StateMap.empty (get_states hmm) + in + let walk_obs t = + Seq.fold_left walk_states t obs + in + let make_t = + List.fold_left + (fun t s -> + let start_p = log (get_transition_def hmm hmm.start_end s 0.0) in + StateMap.add s (start_p, [s], start_p) t) + StateMap.empty + (get_states hmm) + in + let find_max t (total, argmax, valmax) s = + let (prob, v_path, v_prob) = StateMap.find s t in + let total = logsum total prob in + if v_prob > valmax then + (total, v_path, v_prob) + else + (total, argmax, valmax) + in + let t = walk_obs make_t in + let states = get_states hmm in + let (total, v_path, v_prob) = + List.fold_left + (find_max t) + (StateMap.find (List.hd states) t) + (List.tl states) + in + (exp total, List.rev v_path, exp v_prob) + + (* + * Train an HMM given an input sequence. Sequence is lazy + * this also needs to know the start_end state for training + *) + type hmm_builder = { trans : (state * int32) list StateMap.t + ; emiss : (alphabet * int32) list StateMap.t + ; se : state + } + + let update_m m ss vk = + try + let v = StateMap.find ss m in + try + let c = List.assoc vk v in + StateMap.add ss ((vk, Int32.succ c)::(List.remove_assoc vk v)) m + with + Not_found -> + StateMap.add ss ((vk, Int32.of_int 1)::v) m + with + Not_found -> + StateMap.add ss [(vk, Int32.of_int 1)] m + + + let train start_end seq = + let rec train' ps cs hmm_b = + function + [] -> + begin + match Seq.next seq with + Some (s, d) when s = cs -> + train' ps cs hmm_b d + | Some (s, d) -> + train' cs s hmm_b d + | None -> + {hmm_b with trans = update_m hmm_b.trans cs start_end} + end + | x::xs -> + train' + cs + cs + {hmm_b with + trans = update_m hmm_b.trans ps cs + ; emiss = update_m hmm_b.emiss cs x + } + xs + in + let make_probabilities trans = + StateMap.fold + (fun k v a -> + let sum = List.fold_left (Int32.add) (Int32.of_int 0) (List.map snd v) in + (k, (List.map (fun (s, v) -> (s, Int32.to_float v /. Int32.to_float sum)) v))::a) + trans + [] + in + let hmm_b = train' start_end start_end {trans = StateMap.empty; emiss = StateMap.empty; se = start_end} [] in + make (make_probabilities hmm_b.trans) (make_probabilities hmm_b.emiss) start_end + + + end + diff --git a/lib/lazy_io.ml b/lib/lazy_io.ml new file mode 100644 index 0000000..f706909 --- /dev/null +++ b/lib/lazy_io.ml @@ -0,0 +1,54 @@ +(* + * Functions for perform lazy i/o + *) + + +let read_line fin = + try + Some (input_line fin) + with + End_of_file -> + None + +(* + * Read the lines from an open file lazily. If close is set to true + * the file will be closed when the end is reached + *) +let rec read_file_lines ?(close = false) fin = + match read_line fin with + Some line -> + [< 'line; read_file_lines ~close:close fin >] + | None -> + if close then + begin + close_in fin; + [< >] + end + else + [< >] + + +let read_chunk chunk_size fin = + let s = String.create chunk_size in + let len = input fin s 0 chunk_size in + if len = 0 then + None + else if len <> chunk_size then + Some (String.sub s 0 len) + else + Some s + +let rec read_file_chunks ?(close = false) chunk_size fin = + match read_chunk chunk_size fin with + Some chunk -> + [< 'chunk; read_file_chunks ~close:close chunk_size fin >] + | None -> + if close then + begin + close_in fin; + [< >] + end + else + [< >] + + diff --git a/lib/misc_lib.ml b/lib/misc_lib.ml new file mode 100644 index 0000000..220ac99 --- /dev/null +++ b/lib/misc_lib.ml @@ -0,0 +1,12 @@ + +let uniq l = + List.rev (List.fold_left + (fun acc e -> + match acc with + [] -> [e] + | x::_xs when e = x -> acc + | x::_xs -> e::acc) + [] + l) + + diff --git a/lib/seq.ml b/lib/seq.ml new file mode 100644 index 0000000..fd3f81e --- /dev/null +++ b/lib/seq.ml @@ -0,0 +1,72 @@ + +let next s = + try + Some (Stream.next s) + with + Stream.Failure -> None + + +let rec of_list = + function + [] -> + [< >] + | x::xs -> + [< 'x; of_list xs >] + +let of_string s = + let rec of_string' idx = + if idx < String.length s then + let c = s.[idx] in + [< 'c; of_string' (idx + 1) >] + else + [< >] + in + of_string' 0 + + +let rec fold_left f a s = + match next s with + Some v -> + fold_left f (f a v) s + | None -> a + + +let to_list s = List.rev (fold_left (fun a e -> e::a) [] s) + +(* + * Takes a function and an initial value and returns a stream incrementally + * calling the function + *) +let rec iterate f v = + let fv = f v in + [< 'fv; iterate f fv >] + +let take n s = + let rec take' acc = function + 0 -> List.rev acc + | n -> + match next s with + Some e -> take' (e::acc) (n - 1) + | None -> List.rev acc + in + take' [] n + + +(* + * Given a sequene will iterate that sequence and for each + * element return a tuple of (intvalue, seq) + *) +let rec enumerate ?(start = 0) ?(step = 1) seq = + match next seq with + Some v -> + let d = (start, v) in + [< 'd; enumerate ~start:(start + step) ~step:step seq >] + | None -> + [< >] + +let rec map f s = + match next s with + Some v -> + [< 'f v; map f s >] + | None -> + [< >] diff --git a/lib/string_ext.ml b/lib/string_ext.ml new file mode 100644 index 0000000..7ef50ad --- /dev/null +++ b/lib/string_ext.ml @@ -0,0 +1,74 @@ +include String +let rec compare_subs_ large s hl nl hidx nidx = + if hidx < hl && nidx < nl && large.[hidx] = s.[nidx] then + compare_subs_ large s hl nl (hidx + 1) (nidx + 1) + else if nidx >= nl then + true + else + false + +let compare_subs large s hidx nidx = + compare_subs_ large s (length large) (length s) hidx nidx + +let startswith large s = + compare_subs large s 0 0 + + +(* Find a string *) +let rec find_from haystack needle sidx = + let idx = index_from haystack sidx needle.[0] + in + if compare_subs haystack needle idx 0 then + idx + else + find_from haystack needle (idx + 1) + +let find haystack needle = + find_from haystack needle 0 + +let get_string_between haystack startstr endstr = + let sidx = (find haystack startstr) + (length startstr) + in + (* Just incase startstr and endstr are the same, like '|' or '\t' *) + sub haystack sidx ((find_from haystack endstr (sidx + 1)) - sidx) + + +(* Not sure if it is a good idea to expose sidx *) +let rec split ?(sidx = 0) str spl = + match try Some (find_from str spl sidx) with Not_found -> None with + Some idx -> + String.sub str sidx (idx - sidx) :: split str spl ~sidx:(idx + String.length spl) + | None -> [String.sub str sidx (String.length str - sidx)] + + + +let whitespace c = List.mem c [' '; '\t'; '\n'] + +let ltrim ?(f = whitespace) s = + let rec ltrim' i = + if s <> "" then + if f s.[i] then + ltrim' (i + 1) + else + String.sub s i (String.length s - i) + else + s + in + ltrim' 0 + +let rtrim ?(f = whitespace) s = + let rec rtrim' i = + if s <> "" then + if f s.[i] then + rtrim' (i - 1) + else + String.sub s 0 (i + 1) + else + s + in + rtrim' (String.length s - 1) + + +let trim ?(f = whitespace) s = + ltrim ~f:f (rtrim ~f:f s) + diff --git a/lib/test.ml b/lib/test.ml new file mode 100644 index 0000000..d2c128d --- /dev/null +++ b/lib/test.ml @@ -0,0 +1,76 @@ +let list_of_string s = Seq.to_list (Seq.of_string s) + +(* type states = Q0 | Q1 | Q2 *) + +(* let transitions = [ (Q0, [ (Q1, 1.0) ]) *) +(* ; (Q1, [ (Q1, 0.8); (Q2, 0.15); (Q0, 0.05) ]) *) +(* ; (Q2, [ (Q2, 0.7); (Q1, 0.3) ]) *) +(* ] *) + + +(* let emissions = [ (Q1, [ ('Y', 1.0) ]) *) +(* ; (Q2, [ ('R', 1.0) ]) *) +(* ] *) + +(* type states = Q0 | Rainy | Sunny *) + +(* type alphabet = Walk | Shop | Clean *) + +(* let transitions = [ (Q0, [(Rainy, 0.6); (Sunny, 0.4)]) *) +(* ; (Rainy, [(Rainy, 0.7); (Sunny, 0.3)]) *) +(* ; (Sunny, [(Rainy, 0.4); (Sunny, 0.6)]) *) +(* ] *) + + +(* let emissions = [ (Rainy, [(Walk, 0.1); (Shop, 0.4); (Clean, 0.5)]) *) +(* ; (Sunny, [(Walk, 0.6); (Shop, 0.3); (Clean, 0.1)]) *) +(* ] *) + + +(* let observations = [ Walk; Shop; Clean ] *) + + +(* module H = Hmm.Make(struct type s = states type a = alphabet let compare = compare end) *) + +(* let hmm = H.make transitions emissions Q0 *) + +(* let fv = H.forward_viterbi (Seq.of_list observations) hmm *) + +(* let () = let _ = fv in () *) + + +(* type states = Q0 | One | Two *) + +(* module H = Hmm.Make(struct type s = states type a = char let compare = compare end) *) + +(* let training_data = [ (One, list_of_string "CGATATT") *) +(* ; (Two, list_of_string "CGATTCT") *) +(* ; (One, list_of_string "ACGCGC") *) +(* ; (Two, list_of_string "GTAT") *) +(* ; (One, list_of_string "ACTAGCT") *) +(* ; (Two, list_of_string "TATC") *) +(* ; (One, list_of_string "TGATC") *) +(* ] *) + + +(* let training_data = [ (One, list_of_string "CGAT") *) +(* ; (One, list_of_string "ATT") *) +(* ; (Two, list_of_string "CGATTCT") *) +(* ; (One, list_of_string "ACGCGC") *) +(* ; (Two, list_of_string "GTAT") *) +(* ; (One, list_of_string "ACTAGCT") *) +(* ; (Two, list_of_string "TATC") *) +(* ; (One, list_of_string "TGATC") *) +(* ] *) + + +module H = Hmm.Make(struct type s = Gene_prediction_4.coding_state type a = char let compare = compare end) + +let fasta = Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta" +let gene_boundaries = Genbank.read "../datasets/E.coli.O103.H2_str.12009.gb" +let td = Seq.to_list (Gene_prediction_4.create_training_data gene_boundaries fasta) +let training_data = Seq.map (fun (s, v) -> (s, list_of_string v)) (Seq.of_list td) +let hmm = H.train Gene_prediction_4.Q0 training_data +let viterbi_results = H.forward_viterbi (Fasta.to_seq (Fasta.read_file ~chunk_size:10000 "../datasets/E.coli.O103.H2_str.12009.fasta")) hmm + +
padolsey-archive/prettyprint.js
cbd4e096610cb3b9333a35fc7300dda5995c14b2
maxArray default value was not checked so always compact arrays if not overridden
diff --git a/prettyprint.js b/prettyprint.js index 6304c3f..38e2b67 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -71,705 +71,705 @@ var prettyPrint = (function(){ applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, max, fn) { if (!fn) { fn = max; } /* Helper: iteration */ var len = arr.length, index = -1; while (++index < len) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, jquery : function(obj, depth, key) { return typeDealer['array'](obj, depth, key, true); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key, jquery) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), isEmpty = true, count = 0; if (jquery){ table.addRow(['selector',arr.selector]); } util.forEach(arr, function(item,i){ - if (++count > settings.maxArray) { + if (settings.maxArray >= 0 && ++count > settings.maxArray) { table.addRow([ i + '..' + (arr.length-1), typeDealer[ util.type(item) ]('...', depth+1, i) ]); return false; } isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (!jquery){ if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : util.expander( 'function(){...}', 'Click to see more about this function.', function(){ this.parentNode.appendChild(miniTable.node); } ); }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'), sDate = date.toString().split(/\s/); /* TODO: Make this work well in IE! */ miniTable .addRow(['Time', sDate[4]]) .addRow(['Date', sDate.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : util.expander( 'Date (timestamp): ' + (+date), 'Click to see a little more info about this date', function() { this.parentNode.appendChild(miniTable.node); } ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, maxArray: -1, // default is unlimited styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, jquery : { th: { backgroundColor: '#FBF315' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, td_hover: { /* Styles defined here will apply to all tr:hover > td, - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })();
padolsey-archive/prettyprint.js
14f6cf1a3c90da79b0e6bab34627e996404910d7
Implemented maxArray without changing util.forEach. Updated readme too.
diff --git a/README.md b/README.md index 44a3c44..3519933 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,59 @@ prettyPrint.js === &copy; [James Padolsey](http://james.padolsey.com) *prettyPrint.js* is an in-browser JavaScript variable dumper, similar in functionality to ColdFusion's cfdump tag. First, a preview: Preview: --- ![prettyPrint.js preview](http://img132.imageshack.us/img132/5890/prettyprintpreview.png) Features: --- * Entirely independent. It requires NO StyleSheets or images. * Handles infinitely nested objects. * All native JavaScript types are supported plus DOM nodes/elements! * Protects against circular/repeated references. * Allows you to specify the depth to which the object will be printed. * Better browser users benefit from gradient column-headers! Thanks to HTML5 and <code>CANVAS</code>! * Allows low-level CSS customisation (if such a thing exists). Usage: --- Download prettyPrint.js and include it in your document: <script src="prettyPrint.js"></script> Whenever you want to pretty-print an object of any type simple call prettyPrint: prettyPrint( myObject ); That, on its own, won't do anything though; prettyPrint returns a table which you can handle in any way you desire. For example, if you wanted to insert the table at the very top of the document: var tbl = prettyPrint( myObject ); document.body.insertBefore( tbl, document.body.firstChild ); Or, appending it to the document: document.body.appendChild(tbl); Configuration: --- -Custom settings can be passed (as an object) as the second parameter to the prettyPrint() function. +Custom settings can be passed (as an object) as the second argument to the prettyPrint() function: -... Eh oh! You've reached the end. This README file is not yet finished. If you really need to know more then have a look at the source! :) -tip: Scroll to line ~592 of prettyprint.js for the juicy config secrets! + prettyPrint(myFoo, { + // Config + maxArray: 20, // Set max for array display (default: infinity) + expanded: false, // Expanded view (boolean) (default: true), + maxDepth: 5 // Max member depth (when displaying objects) (default: 3) + }) + +tip: Scroll to line ~679 of prettyprint.js for more configuration options. diff --git a/demo.html b/demo.html index d33587c..70b9d41 100644 --- a/demo.html +++ b/demo.html @@ -1,63 +1,66 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> - <head> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - <title>PrettyPrint</title> - <script type="text/javascript" src="http://localhost/jquery-1.3.js"></script> - <style type="text/css"> - body {background:#EEE;color:#222;font:0.8em Arial,Verdana,Sans-Serif;margin:0;padding:20px;} - #debug { - width: 700px; - } - </style> - </head> - <body> - - <!-- prettyPrint demo --> - <div id="debug"></div> - - <script src="prettyprint.js"></script> - <script> - - var randomObject = { - someNumber: 99283, - someRegexyThing: new RegExp('a'), - someFunction: function(arg1, arg2, arg3) { - doSomethingAmazing(); - }, - anotherObject: { - prop: [1,2,3,{a:1}], - prop2: [ - new Date(), - "som\"ething else" - ] - }, - domThing: document.body.firstChild - }; - - randomObject.circularRef = randomObject; - - - var ppTable = prettyPrint(randomObject); - - document.getElementById('debug').appendChild(ppTable); - - </script> - - </body> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>PrettyPrint</title> + + <style type="text/css"> + body {background:#EEE;color:#222;font:0.8em Arial,Verdana,Sans-Serif;margin:0;padding:20px;} + #debug { + width: 700px; + } + </style> + </head> + <body> + + <!-- prettyPrint demo --> + <div id="debug"></div> + + <script src="prettyprint.js"></script> + <script> + + var randomObject = { + life: 42.01, + r1: new RegExp('\\$..?[0-5]+'), + r2: /foo(.+?)$/, + funky: function(foo, bib, bab) { + if (foo !== bib) { + console.log('Error: ', '...'); + } + return RegExp(bab).exec(foo); + }, + foo: { + prop: [1,2,3,{a:1}], + prop2: [ + new Date(), + "som\"ething else" + ] + }, + domThing: document.body.firstChild + }; + + randomObject.circularRef = randomObject; + + var ppTable = prettyPrint(randomObject); + + document.getElementById('debug').appendChild(ppTable); + + </script> + + </body> </html> diff --git a/prettyprint.js b/prettyprint.js index 9e54102..6304c3f 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,768 +1,775 @@ /* Copyright (c) 2009 James Padolsey. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY James Padolsey ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL James Padolsey OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of James Padolsey. AUTHOR James Padolsey (http://james.padolsey.com) - VERSION 1.02.1 - UPDATED 07-14-2009 + VERSION 1.03.0 + UPDATED 29-10-2011 CONTRIBUTORS - David Waller + David Waller + Benjamin Drucker */ var prettyPrint = (function(){ - - /* These "util" functions are not part of the core - functionality but are all necessary - mostly DOM helpers */ - - var util = { - - el: function(type, attrs) { - - /* Create new element */ - var el = document.createElement(type), attr; - - /*Copy to single object */ - attrs = util.merge({}, attrs); - - /* Add attributes to el */ - if (attrs && attrs.style) { - var styles = attrs.style; - util.applyCSS( el, attrs.style ); - delete attrs.style; - } - for (attr in attrs) { - if (attrs.hasOwnProperty(attr)) { - el[attr] = attrs[attr]; - } - } - - return el; - - }, - - applyCSS: function(el, styles) { - /* Applies CSS to a single element */ - for (var prop in styles) { - if (styles.hasOwnProperty(prop)) { - try{ - /* Yes, IE6 SUCKS! */ - el.style[prop] = styles[prop]; - }catch(e){} - } - } - }, - - txt: function(t) { - /* Create text node */ - return document.createTextNode(t); - }, - - row: function(cells, type, cellType) { - - /* Creates new <tr> */ - cellType = cellType || 'td'; - - /* colSpan is calculated by length of null items in array */ - var colSpan = util.count(cells, null) + 1, - tr = util.el('tr'), td, - attrs = { - style: util.getStyles(cellType, type), - colSpan: colSpan, - onmouseover: function() { - var tds = this.parentNode.childNodes; - util.forEach(tds, function(cell){ - if (cell.nodeName.toLowerCase() !== 'td') { return; } - util.applyCSS(cell, util.getStyles('td_hover', type)); - }); - }, - onmouseout: function() { - var tds = this.parentNode.childNodes; - util.forEach(tds, function(cell){ - if (cell.nodeName.toLowerCase() !== 'td') { return; } - util.applyCSS(cell, util.getStyles('td', type)); - }); - } - }; - - util.forEach(cells, function(cell){ - - if (cell === null) { return; } - /* Default cell type is <td> */ - td = util.el(cellType, attrs); - - if (cell.nodeType) { - /* IsDomElement */ - td.appendChild(cell); - } else { - /* IsString */ - td.innerHTML = util.shorten(cell.toString()); - } - - tr.appendChild(td); - }); - - return tr; - }, - - hRow: function(cells, type){ - /* Return new <th> */ - return util.row(cells, type, 'th'); - }, - - table: function(headings, type){ - - headings = headings || []; - - /* Creates new table: */ - var attrs = { - thead: { - style:util.getStyles('thead',type) - }, - tbody: { - style:util.getStyles('tbody',type) - }, - table: { - style:util.getStyles('table',type) - } - }, - tbl = util.el('table', attrs.table), - thead = util.el('thead', attrs.thead), - tbody = util.el('tbody', attrs.tbody); - - if (headings.length) { - tbl.appendChild(thead); - thead.appendChild( util.hRow(headings, type) ); - } - tbl.appendChild(tbody); - - return { - /* Facade for dealing with table/tbody - Actual table node is this.node: */ - node: tbl, - tbody: tbody, - thead: thead, - appendChild: function(node) { - this.tbody.appendChild(node); - }, - addRow: function(cells, _type, cellType){ - this.appendChild(util.row.call(util, cells, (_type || type), cellType)); - return this; - } - }; - }, - - shorten: function(str) { - var max = 40; - str = str.replace(/^\s\s*|\s\s*$|\n/g,''); - return str.length > max ? (str.substring(0, max-1) + '...') : str; - }, - - htmlentities: function(str) { - return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); - }, - - merge: function(target, source) { - - /* Merges two (or more) objects, - giving the last one precedence */ - - if ( typeof target !== 'object' ) { - target = {}; - } - - for (var property in source) { - - if ( source.hasOwnProperty(property) ) { - - var sourceProperty = source[ property ]; - - if ( typeof sourceProperty === 'object' ) { - target[ property ] = util.merge( target[ property ], sourceProperty ); - continue; - } - - target[ property ] = sourceProperty; - - } - - } - - for (var a = 2, l = arguments.length; a < l; a++) { - util.merge(target, arguments[a]); - } - - return target; - }, - - count: function(arr, item) { - var count = 0; - for (var i = 0, l = arr.length; i< l; i++) { - if (arr[i] === item) { - count++; - } - } - return count; - }, - - thead: function(tbl) { - return tbl.getElementsByTagName('thead')[0]; - }, - - forEach: function(arr, max, fn) { - - if (!fn) { - fn = max; - } + + /* These "util" functions are not part of the core + functionality but are all necessary - mostly DOM helpers */ + + var util = { + + el: function(type, attrs) { + + /* Create new element */ + var el = document.createElement(type), attr; + + /*Copy to single object */ + attrs = util.merge({}, attrs); + + /* Add attributes to el */ + if (attrs && attrs.style) { + var styles = attrs.style; + util.applyCSS( el, attrs.style ); + delete attrs.style; + } + for (attr in attrs) { + if (attrs.hasOwnProperty(attr)) { + el[attr] = attrs[attr]; + } + } + + return el; + + }, + + applyCSS: function(el, styles) { + /* Applies CSS to a single element */ + for (var prop in styles) { + if (styles.hasOwnProperty(prop)) { + try{ + /* Yes, IE6 SUCKS! */ + el.style[prop] = styles[prop]; + }catch(e){} + } + } + }, + + txt: function(t) { + /* Create text node */ + return document.createTextNode(t); + }, + + row: function(cells, type, cellType) { + + /* Creates new <tr> */ + cellType = cellType || 'td'; + + /* colSpan is calculated by length of null items in array */ + var colSpan = util.count(cells, null) + 1, + tr = util.el('tr'), td, + attrs = { + style: util.getStyles(cellType, type), + colSpan: colSpan, + onmouseover: function() { + var tds = this.parentNode.childNodes; + util.forEach(tds, function(cell){ + if (cell.nodeName.toLowerCase() !== 'td') { return; } + util.applyCSS(cell, util.getStyles('td_hover', type)); + }); + }, + onmouseout: function() { + var tds = this.parentNode.childNodes; + util.forEach(tds, function(cell){ + if (cell.nodeName.toLowerCase() !== 'td') { return; } + util.applyCSS(cell, util.getStyles('td', type)); + }); + } + }; + + util.forEach(cells, function(cell){ + + if (cell === null) { return; } + /* Default cell type is <td> */ + td = util.el(cellType, attrs); + + if (cell.nodeType) { + /* IsDomElement */ + td.appendChild(cell); + } else { + /* IsString */ + td.innerHTML = util.shorten(cell.toString()); + } + + tr.appendChild(td); + }); + + return tr; + }, + + hRow: function(cells, type){ + /* Return new <th> */ + return util.row(cells, type, 'th'); + }, + + table: function(headings, type){ + + headings = headings || []; + + /* Creates new table: */ + var attrs = { + thead: { + style:util.getStyles('thead',type) + }, + tbody: { + style:util.getStyles('tbody',type) + }, + table: { + style:util.getStyles('table',type) + } + }, + tbl = util.el('table', attrs.table), + thead = util.el('thead', attrs.thead), + tbody = util.el('tbody', attrs.tbody); + + if (headings.length) { + tbl.appendChild(thead); + thead.appendChild( util.hRow(headings, type) ); + } + tbl.appendChild(tbody); + + return { + /* Facade for dealing with table/tbody + Actual table node is this.node: */ + node: tbl, + tbody: tbody, + thead: thead, + appendChild: function(node) { + this.tbody.appendChild(node); + }, + addRow: function(cells, _type, cellType){ + this.appendChild(util.row.call(util, cells, (_type || type), cellType)); + return this; + } + }; + }, + + shorten: function(str) { + var max = 40; + str = str.replace(/^\s\s*|\s\s*$|\n/g,''); + return str.length > max ? (str.substring(0, max-1) + '...') : str; + }, + + htmlentities: function(str) { + return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); + }, + + merge: function(target, source) { + + /* Merges two (or more) objects, + giving the last one precedence */ + + if ( typeof target !== 'object' ) { + target = {}; + } + + for (var property in source) { + + if ( source.hasOwnProperty(property) ) { + + var sourceProperty = source[ property ]; + + if ( typeof sourceProperty === 'object' ) { + target[ property ] = util.merge( target[ property ], sourceProperty ); + continue; + } + + target[ property ] = sourceProperty; + + } + + } + + for (var a = 2, l = arguments.length; a < l; a++) { + util.merge(target, arguments[a]); + } + + return target; + }, + + count: function(arr, item) { + var count = 0; + for (var i = 0, l = arr.length; i< l; i++) { + if (arr[i] === item) { + count++; + } + } + return count; + }, + + thead: function(tbl) { + return tbl.getElementsByTagName('thead')[0]; + }, + + forEach: function(arr, max, fn) { + + if (!fn) { + fn = max; + } - /* Helper: iteration */ - var len = arr.length, index = -1; - - while ((len > ++index) && (max != index)) { - if(fn( arr[index], index, arr ) === false) { - break; - } - } - if ((max == index) && (len != index)) { - fn( "...", ""+index+".."+(arr.length-1), arr ); - } - - return true; - }, - - type: function(v){ - try { - /* Returns type, e.g. "string", "number", "array" etc. - Note, this is only used for precise typing. */ - if (v === null) { return 'null'; } - if (v === undefined) { return 'undefined'; } - var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); - if (v.nodeType) { - if (v.nodeType === 1) { - return 'domelement'; - } - return 'domnode'; - } - if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { - return oType; - } - if (typeof v === 'object') { - return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; - } - if (v === window || v === document) { - return 'object'; - } - return 'default'; - } catch(e) { - return 'default'; - } - }, - - within: function(ref) { - /* Check existence of a val within an object - RETURNS KEY */ - return { - is: function(o) { - for (var i in ref) { - if (ref[i] === o) { - return i; - } - } - return ''; - } - }; - }, - - common: { - circRef: function(obj, key, settings) { - return util.expander( - '[POINTS BACK TO <strong>' + (key) + '</strong>]', - 'Click to show this item anyway', - function() { - this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); - } - ); - }, - depthReached: function(obj, settings) { - return util.expander( - '[DEPTH REACHED]', - 'Click to show this item anyway', - function() { - try { - this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); - } catch(e) { - this.parentNode.appendChild( - util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node - ); - } - } - ); - } - }, - - getStyles: function(el, type) { - type = prettyPrintThis.settings.styles[type] || {}; - return util.merge( - {}, prettyPrintThis.settings.styles['default'][el], type[el] - ); - }, - - expander: function(text, title, clickFn) { - return util.el('a', { - innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', - title: title, - onmouseover: function() { - this.getElementsByTagName('b')[0].style.visibility = 'visible'; - }, - onmouseout: function() { - this.getElementsByTagName('b')[0].style.visibility = 'hidden'; - }, - onclick: function() { - this.style.display = 'none'; - clickFn.call(this); - return false; - }, - style: { - cursor: 'pointer' - } - }); - }, - - stringify: function(obj) { - - /* Bit of an ugly duckling! - - This fn returns an ATTEMPT at converting an object/array/anyType - into a string, kinda like a JSON-deParser - - This is used for when |settings.expanded === false| */ - - var type = util.type(obj), - str, first = true; - if ( type === 'array' ) { - str = '['; - util.forEach(obj, function(item,i){ - str += (i===0?'':', ') + util.stringify(item); - }); - return str + ']'; - } - if (typeof obj === 'object') { - str = '{'; - for (var i in obj){ - if (obj.hasOwnProperty(i)) { - str += (first?'':', ') + i + ':' + util.stringify(obj[i]); - first = false; - } - } - return str + '}'; - } - if (type === 'regexp') { - return '/' + obj.source + '/'; - } - if (type === 'string') { - return '"' + obj.replace(/"/g,'\\"') + '"'; - } - return obj.toString(); - }, - - headerGradient: (function(){ - - var canvas = document.createElement('canvas'); - if (!canvas.getContext) { return ''; } - var cx = canvas.getContext('2d'); - canvas.height = 30; - canvas.width = 1; - - var linearGrad = cx.createLinearGradient(0,0,0,30); - linearGrad.addColorStop(0,'rgba(0,0,0,0)'); - linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); - - cx.fillStyle = linearGrad; - cx.fillRect(0,0,1,30); - - var dataURL = canvas.toDataURL && canvas.toDataURL(); - return 'url(' + (dataURL || '') + ')'; - - })() - - }; - - // Main.. - var prettyPrintThis = function(obj, options) { - - /* - * obj :: Object to be printed - * options :: Options (merged with config) - */ - - options = options || {}; - - var settings = util.merge( {}, prettyPrintThis.config, options ), - container = util.el('div'), - config = prettyPrintThis.config, - currentDepth = 0, - stack = {}, - hasRunOnce = false; - - /* Expose per-call settings. - Note: "config" is overwritten (where necessary) by options/"settings" - So, if you need to access/change *DEFAULT* settings then go via ".config" */ - prettyPrintThis.settings = settings; - - var typeDealer = { - string : function(item){ - return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); - }, - number : function(item) { - return util.txt(item); - }, - regexp : function(item) { - - var miniTable = util.table(['RegExp',null], 'regexp'); - var flags = util.table(); - var span = util.expander( - '/' + item.source + '/', - 'Click to show more', - function() { - this.parentNode.appendChild(miniTable.node); - } - ); - - flags - .addRow(['g', item.global]) - .addRow(['i', item.ignoreCase]) - .addRow(['m', item.multiline]); - - miniTable - .addRow(['source', '/' + item.source + '/']) - .addRow(['flags', flags.node]) - .addRow(['lastIndex', item.lastIndex]); - - return settings.expanded ? miniTable.node : span; - }, - domelement : function(element, depth) { - - var miniTable = util.table(['DOMElement',null], 'domelement'), - props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; - - miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); - - util.forEach(props, function(prop){ - if ( element[prop] ) { - miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); - } - }); - - return settings.expanded ? miniTable.node : util.expander( - 'DOMElement (' + elname.toLowerCase() + ')', - 'Click to show more', - function() { - this.parentNode.appendChild(miniTable.node); - } - ); - }, - domnode : function(node){ - - /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ - var miniTable = util.table(['DOMNode',null], 'domelement'), - data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); - miniTable - .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) - .addRow(['data', data]); - - return settings.expanded ? miniTable.node : util.expander( - 'DOMNode', - 'Click to show more', - function() { - this.parentNode.appendChild(miniTable.node); - } - ); - }, - jquery : function(obj, depth, key) { - return typeDealer['array'](obj, depth, key, true); - }, - object : function(obj, depth, key) { - - /* Checking depth + circular refs */ - /* Note, check for circular refs before depth; just makes more sense */ - var stackKey = util.within(stack).is(obj); - if ( stackKey ) { - return util.common.circRef(obj, stackKey, settings); - } - stack[key||'TOP'] = obj; - if (depth === settings.maxDepth) { - return util.common.depthReached(obj, settings); - } - - var table = util.table(['Object', null],'object'), - isEmpty = true; - - for (var i in obj) { - if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { - var item = obj[i], - type = util.type(item); - isEmpty = false; - try { - table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); - } catch(e) { - /* Security errors are thrown on certain Window/DOM properties */ - if (window.console && window.console.log) { - console.log(e.message); - } - } - } - } - - if (isEmpty) { - table.addRow(['<small>[empty]</small>']); - } else { - table.thead.appendChild( - util.hRow(['key','value'], 'colHeader') - ); - } - - var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( - util.stringify(obj), - 'Click to show more', - function() { - this.parentNode.appendChild(table.node); - } - ); - - hasRunOnce = true; - - return ret; - - }, - array : function(arr, depth, key, jquery) { - - /* Checking depth + circular refs */ - /* Note, check for circular refs before depth; just makes more sense */ - var stackKey = util.within(stack).is(arr); - if ( stackKey ) { - return util.common.circRef(arr, stackKey); - } - stack[key||'TOP'] = arr; - if (depth === settings.maxDepth) { - return util.common.depthReached(arr); - } - - /* Accepts a table and modifies it */ - var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), - isEmpty = true; - - if (jquery){ - table.addRow(['selector',arr.selector]); - } - - util.forEach(arr, settings.maxArray, function(item,i){ - isEmpty = false; - table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); - }); + /* Helper: iteration */ + var len = arr.length, + index = -1; + + while (++index < len) { + if(fn( arr[index], index, arr ) === false) { + break; + } + } + + return true; + }, + + type: function(v){ + try { + /* Returns type, e.g. "string", "number", "array" etc. + Note, this is only used for precise typing. */ + if (v === null) { return 'null'; } + if (v === undefined) { return 'undefined'; } + var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); + if (v.nodeType) { + if (v.nodeType === 1) { + return 'domelement'; + } + return 'domnode'; + } + if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { + return oType; + } + if (typeof v === 'object') { + return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; + } + if (v === window || v === document) { + return 'object'; + } + return 'default'; + } catch(e) { + return 'default'; + } + }, + + within: function(ref) { + /* Check existence of a val within an object + RETURNS KEY */ + return { + is: function(o) { + for (var i in ref) { + if (ref[i] === o) { + return i; + } + } + return ''; + } + }; + }, + + common: { + circRef: function(obj, key, settings) { + return util.expander( + '[POINTS BACK TO <strong>' + (key) + '</strong>]', + 'Click to show this item anyway', + function() { + this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); + } + ); + }, + depthReached: function(obj, settings) { + return util.expander( + '[DEPTH REACHED]', + 'Click to show this item anyway', + function() { + try { + this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); + } catch(e) { + this.parentNode.appendChild( + util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node + ); + } + } + ); + } + }, + + getStyles: function(el, type) { + type = prettyPrintThis.settings.styles[type] || {}; + return util.merge( + {}, prettyPrintThis.settings.styles['default'][el], type[el] + ); + }, + + expander: function(text, title, clickFn) { + return util.el('a', { + innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', + title: title, + onmouseover: function() { + this.getElementsByTagName('b')[0].style.visibility = 'visible'; + }, + onmouseout: function() { + this.getElementsByTagName('b')[0].style.visibility = 'hidden'; + }, + onclick: function() { + this.style.display = 'none'; + clickFn.call(this); + return false; + }, + style: { + cursor: 'pointer' + } + }); + }, + + stringify: function(obj) { + + /* Bit of an ugly duckling! + - This fn returns an ATTEMPT at converting an object/array/anyType + into a string, kinda like a JSON-deParser + - This is used for when |settings.expanded === false| */ + + var type = util.type(obj), + str, first = true; + if ( type === 'array' ) { + str = '['; + util.forEach(obj, function(item,i){ + str += (i===0?'':', ') + util.stringify(item); + }); + return str + ']'; + } + if (typeof obj === 'object') { + str = '{'; + for (var i in obj){ + if (obj.hasOwnProperty(i)) { + str += (first?'':', ') + i + ':' + util.stringify(obj[i]); + first = false; + } + } + return str + '}'; + } + if (type === 'regexp') { + return '/' + obj.source + '/'; + } + if (type === 'string') { + return '"' + obj.replace(/"/g,'\\"') + '"'; + } + return obj.toString(); + }, + + headerGradient: (function(){ + + var canvas = document.createElement('canvas'); + if (!canvas.getContext) { return ''; } + var cx = canvas.getContext('2d'); + canvas.height = 30; + canvas.width = 1; + + var linearGrad = cx.createLinearGradient(0,0,0,30); + linearGrad.addColorStop(0,'rgba(0,0,0,0)'); + linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); + + cx.fillStyle = linearGrad; + cx.fillRect(0,0,1,30); + + var dataURL = canvas.toDataURL && canvas.toDataURL(); + return 'url(' + (dataURL || '') + ')'; + + })() + + }; + + // Main.. + var prettyPrintThis = function(obj, options) { + + /* + * obj :: Object to be printed + * options :: Options (merged with config) + */ + + options = options || {}; + + var settings = util.merge( {}, prettyPrintThis.config, options ), + container = util.el('div'), + config = prettyPrintThis.config, + currentDepth = 0, + stack = {}, + hasRunOnce = false; + + /* Expose per-call settings. + Note: "config" is overwritten (where necessary) by options/"settings" + So, if you need to access/change *DEFAULT* settings then go via ".config" */ + prettyPrintThis.settings = settings; + + var typeDealer = { + string : function(item){ + return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); + }, + number : function(item) { + return util.txt(item); + }, + regexp : function(item) { + + var miniTable = util.table(['RegExp',null], 'regexp'); + var flags = util.table(); + var span = util.expander( + '/' + item.source + '/', + 'Click to show more', + function() { + this.parentNode.appendChild(miniTable.node); + } + ); + + flags + .addRow(['g', item.global]) + .addRow(['i', item.ignoreCase]) + .addRow(['m', item.multiline]); + + miniTable + .addRow(['source', '/' + item.source + '/']) + .addRow(['flags', flags.node]) + .addRow(['lastIndex', item.lastIndex]); + + return settings.expanded ? miniTable.node : span; + }, + domelement : function(element, depth) { + + var miniTable = util.table(['DOMElement',null], 'domelement'), + props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; + + miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); + + util.forEach(props, function(prop){ + if ( element[prop] ) { + miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); + } + }); + + return settings.expanded ? miniTable.node : util.expander( + 'DOMElement (' + elname.toLowerCase() + ')', + 'Click to show more', + function() { + this.parentNode.appendChild(miniTable.node); + } + ); + }, + domnode : function(node){ + + /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ + var miniTable = util.table(['DOMNode',null], 'domelement'), + data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); + miniTable + .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) + .addRow(['data', data]); + + return settings.expanded ? miniTable.node : util.expander( + 'DOMNode', + 'Click to show more', + function() { + this.parentNode.appendChild(miniTable.node); + } + ); + }, + jquery : function(obj, depth, key) { + return typeDealer['array'](obj, depth, key, true); + }, + object : function(obj, depth, key) { + + /* Checking depth + circular refs */ + /* Note, check for circular refs before depth; just makes more sense */ + var stackKey = util.within(stack).is(obj); + if ( stackKey ) { + return util.common.circRef(obj, stackKey, settings); + } + stack[key||'TOP'] = obj; + if (depth === settings.maxDepth) { + return util.common.depthReached(obj, settings); + } + + var table = util.table(['Object', null],'object'), + isEmpty = true; + + for (var i in obj) { + if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { + var item = obj[i], + type = util.type(item); + isEmpty = false; + try { + table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); + } catch(e) { + /* Security errors are thrown on certain Window/DOM properties */ + if (window.console && window.console.log) { + console.log(e.message); + } + } + } + } + + if (isEmpty) { + table.addRow(['<small>[empty]</small>']); + } else { + table.thead.appendChild( + util.hRow(['key','value'], 'colHeader') + ); + } + + var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( + util.stringify(obj), + 'Click to show more', + function() { + this.parentNode.appendChild(table.node); + } + ); + + hasRunOnce = true; + + return ret; + + }, + array : function(arr, depth, key, jquery) { + + /* Checking depth + circular refs */ + /* Note, check for circular refs before depth; just makes more sense */ + var stackKey = util.within(stack).is(arr); + if ( stackKey ) { + return util.common.circRef(arr, stackKey); + } + stack[key||'TOP'] = arr; + if (depth === settings.maxDepth) { + return util.common.depthReached(arr); + } + + /* Accepts a table and modifies it */ + var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), + isEmpty = true, + count = 0; + + if (jquery){ + table.addRow(['selector',arr.selector]); + } - if (!jquery){ - if (isEmpty) { - table.addRow(['<small>[empty]</small>']); - } else { - table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); + util.forEach(arr, function(item,i){ + if (++count > settings.maxArray) { + table.addRow([ + i + '..' + (arr.length-1), + typeDealer[ util.type(item) ]('...', depth+1, i) + ]); + return false; } - } - - return settings.expanded ? table.node : util.expander( - util.stringify(arr), - 'Click to show more', - function() { - this.parentNode.appendChild(table.node); - } - ); - - }, - 'function' : function(fn, depth, key) { - - /* Checking JUST circular refs */ - var stackKey = util.within(stack).is(fn); - if ( stackKey ) { return util.common.circRef(fn, stackKey); } - stack[key||'TOP'] = fn; - - var miniTable = util.table(['Function',null], 'function'), - argsTable = util.table(['Arguments']), - args = fn.toString().match(/\((.+?)\)/), - body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); - - miniTable - .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) - .addRow(['body', body]); - - return settings.expanded ? miniTable.node : util.expander( - 'function(){...}', - 'Click to see more about this function.', - function(){ - this.parentNode.appendChild(miniTable.node); - } - ); - }, - 'date' : function(date) { - - var miniTable = util.table(['Date',null], 'date'), - sDate = date.toString().split(/\s/); - - /* TODO: Make this work well in IE! */ - miniTable - .addRow(['Time', sDate[4]]) - .addRow(['Date', sDate.slice(0,4).join('-')]); - - return settings.expanded ? miniTable.node : util.expander( - 'Date (timestamp): ' + (+date), - 'Click to see a little more info about this date', - function() { - this.parentNode.appendChild(miniTable.node); - } - ); - - }, - 'boolean' : function(bool) { - return util.txt( bool.toString().toUpperCase() ); - }, - 'undefined' : function() { - return util.txt('UNDEFINED'); - }, - 'null' : function() { - return util.txt('NULL'); - }, - 'default' : function() { - /* When a type cannot be found */ - return util.txt('prettyPrint: TypeNotFound Error'); - } - }; - - container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); - - return container; - - }; - - /* Configuration */ - - /* All items can be overwridden by passing an - "options" object when calling prettyPrint */ - prettyPrintThis.config = { - - /* Try setting this to false to save space */ - expanded: true, - - forceObject: false, - maxDepth: 3, - maxArray: -1, // default is unlimited - styles: { - array: { - th: { - backgroundColor: '#6DBD2A', - color: 'white' - } - }, - 'function': { - th: { - backgroundColor: '#D82525' - } - }, - regexp: { - th: { - backgroundColor: '#E2F3FB', - color: '#000' - } - }, - object: { - th: { - backgroundColor: '#1F96CF' - } - }, - jquery : { - th: { - backgroundColor: '#FBF315' - } - }, - error: { - th: { - backgroundColor: 'red', - color: 'yellow' - } - }, - domelement: { - th: { - backgroundColor: '#F3801E' - } - }, - date: { - th: { - backgroundColor: '#A725D8' - } - }, - colHeader: { - th: { - backgroundColor: '#EEE', - color: '#000', - textTransform: 'uppercase' - } - }, - 'default': { - table: { - borderCollapse: 'collapse', - width: '100%' - }, - td: { - padding: '5px', - fontSize: '12px', - backgroundColor: '#FFF', - color: '#222', - border: '1px solid #000', - verticalAlign: 'top', - fontFamily: '"Consolas","Lucida Console",Courier,mono', - whiteSpace: 'nowrap' - }, - td_hover: { - /* Styles defined here will apply to all tr:hover > td, - - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ - }, - th: { - padding: '5px', - fontSize: '12px', - backgroundColor: '#222', - color: '#EEE', - textAlign: 'left', - border: '1px solid #000', - verticalAlign: 'top', - fontFamily: '"Consolas","Lucida Console",Courier,mono', - backgroundImage: util.headerGradient, - backgroundRepeat: 'repeat-x' - } - } - } - }; - - return prettyPrintThis; - + isEmpty = false; + table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); + }); + + if (!jquery){ + if (isEmpty) { + table.addRow(['<small>[empty]</small>']); + } else { + table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); + } + } + + return settings.expanded ? table.node : util.expander( + util.stringify(arr), + 'Click to show more', + function() { + this.parentNode.appendChild(table.node); + } + ); + + }, + 'function' : function(fn, depth, key) { + + /* Checking JUST circular refs */ + var stackKey = util.within(stack).is(fn); + if ( stackKey ) { return util.common.circRef(fn, stackKey); } + stack[key||'TOP'] = fn; + + var miniTable = util.table(['Function',null], 'function'), + argsTable = util.table(['Arguments']), + args = fn.toString().match(/\((.+?)\)/), + body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); + + miniTable + .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) + .addRow(['body', body]); + + return settings.expanded ? miniTable.node : util.expander( + 'function(){...}', + 'Click to see more about this function.', + function(){ + this.parentNode.appendChild(miniTable.node); + } + ); + }, + 'date' : function(date) { + + var miniTable = util.table(['Date',null], 'date'), + sDate = date.toString().split(/\s/); + + /* TODO: Make this work well in IE! */ + miniTable + .addRow(['Time', sDate[4]]) + .addRow(['Date', sDate.slice(0,4).join('-')]); + + return settings.expanded ? miniTable.node : util.expander( + 'Date (timestamp): ' + (+date), + 'Click to see a little more info about this date', + function() { + this.parentNode.appendChild(miniTable.node); + } + ); + + }, + 'boolean' : function(bool) { + return util.txt( bool.toString().toUpperCase() ); + }, + 'undefined' : function() { + return util.txt('UNDEFINED'); + }, + 'null' : function() { + return util.txt('NULL'); + }, + 'default' : function() { + /* When a type cannot be found */ + return util.txt('prettyPrint: TypeNotFound Error'); + } + }; + + container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); + + return container; + + }; + + /* Configuration */ + + /* All items can be overwridden by passing an + "options" object when calling prettyPrint */ + prettyPrintThis.config = { + + /* Try setting this to false to save space */ + expanded: true, + + forceObject: false, + maxDepth: 3, + maxArray: -1, // default is unlimited + styles: { + array: { + th: { + backgroundColor: '#6DBD2A', + color: 'white' + } + }, + 'function': { + th: { + backgroundColor: '#D82525' + } + }, + regexp: { + th: { + backgroundColor: '#E2F3FB', + color: '#000' + } + }, + object: { + th: { + backgroundColor: '#1F96CF' + } + }, + jquery : { + th: { + backgroundColor: '#FBF315' + } + }, + error: { + th: { + backgroundColor: 'red', + color: 'yellow' + } + }, + domelement: { + th: { + backgroundColor: '#F3801E' + } + }, + date: { + th: { + backgroundColor: '#A725D8' + } + }, + colHeader: { + th: { + backgroundColor: '#EEE', + color: '#000', + textTransform: 'uppercase' + } + }, + 'default': { + table: { + borderCollapse: 'collapse', + width: '100%' + }, + td: { + padding: '5px', + fontSize: '12px', + backgroundColor: '#FFF', + color: '#222', + border: '1px solid #000', + verticalAlign: 'top', + fontFamily: '"Consolas","Lucida Console",Courier,mono', + whiteSpace: 'nowrap' + }, + td_hover: { + /* Styles defined here will apply to all tr:hover > td, + - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ + }, + th: { + padding: '5px', + fontSize: '12px', + backgroundColor: '#222', + color: '#EEE', + textAlign: 'left', + border: '1px solid #000', + verticalAlign: 'top', + fontFamily: '"Consolas","Lucida Console",Courier,mono', + backgroundImage: util.headerGradient, + backgroundRepeat: 'repeat-x' + } + } + } + }; + + return prettyPrintThis; + })();
padolsey-archive/prettyprint.js
61ea7f9f266c7b14b4cac0a10ecd167c44b4fabd
Small issue: if an array is truncated due to settings.maxArray, the largest index display was actually the array length (one too large).
diff --git a/prettyprint.js b/prettyprint.js index a24cd1b..f456a90 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,735 +1,735 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.02.1 UPDATED 07-14-2009 CONTRIBUTORS David Waller */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, max, fn) { if (!fn) { fn = max; } /* Helper: iteration */ var len = arr.length, index = -1; while ((len > ++index) && (max != index)) { if(fn( arr[index], index, arr ) === false) { break; } } if ((max == index) && (len != index)) { - fn( "...", ""+index+".."+arr.length, arr ); + fn( "...", ""+index+".."+(arr.length-1), arr ); } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, jquery : function(obj, depth, key) { return typeDealer['array'](obj, depth, key, true); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key, jquery) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), isEmpty = true; if (jquery){ table.addRow(['selector',arr.selector]); } util.forEach(arr, settings.maxArray, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (!jquery){ if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : util.expander( 'function(){...}', 'Click to see more about this function.', function(){ this.parentNode.appendChild(miniTable.node); } ); }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'), sDate = date.toString().split(/\s/); /* TODO: Make this work well in IE! */ miniTable .addRow(['Time', sDate[4]]) .addRow(['Date', sDate.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : util.expander( 'Date (timestamp): ' + (+date), 'Click to see a little more info about this date', function() { this.parentNode.appendChild(miniTable.node); } ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, maxArray: -1, // default is unlimited styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, jquery : { th: { backgroundColor: '#FBF315' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, td_hover: { /* Styles defined here will apply to all tr:hover > td, - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } };
padolsey-archive/prettyprint.js
d600ea99592ac27277797753c3d77d1013b27ac9
Adding a setting "maxArray" that allows one to limit the display length of large arrays.
diff --git a/prettyprint.js b/prettyprint.js index e8744d6..a24cd1b 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,730 +1,738 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.02.1 UPDATED 07-14-2009 CONTRIBUTORS David Waller */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, - forEach: function(arr, fn) { + forEach: function(arr, max, fn) { + if (!fn) { + fn = max; + } + /* Helper: iteration */ var len = arr.length, index = -1; - while (len > ++index) { + while ((len > ++index) && (max != index)) { if(fn( arr[index], index, arr ) === false) { break; } } + if ((max == index) && (len != index)) { + fn( "...", ""+index+".."+arr.length, arr ); + } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, jquery : function(obj, depth, key) { return typeDealer['array'](obj, depth, key, true); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key, jquery) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), isEmpty = true; if (jquery){ table.addRow(['selector',arr.selector]); } - - util.forEach(arr, function(item,i){ + + util.forEach(arr, settings.maxArray, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); - + if (!jquery){ if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : util.expander( 'function(){...}', 'Click to see more about this function.', function(){ this.parentNode.appendChild(miniTable.node); } ); }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'), sDate = date.toString().split(/\s/); /* TODO: Make this work well in IE! */ miniTable .addRow(['Time', sDate[4]]) .addRow(['Date', sDate.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : util.expander( 'Date (timestamp): ' + (+date), 'Click to see a little more info about this date', function() { this.parentNode.appendChild(miniTable.node); } ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, + maxArray: -1, // default is unlimited styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, jquery : { th: { backgroundColor: '#FBF315' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, td_hover: { /* Styles defined here will apply to all tr:hover > td, - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
36668ddf39d7f0df96384dc0498a24dc0abf3d5b
Per email from James Padolsey that I received on 2011/04/30 at 5:33AM, prettyprint.js is licensed under the 2 clause BSD license.
diff --git a/prettyprint.js b/prettyprint.js index e8744d6..194f439 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,730 +1,760 @@ /* +Copyright (c) 2009 James Padolsey. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY James Padolsey ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL James Padolsey OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are +those of the authors and should not be interpreted as representing official +policies, either expressed or implied, of James Padolsey. + AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.02.1 UPDATED 07-14-2009 CONTRIBUTORS David Waller + */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, jquery : function(obj, depth, key) { return typeDealer['array'](obj, depth, key, true); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key, jquery) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), isEmpty = true; if (jquery){ table.addRow(['selector',arr.selector]); } util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (!jquery){ if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : util.expander( 'function(){...}', 'Click to see more about this function.', function(){ this.parentNode.appendChild(miniTable.node); } ); }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'), sDate = date.toString().split(/\s/); /* TODO: Make this work well in IE! */ miniTable .addRow(['Time', sDate[4]]) .addRow(['Date', sDate.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : util.expander( 'Date (timestamp): ' + (+date), 'Click to see a little more info about this date', function() { this.parentNode.appendChild(miniTable.node); } ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, jquery : { th: { backgroundColor: '#FBF315' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, td_hover: { /* Styles defined here will apply to all tr:hover > td, - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; -})(); \ No newline at end of file +})();
padolsey-archive/prettyprint.js
8b69a8a516780f1ad355bec6ca6aee5c7143d3c3
Version number correction + adding David Walker as contributor
diff --git a/prettyprint.js b/prettyprint.js index 4a44067..e8744d6 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,518 +1,518 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) - VERSION 1.02.x + VERSION 1.02.1 UPDATED 07-14-2009 - - (hacked by David Waller to incorporate support for jQuery objects) + CONTRIBUTORS + David Waller */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, jquery : function(obj, depth, key) { return typeDealer['array'](obj, depth, key, true); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } );
padolsey-archive/prettyprint.js
768249e400dacec31d5e3bf8d545dfae709c66a3
added array-like treatment of jQuery objects
diff --git a/prettyprint.js b/prettyprint.js index 5b8a6be..4a44067 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,714 +1,730 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) - VERSION 1.02 - UPDATED 07-06-2009 + VERSION 1.02.x + UPDATED 07-14-2009 + + (hacked by David Waller to incorporate support for jQuery objects) */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, applyCSS: function(el, styles) { /* Applies CSS to a single element */ for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan, onmouseover: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td_hover', type)); }); }, onmouseout: function() { var tds = this.parentNode.childNodes; util.forEach(tds, function(cell){ if (cell.nodeName.toLowerCase() !== 'td') { return; } util.applyCSS(cell, util.getStyles('td', type)); }); } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { - return 'object'; + return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), - props = ['id', 'className', 'innerHTML']; + props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || ''; - miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); + miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( - 'DOMElement (' + element.nodeName.toLowerCase() + ')', + 'DOMElement (' + elname.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, + jquery : function(obj, depth, key) { + return typeDealer['array'](obj, depth, key, true); + }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, - array : function(arr, depth, key) { + array : function(arr, depth, key, jquery) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ - var table = util.table(['Array(' + arr.length + ')', null], 'array'), + var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()), isEmpty = true; + if (jquery){ + table.addRow(['selector',arr.selector]); + } + util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); - if (isEmpty) { - table.addRow(['<small>[empty]</small>']); - } else { - table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); + if (!jquery){ + if (isEmpty) { + table.addRow(['<small>[empty]</small>']); + } else { + table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); + } } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : util.expander( 'function(){...}', 'Click to see more about this function.', function(){ this.parentNode.appendChild(miniTable.node); } ); }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'), sDate = date.toString().split(/\s/); /* TODO: Make this work well in IE! */ miniTable .addRow(['Time', sDate[4]]) .addRow(['Date', sDate.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : util.expander( 'Date (timestamp): ' + (+date), 'Click to see a little more info about this date', function() { this.parentNode.appendChild(miniTable.node); } ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, + jquery : { + th: { + backgroundColor: '#FBF315' + } + }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, td_hover: { /* Styles defined here will apply to all tr:hover > td, - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
e27783e56f7e0b05048b4d6d6e0ac1590cfe0480
Added td_hover style option + util.applyCSS
diff --git a/prettyprint.js b/prettyprint.js index 1423578..5b8a6be 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,712 +1,714 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) - VERSION 1.01 - UPDATED 06-06-2009 + VERSION 1.02 + UPDATED 07-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; - for (var prop in styles) { - if (styles.hasOwnProperty(prop)) { - try{ - /* Yes, IE6 SUCKS! */ - el.style[prop] = styles[prop]; - }catch(e){} - } - } + util.applyCSS( el, attrs.style ); delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, + applyCSS: function(el, styles) { + /* Applies CSS to a single element */ + for (var prop in styles) { + if (styles.hasOwnProperty(prop)) { + try{ + /* Yes, IE6 SUCKS! */ + el.style[prop] = styles[prop]; + }catch(e){} + } + } + }, + txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), - colSpan: colSpan + colSpan: colSpan, + onmouseover: function() { + var tds = this.parentNode.childNodes; + util.forEach(tds, function(cell){ + if (cell.nodeName.toLowerCase() !== 'td') { return; } + util.applyCSS(cell, util.getStyles('td_hover', type)); + }); + }, + onmouseout: function() { + var tds = this.parentNode.childNodes; + util.forEach(tds, function(cell){ + if (cell.nodeName.toLowerCase() !== 'td') { return; } + util.applyCSS(cell, util.getStyles('td', type)); + }); + } }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), - span = util.el('span', { - innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', - onmouseover: function() { - this.getElementsByTagName('b')[0].style.visibility = 'visible'; - }, - onmouseout: function() { - this.getElementsByTagName('b')[0].style.visibility = 'hidden'; - }, - onclick: function() { - this.style.display = 'none'; - this.parentNode.appendChild(miniTable.node); - }, - style: { - cursor: 'pointer' - } - }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); - return settings.expanded ? miniTable.node : span; - }, - 'date' : function(date) { - - var miniTable = util.table(['Date',null], 'date'); - var span = util.el('span', { - innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', - onmouseover: function() { - this.getElementsByTagName('b')[0].style.visibility = 'visible'; - }, - onmouseout: function() { - this.getElementsByTagName('b')[0].style.visibility = 'hidden'; - }, - onclick: function() { - this.style.display = 'none'; + return settings.expanded ? miniTable.node : util.expander( + 'function(){...}', + 'Click to see more about this function.', + function(){ this.parentNode.appendChild(miniTable.node); - }, - style: { - cursor: 'pointer' } - }); + ); + }, + 'date' : function(date) { - date = date.toString().split(/\s/); + var miniTable = util.table(['Date',null], 'date'), + sDate = date.toString().split(/\s/); - /* TODO: Make cross-browser functional */ + /* TODO: Make this work well in IE! */ miniTable - .addRow(['Time', date[4]]) - .addRow(['Date', date.slice(0,4).join('-')]); + .addRow(['Time', sDate[4]]) + .addRow(['Date', sDate.slice(0,4).join('-')]); - return settings.expanded ? miniTable.node : span; + return settings.expanded ? miniTable.node : util.expander( + 'Date (timestamp): ' + (+date), + 'Click to see a little more info about this date', + function() { + this.parentNode.appendChild(miniTable.node); + } + ); }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, + td_hover: { + /* Styles defined here will apply to all tr:hover > td, + - Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */ + }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
cb7874eba4346455743e741e718dd8320fa055c6
Fixing function aspect ( for e.g. 'function() 1' )
diff --git a/prettyprint.js b/prettyprint.js index e84cf3b..1423578 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -51,662 +51,662 @@ var prettyPrint = (function(){ /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { if ( source.hasOwnProperty(property) ) { var sourceProperty = source[ property ]; if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), - body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); + body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
a68366ff627ad4e4c38c59f041c321108982e06f
damn you JSLINT! :D
diff --git a/prettyprint.js b/prettyprint.js index cd049a7..e84cf3b 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,675 +1,675 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.01 UPDATED 06-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { - var sourceProperty = source[ property ]; - - if ( !source.hasOwnProperty(property) ) { - continue; - } - - if ( typeof sourceProperty === 'object' ) { - target[ property ] = util.merge( target[ property ], sourceProperty ); - continue; + if ( source.hasOwnProperty(property) ) { + + var sourceProperty = source[ property ]; + + if ( typeof sourceProperty === 'object' ) { + target[ property ] = util.merge( target[ property ], sourceProperty ); + continue; + } + + target[ property ] = sourceProperty; + } - target[ property ] = sourceProperty; - } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000',
padolsey-archive/prettyprint.js
e3c4a5a5d167bfe98052838331958ea3d1b259fe
New comments + fixed <2 Chrome issue (cnvs.toDataURL)
diff --git a/prettyprint.js b/prettyprint.js index c7e5050..cd049a7 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,712 +1,712 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.01 UPDATED 06-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { var sourceProperty = source[ property ]; if ( !source.hasOwnProperty(property) ) { continue; } if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { /* Bit of an ugly duckling! - This fn returns an ATTEMPT at converting an object/array/anyType into a string, kinda like a JSON-deParser - This is used for when |settings.expanded === false| */ var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL && canvas.toDataURL(); - return 'url(' + (dataURL||'') + ')'; + return 'url(' + (dataURL || '') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
f83d3b0f892f107e30eff94d8ebd16d1efbd6bf1
Better comments + fixed canvas.toDataURL issues (i think...)
diff --git a/prettyprint.js b/prettyprint.js index 37fb8f4..c7e5050 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,705 +1,712 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.01 UPDATED 06-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(target, source) { /* Merges two (or more) objects, giving the last one precedence */ if ( typeof target !== 'object' ) { target = {}; } for (var property in source) { var sourceProperty = source[ property ]; if ( !source.hasOwnProperty(property) ) { continue; } if ( typeof sourceProperty === 'object' ) { target[ property ] = util.merge( target[ property ], sourceProperty ); continue; } target[ property ] = sourceProperty; } for (var a = 2, l = arguments.length; a < l; a++) { util.merge(target, arguments[a]); } return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.settings.styles[type] || {}; return util.merge( {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { + + /* Bit of an ugly duckling! + - This fn returns an ATTEMPT at converting an object/array/anyType + into a string, kinda like a JSON-deParser + - This is used for when |settings.expanded === false| */ + var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); - var dataURL = canvas.toDataURL(); + + var dataURL = canvas.toDataURL && canvas.toDataURL(); return 'url(' + (dataURL||'') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ options = options || {}; var settings = util.merge( {}, prettyPrintThis.config, options ), container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; /* Expose per-call settings. Note: "config" is overwritten (where necessary) by options/"settings" So, if you need to access/change *DEFAULT* settings then go via ".config" */ prettyPrintThis.settings = settings; var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
1220ac5d12533c435fe8ede1da918e2527fa8a89
Improved util,merge (it now recurses)
diff --git a/prettyprint.js b/prettyprint.js index 30db4a7..37fb8f4 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,687 +1,705 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.01 - UPDATED 05-06-2009 + UPDATED 06-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ - attrs = util.merge(attrs); + attrs = util.merge({}, attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, - merge: function(o1,o2) { - /* Merges two objects, - giving the second one precedence */ + merge: function(target, source) { - /* TODO: Deep merge */ - o1 = o1 || {}; - o2 = o2 || {}; - var ret = {}, i; - for (i in o1){ - if (o1.hasOwnProperty(i)) { - ret[i] = o1[i]; - } + /* Merges two (or more) objects, + giving the last one precedence */ + + if ( typeof target !== 'object' ) { + target = {}; } - for (i in o2){ - if (o2.hasOwnProperty(i)) { - ret[i] = o2[i]; + + for (var property in source) { + + var sourceProperty = source[ property ]; + + if ( !source.hasOwnProperty(property) ) { + continue; + } + + if ( typeof sourceProperty === 'object' ) { + target[ property ] = util.merge( target[ property ], sourceProperty ); + continue; } + + target[ property ] = sourceProperty; + + } + + for (var a = 2, l = arguments.length; a < l; a++) { + util.merge(target, arguments[a]); } - return ret; + + return target; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { - type = prettyPrintThis.config.styles[type] || {}; + type = prettyPrintThis.settings.styles[type] || {}; return util.merge( - prettyPrintThis.config.styles['default'][el], type[el] + {}, prettyPrintThis.settings.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL(); return 'url(' + (dataURL||'') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ - var settings = util.merge( prettyPrintThis.config, options ); + options = options || {}; - var container = util.el('div'), + var settings = util.merge( {}, prettyPrintThis.config, options ), + container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; + /* Expose per-call settings. + Note: "config" is overwritten (where necessary) by options/"settings" + So, if you need to access/change *DEFAULT* settings then go via ".config" */ + prettyPrintThis.settings = settings; + var typeDealer = { string : function(item){ return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; if (depth === settings.maxDepth) { return util.common.depthReached(arr); } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ /* All items can be overwridden by passing an "options" object when calling prettyPrint */ prettyPrintThis.config = { /* Try setting this to false to save space */ expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
6a2e2526a79aa4d5ef80c49ccbd315a60b67568a
Improving comments a bit
diff --git a/prettyprint.js b/prettyprint.js index d209b3c..30db4a7 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,671 +1,687 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) - VERSION 1.0 + VERSION 1.01 UPDATED 05-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge(attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(o1,o2) { /* Merges two objects, giving the second one precedence */ + + /* TODO: Deep merge */ o1 = o1 || {}; o2 = o2 || {}; var ret = {}, i; for (i in o1){ if (o1.hasOwnProperty(i)) { ret[i] = o1[i]; } } for (i in o2){ if (o2.hasOwnProperty(i)) { ret[i] = o2[i]; } } return ret; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.config.styles[type] || {}; return util.merge( prettyPrintThis.config.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL(); return 'url(' + (dataURL||'') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ var settings = util.merge( prettyPrintThis.config, options ); var container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; var typeDealer = { string : function(item){ - //return util.el('div'); return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ - if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } + /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(obj); - if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } + if ( stackKey ) { + return util.common.circRef(obj, stackKey, settings); + } stack[key||'TOP'] = obj; + if (depth === settings.maxDepth) { + return util.common.depthReached(obj, settings); + } - var table = util.table(['Object',null],'object'), + var table = util.table(['Object', null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { - /* Security errors are thrown on certain Window properties */ + /* Security errors are thrown on certain Window/DOM properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ - if (depth === settings.maxDepth) { return util.common.depthReached(arr); } + /* Note, check for circular refs before depth; just makes more sense */ var stackKey = util.within(stack).is(arr); - if ( stackKey ) { return util.common.circRef(arr, stackKey); } + if ( stackKey ) { + return util.common.circRef(arr, stackKey); + } stack[key||'TOP'] = arr; + if (depth === settings.maxDepth) { + return util.common.depthReached(arr); + } /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); + /* TODO: Make cross-browser functional */ miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ + + /* All items can be overwridden by passing an + "options" object when calling prettyPrint */ prettyPrintThis.config = { + + /* Try setting this to false to save space */ expanded: true, + forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', - whiteSpace: 'nowrap', - backgroundImage: util.innerShadows, - backgroundRepeat: 'repeat-x' + whiteSpace: 'nowrap' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
ed94a997925c6bf269b780712c17fd27cf284886
Removing redundancy
diff --git a/demo.html b/demo.html index 6263e64..d33587c 100644 --- a/demo.html +++ b/demo.html @@ -1,63 +1,63 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>PrettyPrint</title> <script type="text/javascript" src="http://localhost/jquery-1.3.js"></script> <style type="text/css"> body {background:#EEE;color:#222;font:0.8em Arial,Verdana,Sans-Serif;margin:0;padding:20px;} #debug { width: 700px; } </style> </head> <body> <!-- prettyPrint demo --> <div id="debug"></div> <script src="prettyprint.js"></script> <script> var randomObject = { someNumber: 99283, someRegexyThing: new RegExp('a'), someFunction: function(arg1, arg2, arg3) { doSomethingAmazing(); }, anotherObject: { prop: [1,2,3,{a:1}], prop2: [ new Date(), "som\"ething else" ] }, domThing: document.body.firstChild }; randomObject.circularRef = randomObject; - var ppTable = prettyPrint(randomObject,{expanded:false}); + var ppTable = prettyPrint(randomObject); document.getElementById('debug').appendChild(ppTable); </script> </body> </html> diff --git a/prettyprint.js b/prettyprint.js index 0b8ddcc..d209b3c 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,677 +1,671 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.0 UPDATED 05-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge(attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(o1,o2) { /* Merges two objects, giving the second one precedence */ o1 = o1 || {}; o2 = o2 || {}; var ret = {}, i; for (i in o1){ if (o1.hasOwnProperty(i)) { ret[i] = o1[i]; } } for (i in o2){ if (o2.hasOwnProperty(i)) { ret[i] = o2[i]; } } return ret; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.config.styles[type] || {}; return util.merge( prettyPrintThis.config.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { var type = util.type(obj), str, first = true; if ( type === 'array' ) { str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL(); return 'url(' + (dataURL||'') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ var settings = util.merge( prettyPrintThis.config, options ); var container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; var typeDealer = { string : function(item){ //return util.el('div'); return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; var table = util.table(['Object',null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ if (depth === settings.maxDepth) { return util.common.depthReached(arr); } var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; - /* Check that we've not reached maxDepth */ - if (depth === settings.maxDepth) { - //table.addRow( [i, util.common.depthReached()] ); - return 'DR'; - } - util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ prettyPrintThis.config = { expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap', backgroundImage: util.innerShadows, backgroundRepeat: 'repeat-x' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
padolsey-archive/prettyprint.js
103b4028ecae0db78428f529a9c9fbcf7e226b77
Must please JSlint
diff --git a/demo.html b/demo.html index d33587c..6263e64 100644 --- a/demo.html +++ b/demo.html @@ -1,63 +1,63 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>PrettyPrint</title> <script type="text/javascript" src="http://localhost/jquery-1.3.js"></script> <style type="text/css"> body {background:#EEE;color:#222;font:0.8em Arial,Verdana,Sans-Serif;margin:0;padding:20px;} #debug { width: 700px; } </style> </head> <body> <!-- prettyPrint demo --> <div id="debug"></div> <script src="prettyprint.js"></script> <script> var randomObject = { someNumber: 99283, someRegexyThing: new RegExp('a'), someFunction: function(arg1, arg2, arg3) { doSomethingAmazing(); }, anotherObject: { prop: [1,2,3,{a:1}], prop2: [ new Date(), "som\"ething else" ] }, domThing: document.body.firstChild }; randomObject.circularRef = randomObject; - var ppTable = prettyPrint(randomObject); + var ppTable = prettyPrint(randomObject,{expanded:false}); document.getElementById('debug').appendChild(ppTable); </script> </body> </html> diff --git a/prettyprint.js b/prettyprint.js index be8ba9b..0b8ddcc 100644 --- a/prettyprint.js +++ b/prettyprint.js @@ -1,676 +1,677 @@ /* AUTHOR James Padolsey (http://james.padolsey.com) VERSION 1.0 UPDATED 05-06-2009 */ var prettyPrint = (function(){ /* These "util" functions are not part of the core functionality but are all necessary - mostly DOM helpers */ var util = { el: function(type, attrs) { /* Create new element */ var el = document.createElement(type), attr; /*Copy to single object */ attrs = util.merge(attrs); /* Add attributes to el */ if (attrs && attrs.style) { var styles = attrs.style; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { try{ /* Yes, IE6 SUCKS! */ el.style[prop] = styles[prop]; }catch(e){} } } delete attrs.style; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { el[attr] = attrs[attr]; } } return el; }, txt: function(t) { /* Create text node */ return document.createTextNode(t); }, row: function(cells, type, cellType) { /* Creates new <tr> */ cellType = cellType || 'td'; /* colSpan is calculated by length of null items in array */ var colSpan = util.count(cells, null) + 1, tr = util.el('tr'), td, attrs = { style: util.getStyles(cellType, type), colSpan: colSpan }; util.forEach(cells, function(cell){ if (cell === null) { return; } /* Default cell type is <td> */ td = util.el(cellType, attrs); if (cell.nodeType) { /* IsDomElement */ td.appendChild(cell); } else { /* IsString */ td.innerHTML = util.shorten(cell.toString()); } tr.appendChild(td); }); return tr; }, hRow: function(cells, type){ /* Return new <th> */ return util.row(cells, type, 'th'); }, table: function(headings, type){ headings = headings || []; /* Creates new table: */ var attrs = { thead: { style:util.getStyles('thead',type) }, tbody: { style:util.getStyles('tbody',type) }, table: { style:util.getStyles('table',type) } }, tbl = util.el('table', attrs.table), thead = util.el('thead', attrs.thead), tbody = util.el('tbody', attrs.tbody); if (headings.length) { tbl.appendChild(thead); thead.appendChild( util.hRow(headings, type) ); } tbl.appendChild(tbody); return { /* Facade for dealing with table/tbody Actual table node is this.node: */ node: tbl, tbody: tbody, thead: thead, appendChild: function(node) { this.tbody.appendChild(node); }, addRow: function(cells, _type, cellType){ this.appendChild(util.row.call(util, cells, (_type || type), cellType)); return this; } }; }, shorten: function(str) { var max = 40; str = str.replace(/^\s\s*|\s\s*$|\n/g,''); return str.length > max ? (str.substring(0, max-1) + '...') : str; }, htmlentities: function(str) { return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }, merge: function(o1,o2) { /* Merges two objects, giving the second one precedence */ o1 = o1 || {}; o2 = o2 || {}; var ret = {}, i; for (i in o1){ if (o1.hasOwnProperty(i)) { ret[i] = o1[i]; } } for (i in o2){ if (o2.hasOwnProperty(i)) { ret[i] = o2[i]; } } return ret; }, count: function(arr, item) { var count = 0; for (var i = 0, l = arr.length; i< l; i++) { if (arr[i] === item) { count++; } } return count; }, thead: function(tbl) { return tbl.getElementsByTagName('thead')[0]; }, forEach: function(arr, fn) { /* Helper: iteration */ var len = arr.length, index = -1; while (len > ++index) { if(fn( arr[index], index, arr ) === false) { break; } } return true; }, type: function(v){ try { /* Returns type, e.g. "string", "number", "array" etc. Note, this is only used for precise typing. */ if (v === null) { return 'null'; } if (v === undefined) { return 'undefined'; } var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase(); if (v.nodeType) { if (v.nodeType === 1) { return 'domelement'; } return 'domnode'; } if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) { return oType; } if (typeof v === 'object') { return 'object'; } if (v === window || v === document) { return 'object'; } return 'default'; } catch(e) { return 'default'; } }, within: function(ref) { /* Check existence of a val within an object RETURNS KEY */ return { is: function(o) { for (var i in ref) { if (ref[i] === o) { return i; } } return ''; } }; }, common: { circRef: function(obj, key, settings) { return util.expander( '[POINTS BACK TO <strong>' + (key) + '</strong>]', 'Click to show this item anyway', function() { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } ); }, depthReached: function(obj, settings) { return util.expander( '[DEPTH REACHED]', 'Click to show this item anyway', function() { try { this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) ); } catch(e) { this.parentNode.appendChild( util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node ); } } ); } }, getStyles: function(el, type) { type = prettyPrintThis.config.styles[type] || {}; return util.merge( prettyPrintThis.config.styles['default'][el], type[el] ); }, expander: function(text, title, clickFn) { return util.el('a', { innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>', title: title, onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; clickFn.call(this); return false; }, style: { cursor: 'pointer' } }); }, stringify: function(obj) { - var type = util.type(obj); + var type = util.type(obj), + str, first = true; if ( type === 'array' ) { - var str = '['; + str = '['; util.forEach(obj, function(item,i){ str += (i===0?'':', ') + util.stringify(item); }); return str + ']'; } if (typeof obj === 'object') { - var str = '{', first = true; + str = '{'; for (var i in obj){ if (obj.hasOwnProperty(i)) { str += (first?'':', ') + i + ':' + util.stringify(obj[i]); first = false; } } return str + '}'; } if (type === 'regexp') { return '/' + obj.source + '/'; } if (type === 'string') { return '"' + obj.replace(/"/g,'\\"') + '"'; } return obj.toString(); }, headerGradient: (function(){ var canvas = document.createElement('canvas'); if (!canvas.getContext) { return ''; } var cx = canvas.getContext('2d'); canvas.height = 30; canvas.width = 1; var linearGrad = cx.createLinearGradient(0,0,0,30); linearGrad.addColorStop(0,'rgba(0,0,0,0)'); linearGrad.addColorStop(1,'rgba(0,0,0,0.25)'); cx.fillStyle = linearGrad; cx.fillRect(0,0,1,30); var dataURL = canvas.toDataURL(); return 'url(' + (dataURL||'') + ')'; })() }; // Main.. var prettyPrintThis = function(obj, options) { /* * obj :: Object to be printed * options :: Options (merged with config) */ var settings = util.merge( prettyPrintThis.config, options ); var container = util.el('div'), config = prettyPrintThis.config, currentDepth = 0, stack = {}, hasRunOnce = false; var typeDealer = { string : function(item){ //return util.el('div'); return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"'); }, number : function(item) { return util.txt(item); }, regexp : function(item) { var miniTable = util.table(['RegExp',null], 'regexp'); var flags = util.table(); var span = util.expander( '/' + item.source + '/', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); flags .addRow(['g', item.global]) .addRow(['i', item.ignoreCase]) .addRow(['m', item.multiline]); miniTable .addRow(['source', '/' + item.source + '/']) .addRow(['flags', flags.node]) .addRow(['lastIndex', item.lastIndex]); return settings.expanded ? miniTable.node : span; }, domelement : function(element, depth) { var miniTable = util.table(['DOMElement',null], 'domelement'), props = ['id', 'className', 'innerHTML']; miniTable.addRow(['tag', '&lt;' + element.nodeName.toLowerCase() + '&gt;']); util.forEach(props, function(prop){ if ( element[prop] ) { miniTable.addRow([ prop, util.htmlentities(element[prop]) ]); } }); return settings.expanded ? miniTable.node : util.expander( 'DOMElement (' + element.nodeName.toLowerCase() + ')', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, domnode : function(node){ /* Deals with all DOMNodes that aren't elements (nodeType !== 1) */ var miniTable = util.table(['DOMNode',null], 'domelement'), data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') ); miniTable .addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')']) .addRow(['data', data]); return settings.expanded ? miniTable.node : util.expander( 'DOMNode', 'Click to show more', function() { this.parentNode.appendChild(miniTable.node); } ); }, object : function(obj, depth, key) { /* Checking depth + circular refs */ if (depth === settings.maxDepth) { return util.common.depthReached(obj, settings); } var stackKey = util.within(stack).is(obj); if ( stackKey ) { return util.common.circRef(obj, stackKey, settings); } stack[key||'TOP'] = obj; var table = util.table(['Object',null],'object'), isEmpty = true; for (var i in obj) { if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) { var item = obj[i], type = util.type(item); isEmpty = false; try { table.addRow([i, typeDealer[ type ](item, depth+1, i)], type); } catch(e) { /* Security errors are thrown on certain Window properties */ if (window.console && window.console.log) { console.log(e.message); } } } } if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['key','value'], 'colHeader') ); } var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander( util.stringify(obj), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); hasRunOnce = true; return ret; }, array : function(arr, depth, key) { /* Checking depth + circular refs */ if (depth === settings.maxDepth) { return util.common.depthReached(arr); } var stackKey = util.within(stack).is(arr); if ( stackKey ) { return util.common.circRef(arr, stackKey); } stack[key||'TOP'] = arr; /* Accepts a table and modifies it */ var table = util.table(['Array(' + arr.length + ')', null], 'array'), isEmpty = true; /* Check that we've not reached maxDepth */ if (depth === settings.maxDepth) { //table.addRow( [i, util.common.depthReached()] ); return 'DR'; } util.forEach(arr, function(item,i){ isEmpty = false; table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]); }); if (isEmpty) { table.addRow(['<small>[empty]</small>']); } else { table.thead.appendChild( util.hRow(['index','value'], 'colHeader') ); } return settings.expanded ? table.node : util.expander( util.stringify(arr), 'Click to show more', function() { this.parentNode.appendChild(table.node); } ); }, 'function' : function(fn, depth, key) { /* Checking JUST circular refs */ var stackKey = util.within(stack).is(fn); if ( stackKey ) { return util.common.circRef(fn, stackKey); } stack[key||'TOP'] = fn; var miniTable = util.table(['Function',null], 'function'), span = util.el('span', { innerHTML: 'function(){...} <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }), argsTable = util.table(['Arguments']), args = fn.toString().match(/\((.+?)\)/), body = fn.toString().match(/\{([\S\s]+)/)[1].replace(/\}$/,''); miniTable .addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>']) .addRow(['body', body]); return settings.expanded ? miniTable.node : span; }, 'date' : function(date) { var miniTable = util.table(['Date',null], 'date'); var span = util.el('span', { innerHTML: (+date) + ' <b style="visibility:hidden;">[+]</b>', onmouseover: function() { this.getElementsByTagName('b')[0].style.visibility = 'visible'; }, onmouseout: function() { this.getElementsByTagName('b')[0].style.visibility = 'hidden'; }, onclick: function() { this.style.display = 'none'; this.parentNode.appendChild(miniTable.node); }, style: { cursor: 'pointer' } }); date = date.toString().split(/\s/); miniTable .addRow(['Time', date[4]]) .addRow(['Date', date.slice(0,4).join('-')]); return settings.expanded ? miniTable.node : span; }, 'boolean' : function(bool) { return util.txt( bool.toString().toUpperCase() ); }, 'undefined' : function() { return util.txt('UNDEFINED'); }, 'null' : function() { return util.txt('NULL'); }, 'default' : function() { /* When a type cannot be found */ return util.txt('prettyPrint: TypeNotFound Error'); } }; container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) ); return container; }; /* Configuration */ prettyPrintThis.config = { expanded: true, forceObject: false, maxDepth: 3, styles: { array: { th: { backgroundColor: '#6DBD2A', color: 'white' } }, 'function': { th: { backgroundColor: '#D82525' } }, regexp: { th: { backgroundColor: '#E2F3FB', color: '#000' } }, object: { th: { backgroundColor: '#1F96CF' } }, error: { th: { backgroundColor: 'red', color: 'yellow' } }, domelement: { th: { backgroundColor: '#F3801E' } }, date: { th: { backgroundColor: '#A725D8' } }, colHeader: { th: { backgroundColor: '#EEE', color: '#000', textTransform: 'uppercase' } }, 'default': { table: { borderCollapse: 'collapse', width: '100%' }, td: { padding: '5px', fontSize: '12px', backgroundColor: '#FFF', color: '#222', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', whiteSpace: 'nowrap', backgroundImage: util.innerShadows, backgroundRepeat: 'repeat-x' }, th: { padding: '5px', fontSize: '12px', backgroundColor: '#222', color: '#EEE', textAlign: 'left', border: '1px solid #000', verticalAlign: 'top', fontFamily: '"Consolas","Lucida Console",Courier,mono', backgroundImage: util.headerGradient, backgroundRepeat: 'repeat-x' } } } }; return prettyPrintThis; })(); \ No newline at end of file
antimatter15/fluidizer
ded96d9537ab76dd2b83301878b1455109aa1123
changed from welfarehost.com to chemicalservers.com
diff --git a/bookmarklet.js b/bookmarklet.js index 937a94c..5c125d7 100644 --- a/bookmarklet.js +++ b/bookmarklet.js @@ -1 +1 @@ -javascript:(function(){function k(a){return(a||"").replace(/^\s+|\s+$/g,"")}function u(a,g){var b=new XMLHttpRequest;b.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(a),true);b.onreadystatechange=function(){b.readyState==4&&b.status==200&&g(b.responseText)};b.send()}function o(){for(var a=0,g=0,b=false,h="*,div,p,body,span".split(",");!b&&g++<20;){if(document.body.scrollWidth>window.innerWidth){b=true;a-=100}else a+=100;for(var c=d.length;c--;){var f=d[c].text;try{for(var i=document.querySelectorAll(f),l=i.length;l--;){var n=i[l],p=parseFloat(d[c].width,10),q=d[c].width.replace(/^[\-\d\.]+/,"");if(q!="px")if(q=="em")p*=16;else console.warn("not used to handling non-px units");if(p>400&&h.indexOf(f)==-1){if(!n.a)n.a=p;n.style.width=n.a+a+"px"}}}catch(x){}}}try{c=d.length;a=0;for(var r;c--;)if(h.indexOf(d[c].text)==-1)try{var j=document.querySelectorAll(d[c].text);if(j.length==1&&j[0].getElementsByTagName("*").length>15&&(j[0]==document.body||j[0].parentNode==document.body||j[0].parentNode.parentNode==document.body))if(parseInt(d[c].width,10)>a){a=parseInt(d[c].width,10);r=j[0]}}catch(y){}if(a>500)r.style.width="100%"}catch(z){}}function v(a){function g(){var i=h.split(";").map(function(l){if(k(l.split(":")[0])=="width")return k(l.split(":")[1]);return""}).join("");b&&k(b)&&i&&k(i)&&d.push({text:k(b),width:i});h=b=""}for(var b="",h="",c=0,f=0;f<a.length;f++)if(a[f]=="{")c=1;else if(a[f]=="}"){g();c=0}else if(c==0)b+=a[f];else if(c==1)h+=a[f];g();o()}for(var d=[],s=document.styleSheets,t=s.length;t--;){var e=s[t];if(e.href&&!e.cssRules){console.log(e.href);u(e.href,v)}else{e=e.cssRules;for(var m=e.length;m--;){var w=e[m].selectorText;e[m].style&&e[m].style.width&&d.push({text:w,width:e[m].style.width})}}}window.addEventListener("resize",function(){setTimeout(function(){o()},100)});o()})(); +javascript:(function(){function k(a){return(a||"").replace(/^\s+|\s+$/g,"")}function u(a,g){var b=new XMLHttpRequest;b.open("GET","http://anti15.chemicalservers.com/cssproxy.php?cssurl="+encodeURIComponent(a),true);b.onreadystatechange=function(){b.readyState==4&&b.status==200&&g(b.responseText)};b.send()}function o(){for(var a=0,g=0,b=false,h="*,div,p,body,span".split(",");!b&&g++<20;){if(document.body.scrollWidth>window.innerWidth){b=true;a-=100}else a+=100;for(var c=d.length;c--;){var f=d[c].text;try{for(var i=document.querySelectorAll(f),l=i.length;l--;){var n=i[l],p=parseFloat(d[c].width,10),q=d[c].width.replace(/^[\-\d\.]+/,"");if(q!="px")if(q=="em")p*=16;else console.warn("not used to handling non-px units");if(p>400&&h.indexOf(f)==-1){if(!n.a)n.a=p;n.style.width=n.a+a+"px"}}}catch(x){}}}try{c=d.length;a=0;for(var r;c--;)if(h.indexOf(d[c].text)==-1)try{var j=document.querySelectorAll(d[c].text);if(j.length==1&&j[0].getElementsByTagName("*").length>15&&(j[0]==document.body||j[0].parentNode==document.body||j[0].parentNode.parentNode==document.body))if(parseInt(d[c].width,10)>a){a=parseInt(d[c].width,10);r=j[0]}}catch(y){}if(a>500)r.style.width="100%"}catch(z){}}function v(a){function g(){var i=h.split(";").map(function(l){if(k(l.split(":")[0])=="width")return k(l.split(":")[1]);return""}).join("");b&&k(b)&&i&&k(i)&&d.push({text:k(b),width:i});h=b=""}for(var b="",h="",c=0,f=0;f<a.length;f++)if(a[f]=="{")c=1;else if(a[f]=="}"){g();c=0}else if(c==0)b+=a[f];else if(c==1)h+=a[f];g();o()}for(var d=[],s=document.styleSheets,t=s.length;t--;){var e=s[t];if(e.href&&!e.cssRules){console.log(e.href);u(e.href,v)}else{e=e.cssRules;for(var m=e.length;m--;){var w=e[m].selectorText;e[m].style&&e[m].style.width&&d.push({text:w,width:e[m].style.width})}}}window.addEventListener("resize",function(){setTimeout(function(){o()},100)});o()})(); diff --git a/fluidizer-beta.js b/fluidizer-beta.js index 0f92ecb..e6c85ce 100644 --- a/fluidizer-beta.js +++ b/fluidizer-beta.js @@ -1,130 +1,130 @@ function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} var selectors = [] function download(url, callback){ var xhr = new XMLHttpRequest(); - xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.open("GET","http://anti15.chemicalservers.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ callback(xhr.responseText); } } xhr.send() } //TODO: implement function update_selectors(){ var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; try{ var els = document.querySelectorAll(selectors[selectorx].text); if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) ){ if(parseInt(selectors[selectorx].width,10) > maxWidth){ maxWidth = parseInt(selectors[selectorx].width,10); maxEl = els[0]; } } }catch(err){} } var lmh = 0, bsh = document.body.scrollHeight; if(maxEl) lmh = maxEl.scrollHeight; while(!end && count++ < 20){ if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ end = true; delta -= 100; //console.log('sub') }else{ delta += 100; //console.log('add') } if(maxEl){ lmh = maxEl.scrollHeight; } bsh = document.body.scrollHeight; for(var selectorx = selectors.length; selectorx--;){ var selector = selectors[selectorx].text; for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ var element = elements[elementx]; //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); var width = parseFloat(selectors[selectorx].width,10); var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js if(unit != "px"){ if(unit == "em"){ width = width * 16; }else{ console.warn("not used to handling non-px units") } } if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. if(!element._originalWidth) element._originalWidth = width; element.style.width = (element._originalWidth + delta) + "px"; //console.log(delta, element, (element._originalWidth + delta) + "px") } } } } if(maxWidth > 500){ maxEl.style.width = "100%"; maxEl.style.padding = "10px" } } function load(text){ var selector = "", body = "", mode = 0; function add_selector(){ var width = body.split(";").map(function(e){ if(trim(e.split(":")[0]) == "width"){ return trim(e.split(":")[1]); } return ""; }).join("") if(selector && trim(selector) && width && trim(width)){ selectors.push({text: trim(selector), width: width}); } selector = ""; body = "" } for(var i = 0; i < text.length; i++){ if(text[i] == "{"){ mode = 1; }else if(text[i] == "}"){ add_selector() mode = 0; }else if(mode == 0){ selector += text[i]; }else if(mode == 1){ body += text[i]; } } add_selector() update_selectors() } for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ var sheet = sheets[sheetx]; if(sheet.href && !sheet.cssRules){ console.log(sheet.href) download(sheet.href, load) }else{ for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ var selector = rules[rulex].selectorText; if(rules[rulex].style && rules[rulex].style.width){ selectors.push({text: selector, width: rules[rulex].style.width}); } } } } update_selectors(); diff --git a/fluidizer-complex.js b/fluidizer-complex.js index ff92a76..766e357 100644 --- a/fluidizer-complex.js +++ b/fluidizer-complex.js @@ -1,142 +1,142 @@ function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} var selectors = [] function download(url, callback){ var xhr = new XMLHttpRequest(); - xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.open("GET","http://anti15.chemicalservers.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ callback(xhr.responseText); } } xhr.send() } //TODO: implement function update_selectors(){ var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; try{ var els = document.querySelectorAll(selectors[selectorx].text); if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) ){ if(parseInt(selectors[selectorx].width,10) > maxWidth){ maxWidth = parseInt(selectors[selectorx].width,10); maxEl = els[0]; } } }catch(err){} } var lmh = 0, bsh = document.body.scrollHeight; if(maxEl) lmh = maxEl.scrollHeight; while(!end && count++ < 20){ var fixright = [] for(var selectorx = selectors.length; selectorx--;){ var els = document.querySelectorAll(selectors[selectorx].text) for(var len = els.length; len--;){ if(getComputedStyle(els[len], null).getPropertyValue("float") == "right"){ els[len].style['float'] = "left"; fixright.push(els[len]); } } } if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ end = true; delta -= 100; //console.log('sub') }else{ delta += 100; //console.log('add') } if(maxEl){ lmh = maxEl.scrollHeight; } bsh = document.body.scrollHeight; for(var i = 0; i < fixright.length; i++){ fixright[i].style['float'] = ""; } for(var selectorx = selectors.length; selectorx--;){ var selector = selectors[selectorx].text; for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ var element = elements[elementx]; //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); var width = parseFloat(selectors[selectorx].width,10); var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js if(unit != "px"){ if(unit == "em"){ width = width * 16; }else{ console.warn("not used to handling non-px units") } } if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. if(!element._originalWidth) element._originalWidth = width; element.style.width = (element._originalWidth + delta) + "px"; //console.log(delta, element, (element._originalWidth + delta) + "px") } } } } if(maxWidth > 500){ maxEl.style.width = "100%"; maxEl.style.padding = "10px" } } function load(text){ var selector = "", body = "", mode = 0; function add_selector(){ var width = body.split(";").map(function(e){ if(trim(e.split(":")[0]) == "width"){ return trim(e.split(":")[1]); } return ""; }).join("") if(selector && trim(selector) && width && trim(width)){ selectors.push({text: trim(selector), width: width}); } selector = ""; body = "" } for(var i = 0; i < text.length; i++){ if(text[i] == "{"){ mode = 1; }else if(text[i] == "}"){ add_selector() mode = 0; }else if(mode == 0){ selector += text[i]; }else if(mode == 1){ body += text[i]; } } add_selector() update_selectors() } for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ var sheet = sheets[sheetx]; if(sheet.href && !sheet.cssRules){ console.log(sheet.href) download(sheet.href, load) }else{ for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ var selector = rules[rulex].selectorText; if(rules[rulex].style && rules[rulex].style.width){ selectors.push({text: selector, width: rules[rulex].style.width}); } } } } update_selectors(); diff --git a/fluidizer-simple.js b/fluidizer-simple.js index 73e1323..a62a61a 100644 --- a/fluidizer-simple.js +++ b/fluidizer-simple.js @@ -1,130 +1,130 @@ (function(){ function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} var selectors = []; function download(url, callback){ var xhr = new XMLHttpRequest(); - xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.open("GET","http://anti15.chemicalservers.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ callback(xhr.responseText); } } xhr.send() } //TODO: implement function update_selectors(){ var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); while(!end && count++ < 20){ if(document.body.scrollWidth > window.innerWidth){ end = true; delta -= 100; //console.log('sub') }else{ delta += 100; //console.log('add') } for(var selectorx = selectors.length; selectorx--;){ var selector = selectors[selectorx].text; try{ for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ var element = elements[elementx]; //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); var width = parseFloat(selectors[selectorx].width,10); var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js if(unit != "px"){ if(unit == "em"){ width = width * 16; }else{ console.warn("not used to handling non-px units") } } if(width > 400 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. if(!element._originalWidth) element._originalWidth = width; element.style.width = (element._originalWidth + delta) + "px"; } } }catch(err){} } } try{ for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; try{ var els = document.querySelectorAll(selectors[selectorx].text); if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) ){ if(parseInt(selectors[selectorx].width,10) > maxWidth){ maxWidth = parseInt(selectors[selectorx].width,10); maxEl = els[0]; } } }catch(err){} } if(maxWidth > 500){ maxEl.style.width = "100%"; } }catch(err){} } function load(text){ var selector = "", body = "", mode = 0; function add_selector(){ var width = body.split(";").map(function(e){ if(trim(e.split(":")[0]) == "width"){ return trim(e.split(":")[1]); } return ""; }).join("") if(selector && trim(selector) && width && trim(width)){ selectors.push({text: trim(selector), width: width}); } selector = ""; body = "" } for(var i = 0; i < text.length; i++){ if(text[i] == "{"){ mode = 1; }else if(text[i] == "}"){ add_selector() mode = 0; }else if(mode == 0){ selector += text[i]; }else if(mode == 1){ body += text[i]; } } add_selector() update_selectors() } for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ var sheet = sheets[sheetx]; if(sheet.href && !sheet.cssRules){ console.log(sheet.href) download(sheet.href, load) }else{ for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ var selector = rules[rulex].selectorText; if(rules[rulex].style && rules[rulex].style.width){ selectors.push({text: selector, width: rules[rulex].style.width}); } } } } window.addEventListener("resize", function(){ setTimeout(function(){ update_selectors(); },100) }) update_selectors(); })() diff --git a/fluidizer.js b/fluidizer.js index ff92a76..766e357 100644 --- a/fluidizer.js +++ b/fluidizer.js @@ -1,142 +1,142 @@ function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} var selectors = [] function download(url, callback){ var xhr = new XMLHttpRequest(); - xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.open("GET","http://anti15.chemicalservers.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ callback(xhr.responseText); } } xhr.send() } //TODO: implement function update_selectors(){ var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; try{ var els = document.querySelectorAll(selectors[selectorx].text); if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) ){ if(parseInt(selectors[selectorx].width,10) > maxWidth){ maxWidth = parseInt(selectors[selectorx].width,10); maxEl = els[0]; } } }catch(err){} } var lmh = 0, bsh = document.body.scrollHeight; if(maxEl) lmh = maxEl.scrollHeight; while(!end && count++ < 20){ var fixright = [] for(var selectorx = selectors.length; selectorx--;){ var els = document.querySelectorAll(selectors[selectorx].text) for(var len = els.length; len--;){ if(getComputedStyle(els[len], null).getPropertyValue("float") == "right"){ els[len].style['float'] = "left"; fixright.push(els[len]); } } } if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ end = true; delta -= 100; //console.log('sub') }else{ delta += 100; //console.log('add') } if(maxEl){ lmh = maxEl.scrollHeight; } bsh = document.body.scrollHeight; for(var i = 0; i < fixright.length; i++){ fixright[i].style['float'] = ""; } for(var selectorx = selectors.length; selectorx--;){ var selector = selectors[selectorx].text; for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ var element = elements[elementx]; //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); var width = parseFloat(selectors[selectorx].width,10); var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js if(unit != "px"){ if(unit == "em"){ width = width * 16; }else{ console.warn("not used to handling non-px units") } } if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. if(!element._originalWidth) element._originalWidth = width; element.style.width = (element._originalWidth + delta) + "px"; //console.log(delta, element, (element._originalWidth + delta) + "px") } } } } if(maxWidth > 500){ maxEl.style.width = "100%"; maxEl.style.padding = "10px" } } function load(text){ var selector = "", body = "", mode = 0; function add_selector(){ var width = body.split(";").map(function(e){ if(trim(e.split(":")[0]) == "width"){ return trim(e.split(":")[1]); } return ""; }).join("") if(selector && trim(selector) && width && trim(width)){ selectors.push({text: trim(selector), width: width}); } selector = ""; body = "" } for(var i = 0; i < text.length; i++){ if(text[i] == "{"){ mode = 1; }else if(text[i] == "}"){ add_selector() mode = 0; }else if(mode == 0){ selector += text[i]; }else if(mode == 1){ body += text[i]; } } add_selector() update_selectors() } for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ var sheet = sheets[sheetx]; if(sheet.href && !sheet.cssRules){ console.log(sheet.href) download(sheet.href, load) }else{ for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ var selector = rules[rulex].selectorText; if(rules[rulex].style && rules[rulex].style.width){ selectors.push({text: selector, width: rules[rulex].style.width}); } } } } update_selectors();
antimatter15/fluidizer
7a7610b268d433041a4046602405c79948053a5d
Added a readme
diff --git a/README.md b/README.md index e69de29..df605b9 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,14 @@ +So. What is fluidizer? + +Basically, I felt fixed-width layouts were really wasteful. With the advent of really large monitors, I don't consider mine large at all, but my left monitor is 1600px wide. Why is it that many if not most sites are still stuck with a 900px-wide content area? Heaven forbid layouts with even *less* than that, but I've seen it. + +There probably is some typographical eye-tracking scientific super-awesome explanation-- maybe the eye just hates having to skim long lines and has an urge to jump sixteen pixels down. + +I have to admit, even I don't ever use fluidizer myself, but it was an interesting experiment. + +This was developed some ancient time ago, well, fluidizer-beta was last modified 16 Feb 2010 at 06:45:59 PM EST. fluidizer-simple at 16 Feb 2010 06:44:53 PM EST. fluidizer-complex at Tue 16 Feb 2010 06:45:51 PM EST. fluidizer at Tue 16 Feb 2010 06:08:46 PM EST. fixedwidth at Mon 15 Feb 2010 07:54:53 PM EST. + +I don't remember which one was the latest one and I won't bother reading the dates from the paragraph above which I just pasted in from the nautilus properties dialog. Anyway, there was one in my bookmars bar which was named "Fluid3" and there weren't any other ones so I assume that means that was the good one, but I don't know which file that corresponds to, so I just copied it over to a new bookmarklet.js + +Have fun. + diff --git a/bookmarklet.js b/bookmarklet.js new file mode 100644 index 0000000..937a94c --- /dev/null +++ b/bookmarklet.js @@ -0,0 +1 @@ +javascript:(function(){function k(a){return(a||"").replace(/^\s+|\s+$/g,"")}function u(a,g){var b=new XMLHttpRequest;b.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(a),true);b.onreadystatechange=function(){b.readyState==4&&b.status==200&&g(b.responseText)};b.send()}function o(){for(var a=0,g=0,b=false,h="*,div,p,body,span".split(",");!b&&g++<20;){if(document.body.scrollWidth>window.innerWidth){b=true;a-=100}else a+=100;for(var c=d.length;c--;){var f=d[c].text;try{for(var i=document.querySelectorAll(f),l=i.length;l--;){var n=i[l],p=parseFloat(d[c].width,10),q=d[c].width.replace(/^[\-\d\.]+/,"");if(q!="px")if(q=="em")p*=16;else console.warn("not used to handling non-px units");if(p>400&&h.indexOf(f)==-1){if(!n.a)n.a=p;n.style.width=n.a+a+"px"}}}catch(x){}}}try{c=d.length;a=0;for(var r;c--;)if(h.indexOf(d[c].text)==-1)try{var j=document.querySelectorAll(d[c].text);if(j.length==1&&j[0].getElementsByTagName("*").length>15&&(j[0]==document.body||j[0].parentNode==document.body||j[0].parentNode.parentNode==document.body))if(parseInt(d[c].width,10)>a){a=parseInt(d[c].width,10);r=j[0]}}catch(y){}if(a>500)r.style.width="100%"}catch(z){}}function v(a){function g(){var i=h.split(";").map(function(l){if(k(l.split(":")[0])=="width")return k(l.split(":")[1]);return""}).join("");b&&k(b)&&i&&k(i)&&d.push({text:k(b),width:i});h=b=""}for(var b="",h="",c=0,f=0;f<a.length;f++)if(a[f]=="{")c=1;else if(a[f]=="}"){g();c=0}else if(c==0)b+=a[f];else if(c==1)h+=a[f];g();o()}for(var d=[],s=document.styleSheets,t=s.length;t--;){var e=s[t];if(e.href&&!e.cssRules){console.log(e.href);u(e.href,v)}else{e=e.cssRules;for(var m=e.length;m--;){var w=e[m].selectorText;e[m].style&&e[m].style.width&&d.push({text:w,width:e[m].style.width})}}}window.addEventListener("resize",function(){setTimeout(function(){o()},100)});o()})();
antimatter15/fluidizer
778a99c7d5455b1e30a5316a60921ea8908e817a
so this is the initial commit
diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/fixedwidth.js b/fixedwidth.js new file mode 100644 index 0000000..16edf11 --- /dev/null +++ b/fixedwidth.js @@ -0,0 +1,558 @@ +var sheet, rule, width, elements, element; +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx] + if(sheet.cssRules){ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + rule = rules[rulex]; + if(rule && rule.style && (width = rule.style.width)){ + + var elarr = [] + if((elements = document.querySelectorAll(rule.selectorText)).length > 0){ + for(var elementx = elements.length; elementx --; ){ + if(element = elements[elementx]){ + elarr.push(element) + } + } + } + + var lastwidth = 0, widthmin = 0, widthmax = 0, widthsum = 0; + for(var elen = elarr.length; elen --;){ + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + + var widthnum = parseInt(width, 10) + var unit = width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + console.warn("not used to handling non-px units") + } + if(lastwidth && lastwidth != widthnum){ + console.warn("different value for same selector:",lastwidth,widthnum) + } + if(!lastwidth){ + widthmin = widthnum + } + widthmin = Math.min(widthmin, widthnum); + widthmax = Math.max(widthmax, widthnum); + widthsum += widthnum; + lastwidth = widthnum; + } + if(elarr.length){ + var widthavg = widthsum/elarr.length; + if(widthavg == widthmin == widthmax){ + }else{ + console.warn("averages different from min and max") + } + console.log("average width",widthavg) + console.log("widthmin",widthmin) + console.log("widthmax",widthmax); + var delta = 200//window.innerWidth - widthmax; + for(var elen = elarr.length; elen --;){ + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + if(parseInt(width, 10) > 480){ //TODO: a purtierful solution + elarr[elen].style.width = (parseInt(width, 10) + delta) + "px" + } + } + } + + } + } + } +} + +var delta = 200, selectors = []; + +while(delta > 0){ + if(document.body.scrollWidth > window.innerWidth){ + delta = -200; + } + + var sheet, rule, width, elements, element; + for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx] + if(sheet.cssRules){ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + rule = rules[rulex]; + if(rule && rule.style && (width = rule.style.width)){ + + var elarr = [] + if((elements = document.querySelectorAll(rule.selectorText)).length > 0){ + for(var elementx = elements.length; elementx --; ){ + if(element = elements[elementx]){ + elarr.push(element) + } + } + } + if(elarr.length){ + for(var elen = elarr.length; elen --;){ + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + if(parseInt(width, 10) > 480){ //TODO: a purtierful solution + elarr[elen].style.width = (parseInt(width, 10) + delta) + "px" + selectors.push(rule.selectorText) + } + } + } + } + } + } + } +} + + + + + + + + + + + + + + +var delta = 200, selectors = []; + +while(delta > 0){ + if(document.body.scrollWidth > window.innerWidth){ + delta = -200; + } + + var elarr = [] + var sheet, rule, width, elements, element; + for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx] + if(sheet.cssRules){ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + rule = rules[rulex]; + if(rule && rule.style && (width = rule.style.width)){ + + if((elements = document.querySelectorAll(rule.selectorText)).length > 0){ + for(var elementx = elements.length; elementx --; ){ + if(element = elements[elementx]){ + elarr.push(element) + } + } + } + + } + } + } + } + if(elarr.length){ + for(var elen = elarr.length; elen --;){ + + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + if(parseInt(width, 10) > 480){ //TODO: a purtierful solution + elarr[elen].style.width = (parseInt(width, 10) + delta) + "px" + selectors.push(rule.selectorText) + } + } + } +} + + + + + + + + + + + + + +var delta = 200; + +while(delta > 0){ + if(document.body.scrollWidth > window.innerWidth){ + delta = -200; + } + + var sheet, rule, width, elements, element; + for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx] + if(sheet.cssRules){ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + rule = rules[rulex]; + if(rule && rule.style && (width = rule.style.width)){ + + var elarr = [] + if((elements = document.querySelectorAll(rule.selectorText)).length > 0){ + for(var elementx = elements.length; elementx --; ){ + if(element = elements[elementx]){ + elarr.push(element) + } + } + } + if(elarr.length){ + for(var elen = elarr.length; elen --;){ + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + if(parseInt(width, 10) > 480){ //TODO: a purtierful solution + elarr[elen].style.width = (parseInt(width, 10) + delta) + "px" + } + } + } + } + } + } + } +} + + + +var delta = 200; + + + +var sheet, rule, width, elements, element; +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx] + if(sheet.cssRules){ + for(var selectorx = sheet.cssRules.length; selectorx--;){ + var selector = sheet.cssRules[selectorx].selectorText; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + if(width > 480){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + console.log((element._originalWidth + delta) + "px") + } + } + } + } +} + + + + + + +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = [] +function download(){} //TODO: implement + +function update_selectors(){ + var delta = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + while(!end){ + if(document.body.scrollWidth > window.innerWidth){ + end = true; + delta -= 200; + console.log('sub') + }else{ + delta += 200; + console.log('add') + } + var usel = []; + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx]; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + //var width = parseInt(selectors[selectorx].width,10); + if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + usel.push(selector) + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + console.log((element._originalWidth + delta) + "px") + } + } + } + console.log(usel) + } +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, function(text){ + var selector = "", mode = 0; + for(var i = 0; i < text.length; i++){ + if(text[i] == "{") mode = 1; + else if(text[i] == "}"){ + if(selector && trim(selector)) selectors.push(trim(selector)); + mode = 0; + }else if(mode == 0) selector += text[i]; + } + if(selector && trim(selector) && selectors.indexOf(trim(selector)) == -1) + selectors.push(trim(selector)); + update_selectors(); + }) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width && selectors.indexOf(selector) == -1){ + selectors.push(selector); + } + } + } +} + +update_selectors(); + + + + + + + + + + + + + + + + + + + + + + + + + +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = [] +function download(){} //TODO: implement + +function update_selectors(){ + var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + while(!end && count++ < 20){ + if(document.body.scrollWidth > window.innerWidth){ + end = true; + delta -= 100; + //console.log('sub') + }else{ + delta += 100; + //console.log('add') + } + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx].text; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + var width = parseFloat(selectors[selectorx].width,10); + var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + if(unit == "em"){ + width = width * 16; + }else{ + console.warn("not used to handling non-px units") + } + } + if(width > 380 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + //console.log((element._originalWidth + delta) + "px") + } + } + } + } +} + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() + update_selectors() +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, load) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width){ + selectors.push({text: selector, width: rules[rulex].style.width}); + } + } + } +} + +update_selectors(); + + + + + + + + + + + + + + + + + + + + + + + + +var sheet, rule, width, elements, element, delta = 200; +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + sheet = sheets[sheetx]; + console.log("Sheet Raw",sheetx) + if(sheet.cssRules){ + console.log("Sheet",sheetx); + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + rule = rules[rulex]; + console.log("rule",rulex,rule) + if(rule && rule.style){ + + var elarr = [] + if((elements = document.querySelectorAll(rule.selectorText)).length > 0){ + //console.log(elements, rule.selectorText) + for(var elementx = elements.length; elementx --; ){ + if(element = elements[elementx]){ + elarr.push(element) + } + } + } + if(elarr.length){ + for(var elen = elarr.length; elen --;){ + var width = document.defaultView.getComputedStyle(elarr[elen],null).getPropertyValue("width"); //stolen from quirksmode + if(parseInt(width, 10) > 480){ //TODO: a purtierful solution + elarr[elen].style.width = (parseInt(width, 10) + delta) + "px" + console.log(width) + }else{ + console.log(width) + } + } + } + + } + } + } +} + + + + + + +function getStyle(element, property){ + var val = document.defaultView.getComputedStyle(element,null).getPropertyValue(property); + return [ + parseInt(val, 10), + val.replace(/^[\-\d\.]+/,'') //stolen from emile.js + ] +} + +var delta = 200; +//while(delta > 0){ + if(document.body.scrollWidth > window.innerWidth){ + delta = -200; + } + for(var elements = document.getElementsByTagName("*"), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + var width = getStyle(element,"width") + if(width[1] == "px"){ + if(width[0] > 480 && element.offsetHeight > 54) + { + element.style.width = (width[0] + delta) + "px"; + element.style.margin = 0; + console.log(width[0], (width[0] + delta) + "px") + } + }else{ + console.log("weird unit", width[1]) + } + } +//} + + + + + + + + + + + + + + + + + + + +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = []; + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() +} + + +load(" div {hello: poop;asdf: 324px;width: 42}\n eating marshmallows, .tasty:hover {nom: nomnom; margin: 42px solid potato}") + + + + + diff --git a/fluidizer-beta.js b/fluidizer-beta.js new file mode 100644 index 0000000..0f92ecb --- /dev/null +++ b/fluidizer-beta.js @@ -0,0 +1,130 @@ +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = [] +function download(url, callback){ + var xhr = new XMLHttpRequest(); + xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.onreadystatechange = function(){ + if(xhr.readyState == 4 && xhr.status == 200){ + callback(xhr.responseText); + } + } + xhr.send() +} //TODO: implement + +function update_selectors(){ + var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + + for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ + if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; + try{ + var els = document.querySelectorAll(selectors[selectorx].text); + if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 + && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) + ){ + if(parseInt(selectors[selectorx].width,10) > maxWidth){ + maxWidth = parseInt(selectors[selectorx].width,10); + maxEl = els[0]; + } + } + }catch(err){} + } + var lmh = 0, bsh = document.body.scrollHeight; + if(maxEl) lmh = maxEl.scrollHeight; + + while(!end && count++ < 20){ + + + if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ + end = true; + delta -= 100; + //console.log('sub') + }else{ + delta += 100; + //console.log('add') + } + if(maxEl){ + lmh = maxEl.scrollHeight; + } + bsh = document.body.scrollHeight; + + + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx].text; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + var width = parseFloat(selectors[selectorx].width,10); + var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + if(unit == "em"){ + width = width * 16; + }else{ + console.warn("not used to handling non-px units") + } + } + if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + //console.log(delta, element, (element._originalWidth + delta) + "px") + } + } + } + } + if(maxWidth > 500){ + maxEl.style.width = "100%"; + maxEl.style.padding = "10px" + } +} + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() + update_selectors() +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, load) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width){ + selectors.push({text: selector, width: rules[rulex].style.width}); + } + } + } +} + +update_selectors(); + + + + diff --git a/fluidizer-complex.js b/fluidizer-complex.js new file mode 100644 index 0000000..ff92a76 --- /dev/null +++ b/fluidizer-complex.js @@ -0,0 +1,142 @@ +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = [] +function download(url, callback){ + var xhr = new XMLHttpRequest(); + xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.onreadystatechange = function(){ + if(xhr.readyState == 4 && xhr.status == 200){ + callback(xhr.responseText); + } + } + xhr.send() +} //TODO: implement + +function update_selectors(){ + var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + + for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ + if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; + try{ + var els = document.querySelectorAll(selectors[selectorx].text); + if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 + && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) + ){ + if(parseInt(selectors[selectorx].width,10) > maxWidth){ + maxWidth = parseInt(selectors[selectorx].width,10); + maxEl = els[0]; + } + } + }catch(err){} + } + var lmh = 0, bsh = document.body.scrollHeight; + if(maxEl) lmh = maxEl.scrollHeight; + + while(!end && count++ < 20){ + var fixright = [] + for(var selectorx = selectors.length; selectorx--;){ + var els = document.querySelectorAll(selectors[selectorx].text) + for(var len = els.length; len--;){ + if(getComputedStyle(els[len], null).getPropertyValue("float") == "right"){ + els[len].style['float'] = "left"; + fixright.push(els[len]); + } + } + } + + if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ + end = true; + delta -= 100; + //console.log('sub') + }else{ + delta += 100; + //console.log('add') + } + if(maxEl){ + lmh = maxEl.scrollHeight; + } + bsh = document.body.scrollHeight; + + for(var i = 0; i < fixright.length; i++){ + fixright[i].style['float'] = ""; + } + + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx].text; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + var width = parseFloat(selectors[selectorx].width,10); + var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + if(unit == "em"){ + width = width * 16; + }else{ + console.warn("not used to handling non-px units") + } + } + if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + //console.log(delta, element, (element._originalWidth + delta) + "px") + } + } + } + } + if(maxWidth > 500){ + maxEl.style.width = "100%"; + maxEl.style.padding = "10px" + } +} + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() + update_selectors() +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, load) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width){ + selectors.push({text: selector, width: rules[rulex].style.width}); + } + } + } +} + +update_selectors(); + + + + diff --git a/fluidizer-simple.js b/fluidizer-simple.js new file mode 100644 index 0000000..73e1323 --- /dev/null +++ b/fluidizer-simple.js @@ -0,0 +1,130 @@ +(function(){ +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = []; + +function download(url, callback){ + var xhr = new XMLHttpRequest(); + xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.onreadystatechange = function(){ + if(xhr.readyState == 4 && xhr.status == 200){ + callback(xhr.responseText); + } + } + xhr.send() +} //TODO: implement + +function update_selectors(){ + var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + while(!end && count++ < 20){ + if(document.body.scrollWidth > window.innerWidth){ + end = true; + delta -= 100; + //console.log('sub') + }else{ + delta += 100; + //console.log('add') + } + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx].text; + try{ + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + + var element = elements[elementx]; + //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + var width = parseFloat(selectors[selectorx].width,10); + var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + if(unit == "em"){ + width = width * 16; + }else{ + console.warn("not used to handling non-px units") + } + } + if(width > 400 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + } + + } + }catch(err){} + } + } + try{ + for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ + if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; + try{ + var els = document.querySelectorAll(selectors[selectorx].text); + if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 + && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) + ){ + if(parseInt(selectors[selectorx].width,10) > maxWidth){ + maxWidth = parseInt(selectors[selectorx].width,10); + maxEl = els[0]; + } + } + }catch(err){} + } + if(maxWidth > 500){ + maxEl.style.width = "100%"; + } + }catch(err){} +} + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() + update_selectors() +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, load) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width){ + selectors.push({text: selector, width: rules[rulex].style.width}); + } + } + } +} + +window.addEventListener("resize", function(){ + setTimeout(function(){ + update_selectors(); + },100) +}) + +update_selectors(); + +})() + + diff --git a/fluidizer.js b/fluidizer.js new file mode 100644 index 0000000..ff92a76 --- /dev/null +++ b/fluidizer.js @@ -0,0 +1,142 @@ +function trim(str){return (str||"").replace(/^\s+|\s+$/g,'')} +var selectors = [] +function download(url, callback){ + var xhr = new XMLHttpRequest(); + xhr.open("GET","http://anti15.welfarehost.com/cssproxy.php?cssurl="+encodeURIComponent(url),true); + xhr.onreadystatechange = function(){ + if(xhr.readyState == 4 && xhr.status == 200){ + callback(xhr.responseText); + } + } + xhr.send() +} //TODO: implement + +function update_selectors(){ + var delta = 0, count = 0, end = false, blocked_selectors = "*,div,p,body,span".split(","); + + for(var selectorx = selectors.length, maxWidth = 0, maxEl; selectorx--;){ + if(blocked_selectors.indexOf(selectors[selectorx].text) != -1) continue; + try{ + var els = document.querySelectorAll(selectors[selectorx].text); + if(els.length == 1 && els[0].getElementsByTagName("*").length > 15 + && (els[0] == document.body || els[0].parentNode == document.body || els[0].parentNode.parentNode == document.body) + ){ + if(parseInt(selectors[selectorx].width,10) > maxWidth){ + maxWidth = parseInt(selectors[selectorx].width,10); + maxEl = els[0]; + } + } + }catch(err){} + } + var lmh = 0, bsh = document.body.scrollHeight; + if(maxEl) lmh = maxEl.scrollHeight; + + while(!end && count++ < 20){ + var fixright = [] + for(var selectorx = selectors.length; selectorx--;){ + var els = document.querySelectorAll(selectors[selectorx].text) + for(var len = els.length; len--;){ + if(getComputedStyle(els[len], null).getPropertyValue("float") == "right"){ + els[len].style['float'] = "left"; + fixright.push(els[len]); + } + } + } + + if(document.body.scrollWidth > window.innerWidth && (!maxEl || maxEl.scrollHeight <= (lmh+100)) && (document.body.scrollHeight <= (bsh + 100))){ + end = true; + delta -= 100; + //console.log('sub') + }else{ + delta += 100; + //console.log('add') + } + if(maxEl){ + lmh = maxEl.scrollHeight; + } + bsh = document.body.scrollHeight; + + for(var i = 0; i < fixright.length; i++){ + fixright[i].style['float'] = ""; + } + + for(var selectorx = selectors.length; selectorx--;){ + var selector = selectors[selectorx].text; + for(var elements = document.querySelectorAll(selector), elementx = elements.length; elementx--;){ + var element = elements[elementx]; + //var width = parseInt(document.defaultView.getComputedStyle(element,null).getPropertyValue("width"),10); + var width = parseFloat(selectors[selectorx].width,10); + var unit = selectors[selectorx].width.replace(/^[\-\d\.]+/,''); //stolen from emile.js + if(unit != "px"){ + if(unit == "em"){ + width = width * 16; + }else{ + console.warn("not used to handling non-px units") + } + } + if(width > 480 && blocked_selectors.indexOf(selector) == -1){ //TODO: a better solution. + if(!element._originalWidth) element._originalWidth = width; + element.style.width = (element._originalWidth + delta) + "px"; + //console.log(delta, element, (element._originalWidth + delta) + "px") + } + } + } + } + if(maxWidth > 500){ + maxEl.style.width = "100%"; + maxEl.style.padding = "10px" + } +} + +function load(text){ + var selector = "", body = "", mode = 0; + function add_selector(){ + var width = body.split(";").map(function(e){ + if(trim(e.split(":")[0]) == "width"){ + return trim(e.split(":")[1]); + } + return ""; + }).join("") + if(selector && trim(selector) && width && trim(width)){ + selectors.push({text: trim(selector), width: width}); + } + selector = ""; + body = "" + } + for(var i = 0; i < text.length; i++){ + if(text[i] == "{"){ + mode = 1; + }else if(text[i] == "}"){ + add_selector() + mode = 0; + }else if(mode == 0){ + selector += text[i]; + }else if(mode == 1){ + body += text[i]; + } + } + add_selector() + update_selectors() +} + + +for(var sheets = document.styleSheets, sheetx = sheets.length; sheetx --;){ + var sheet = sheets[sheetx]; + if(sheet.href && !sheet.cssRules){ + console.log(sheet.href) + download(sheet.href, load) + }else{ + for(var rules = sheet.cssRules, rulex = rules.length; rulex--;){ + var selector = rules[rulex].selectorText; + if(rules[rulex].style && rules[rulex].style.width){ + selectors.push({text: selector, width: rules[rulex].style.width}); + } + } + } +} + +update_selectors(); + + + +
astashov/solutions_grid
605af5e2fdfcc747b65d79ac364732a3847aa3d6
Removed old specs
diff --git a/spec/models/grid_spec.rb b/spec/models/grid_spec.rb index 0b521b9..ec8710e 100644 --- a/spec/models/grid_spec.rb +++ b/spec/models/grid_spec.rb @@ -1,340 +1,340 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Grid do before do @category = mock_model(CategoryExample, :name => "somecategory", :description => "category description") @feed = mock_model(FeedExample, :name => "somefeed", :category_example_id => @category.id, :category => @category, :restricted => false, :description => "Description") FeedExample.stub!(:find).and_return([@feed]) FeedExample.stub!(:table_name).and_return("feeds") CategoryExample.stub!(:find).and_return([@category]) CategoryExample.stub!(:table_name).and_return("categories") set_column_names_and_hashes(FeedExample, :string => %w{name category_example_id restricted description}) set_column_names_and_hashes(DateExample, :string => %w{description}, :date => %w{date}) set_column_names_and_hashes(SpanDateExample, :string => %w{description}, :datetime => %w{start_datetime end_datetime}) set_column_names_and_hashes(HABTMExample, :string => %w{description}) @columns = %w{name category_example_id restricted} end describe "common operations" do it "should copy option 'columns to show' to 'columns to sort' if 'columns to sort' is not specified" do grid = Grid.new(default_options.merge({ :columns => {:show => @columns.dup}})) grid.columns[:sort].all? { |c| @columns.include?(c) }.should be_true end it "should not copy option 'columns to show' to 'columns to sort' or 'columns to filter' if they are specified" do grid = Grid.new(default_options({ :columns => { :show => @columns.dup, :filter => { :by_string => @columns.dup.delete_if {|column| column == 'category_example_id'}}, :sort => @columns.dup.delete_if {|column| column == 'restricted'}, }})) grid.columns[:sort].all? { |c| %w{name category_example_id}.include?(c) }.should be_true grid.columns[:filter][:by_string].all? { |c| %w{name restricted}.include?(c) }.should be_true end end describe "errors handling" do it "should raise an error if model is not defined" do lambda { Grid.new() }.should raise_error(SolutionsGrid::ErrorsHandling::ModelIsNotDefined) end - it "should raise an error if we try to sort by column that not included to 'show'" do - lambda do - Grid.new(default_options.merge({ :columns => { :show => @columns, :sort => @columns + [ 'something' ]}})) - end.should raise_error(SolutionsGrid::ErrorsHandling::ColumnIsNotIncludedToShow) - end +# it "should raise an error if we try to sort by column that not included to 'show'" do +# lambda do +# Grid.new(default_options.merge({ :columns => { :show => @columns, :sort => @columns + [ 'something' ]}})) +# end.should raise_error(SolutionsGrid::ErrorsHandling::ColumnIsNotIncludedToShow) +# end it "should raise an error if we try show unexisted action" do lambda do Grid.new(default_options.merge(:actions => %w{unexisted})) end.should raise_error(SolutionsGrid::ErrorsHandling::UnexistedAction) end - it "should raise an error when we trying to sort by column that forbidden to sort" do - lambda do - Grid.new(default_options.merge(:columns => { :show => @columns, :sort => %w{category_example_id}}, :sorted => { :by_column => "name"})) - end.should raise_error(SolutionsGrid::ErrorsHandling::UnexistedColumn) - end +# it "should raise an error when we trying to sort by column that forbidden to sort" do +# lambda do +# Grid.new(default_options.merge(:columns => { :show => @columns, :sort => %w{category_example_id}}, :sorted => { :by_column => "name"})) +# end.should raise_error(SolutionsGrid::ErrorsHandling::UnexistedColumn) +# end # it "should raise an error when :filter_by_span_date contains not 2 dates" do # span_dates = create_ten_span_date_mocks # lambda do # grid = Grid.new(span_dates, { :columns => { :filter => { :by_span_date => [['start_datetime', 'end_datetime', 'start_datetime']]}}}.merge(default_options)) # end.should raise_error(SolutionsGrid::ErrorsHandling::IncorrectSpanDate) # end # it "should raise an error if Date To < Date From" do # grid = Grid.new(default_options.merge({ # :columns => { # :show => @columns, # :filter => { :by_date => %w{date} } # }, # :filtered => { :from_date => } # })) # lambda do # grid.filter_by_dates({'year' => default_date.year, 'month' => default_date.month, 'day' => default_date.day + 2}, # {'year' => default_date.year, 'month' => default_date.month, 'day' => default_date.day}) # end.should raise_error(SolutionsGrid::ErrorsHandling::IncorrectDate) # end it "should raise an error if user didn't give a name to the grid." do lambda { Grid.new(:model => FeedExample) }.should raise_error(SolutionsGrid::ErrorsHandling::NameIsntSpecified) end end describe "sorting" do it "should sort records by usual column (i.e, by feed name)" do sort("name", 'asc') do |grid| grid.order.should == "feeds.`name` ASC" end end it "should sort records by calculated column (i.e, by feed category)" do sort("category_example_id", 'asc') do |grid| grid.order.should == "categories.`name` ASC" grid.include.should include(:category_example) end end it "should sort records by calculated column with specified name (i.e, by feed's category description)" do sort("category_example_id_description", 'asc', { :columns => { :show => @columns + ['category_example_id_description']}}) do |grid| grid.order.should == "categories.`description` ASC" grid.include.should include(:category_example) end end it "should sort records by calculated column (i.e, by feed category)" do sort("category_example_id", 'asc') do |grid| grid.order.should == "categories.`name` ASC" grid.include.should include(:category_example) end end it "should sort by 'desc' if other is not specified" do sort("name") do |grid| grid.order.should == "feeds.`name` DESC" end end it "should sort records by reverse order" do sort("name", 'desc') do |grid| grid.order.should == "feeds.`name` DESC" end end end describe "filtering" do it "should filter by usual column" do usual_filter('junk') do |grid| grid.conditions.should == '((feeds.`name` LIKE :name OR categories.`name` LIKE :category_example_id OR categories.`description` LIKE :category_example_id_description))' grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description ].include?(k) }.should be_true grid.values[:name].should == '%junk%' grid.include.should == [ :category_example ] end end it "should filter by some usual columns" do grid = Grid.new(default_options( :columns => { :show => @columns + [ "category_example_id_description" ], :filter => { :by_string => %w{name category_example_id_description}, :by_category_example_id => %w{category_example_id} } }, :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict, :convert_id => false } } )) grid.conditions.split(" AND ").all? do |a| [ '((feeds.`name` LIKE :name OR categories.`description` LIKE :category_example_id_description)', '(feeds.`category_example_id` = :category_example_id))' ].should include(a) end grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description ].include?(k) }.should be_true grid.values[:name].should == '%junk%' grid.values[:category_example_id].should == '4' grid.include.should == [ :category_example ] end it "should filter by belonged column that contains _id" do grid = Grid.new(default_options( :columns => { :show => @columns + [ "category_example_id_description_id" ], :filter => { :by_string => %w{name}, :by_category_example_id => %w{category_example_id_description_id} } }, :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict } } )) grid.conditions.should == "((feeds.`name` LIKE :name) AND (categories.`description_id` = :category_example_id_description_id))" grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description_id ].include?(k) }.should be_true grid.values[:name].should == '%junk%' grid.values[:category_example_id_description_id].should == '4' grid.include.should == [ :category_example ] end it "should filter by table.column if dot is presented" do grid = Grid.new(default_options( :columns => { :show => @columns + [ "category_example_id" ], :filter => { :by_string => %w{name}, :by_category_example_id => %w{category_examples.description_id} } }, :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict } } )) grid.conditions.should == "((feeds.`name` LIKE :name) AND (`category_examples`.`description_id` = :description_id))" grid.values.keys.all? {|k| [ :name, :description_id ].include?(k) }.should be_true grid.values[:name].should == '%junk%' grid.values[:description_id].should == '4' grid.include.should == [ :category_example ] end it "should filter with user-defined conditions" do grid = Grid.new(default_options( :columns => { :show => @columns, :filter => { :by_string => %w{name category_example_id} } }, :filtered => { :by_string => { :text => 'smt', :type => :match } }, :conditions => "feeds_partners.partner_id = :partner_id", :values => { :partner_id => 1 }, :include => [ :partners ] )) grid.conditions.should == '((feeds.`name` LIKE :name OR categories.`name` LIKE :category_example_id)) AND (feeds_partners.partner_id = :partner_id)' grid.values.keys.all? {|k| [ :name, :category_example_id, :partner_id ].include?(k) }.should be_true grid.values[:partner_id].should == 1 grid.include.should == [ :category_example, :partners ] end it "should save all records when usual filter is empty" do usual_filter('') do |grid| grid.conditions.should == '' grid.values.should == {} grid.include.should == [:category_example] end end it "should filter records by date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{date description}, :filter => { :by_date => %w{date} }}, :filtered => { :from_date => { :year => "2006" }, :to_date => { :year => "2008", :month => "12" }} )) grid.conditions.should == '(date_examples.`date` >= :date_from_date AND date_examples.`date` <= :date_to_date)' grid.values.keys.all? {|k| [ :date_from_date, :date_to_date ].include?(k) }.should be_true grid.values[:date_from_date].should == DateTime.civil(2006, 1, 1) grid.include.should == [ ] end it "should filter records with overlapping span of date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :year => "2006", :day => "12" }, :to_date => { :year => "2008", :month => "12", :day => "15" }} )) grid.conditions.should == "(date_examples.`start_date` <= :start_date_to_date AND date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.all? {|k| [ :start_date_to_date, :end_date_from_date ].include?(k) }.should be_true grid.values[:end_date_from_date].should == DateTime.civil(2006, 1, 12) grid.include.should == [ ] end it "should filter records with overlapping span of date without start date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :day => "12" }, :to_date => { :year => "2008", :month => "12", :day => "15" }} )) grid.conditions.should == "(date_examples.`start_date` <= :start_date_to_date)" grid.values.keys.should == [ :start_date_to_date ] grid.values[:start_date_to_date].should == DateTime.civil(2008, 12, 15) grid.include.should == [ ] end it "should filter records with overlapping span of date without end date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :year => "2008", :day => "12" } } )) grid.conditions.should == "(date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.should == [ :end_date_from_date ] grid.values[:end_date_from_date].should == DateTime.civil(2008, 1, 12) grid.include.should == [ ] end it "should filter records with overlapping span of date with string" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_string => [ 'description' ], :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :by_string => {:text => "text", :type => :match }, :from_date => { :year => "2008", :day => "12" }, :to_date => { :year => "2008", :day => "16" } } )) grid.conditions.should == "((date_examples.`description` LIKE :description)) AND (date_examples.`start_date` <= :start_date_to_date AND date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.all? {|k| [:end_date_from_date, :description, :start_date_to_date].include?(k) }.should be_true grid.values[:end_date_from_date].should == DateTime.civil(2008, 1, 12) grid.include.should == [ ] end end def sort(by_column, order = nil, options = {}) raise "Block should be given" unless block_given? grid = Grid.new(default_options.merge(:sorted => { :by_column => by_column, :order => order}).merge(options)) yield(grid) end def usual_filter(by_string) raise "Block should be given" unless block_given? grid = Grid.new(default_options( :columns => { :show => @columns + [ "category_example_id_description" ], :filter => { :by_string => %w{name category_example_id category_example_id_description} } }, :filtered => { :by_string => { :text => by_string, :type => :match } } )) yield(grid) end def default_options(options = {}) { :name => 'feed', :model => FeedExample, :columns => { :show => @columns.dup, :sort => %w{name category_example_id}, :filter => {:by_string => %w{name category_example_id}} } }.merge(options) end def default_date Date.civil(2008, 10, 5) end def default_datetime DateTime.civil(2008, 10, 5, 15, 15, 0) end def filter_date_example_expectations date = mock_model(DateExample, :start_date => default_date, :end_date => default_date + 3.months, :description => "Desc") DateExample.should_receive(:find).and_return([date]) DateExample.stub!(:table_name).and_return("date_examples") end -end \ No newline at end of file +end
astashov/solutions_grid
91f0aa8ff5c133da048a66fd8763ab9ff6865d42
Added Sphinx support
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a30965e --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.swp +spec/debug.log diff --git a/lib/solutions_grid/controllers/grid_controller.rb b/lib/solutions_grid/controllers/grid_controller.rb index 9b53fc5..36b3dbc 100644 --- a/lib/solutions_grid/controllers/grid_controller.rb +++ b/lib/solutions_grid/controllers/grid_controller.rb @@ -1,85 +1,86 @@ class GridController < ApplicationController + unloadable def sort raise "You don't specify column to sort" unless params[:column] name = params[:grid_name].to_sym session[:sort] ||= {} controller = params[:controller].to_sym session[:sort][name] ||= {} # If we sorted records by this column before, then just change sort order if session[:sort][name][:by_column] && session[:sort][name][:by_column] == params[:column] previous_order = session[:sort][name][:order] session[:sort][name][:order] = (previous_order == 'asc') ? 'desc' : 'asc' else session[:sort][name][:order] = 'asc' session[:sort][name][:by_column] = params[:column] end flash[:notice] = "Data was sorted by #{CGI.escapeHTML(params[:column]).humanize}" respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end def filter name = params[:grid_name].to_sym session[:filter] ||= {} session[:filter][name] ||= {} session[:page].delete(name) if session[:page] if params[:commit] == 'Clear' session[:filter][name] = nil flash[:notice] = "Filter was cleared" else from_date = params.delete((name.to_s + '_from_date').to_sym) to_date = params.delete((name.to_s + '_to_date').to_sym) session[:filter][name][:from_date] = from_date session[:filter][name][:to_date] = to_date params.each do |key, value| name_match = key.match(/#{name.to_s}_(.*)_filter/) session[:filter][name][name_match[1].to_sym] = value || "" if name_match end flash[:notice] = "Data was filtered" end respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end private def error_handling(msg) msg = msg.to_s[0..1000] + "..." if msg.to_s.length > 1000 flash[:error] = CGI.escapeHTML(msg.to_s) request.env["HTTP_REFERER"] ||= root_url redirect_to :back end end diff --git a/lib/solutions_grid/errors_handling.rb b/lib/solutions_grid/errors_handling.rb index 07f2688..2125079 100644 --- a/lib/solutions_grid/errors_handling.rb +++ b/lib/solutions_grid/errors_handling.rb @@ -1,119 +1,119 @@ module SolutionsGrid::ErrorsHandling def check_for_errors verify_that_model_is_specified verify_that_name_is_specified verify_that_columns_for_show_are_defined - verify_that_sort_columns_are_included_to_show_columns + #verify_that_sort_columns_are_included_to_show_columns verify_that_there_are_no_unexisted_actions - verify_that_column_to_sort_is_included_to_sort_columns + #verify_that_column_to_sort_is_included_to_sort_columns # if @options[:filtered] && @options[:filtered][:from_date] && @options[:filtered][:to_date] # verify_that_date_from_less_than_date_to(@options[:filtered][:from_date], @options[:filtered][:to_date]) # end end private def verify_that_model_is_specified raise ModelIsNotDefined, "You should specify model" unless @options[:model] end def verify_that_name_is_specified raise NameIsntSpecified, "You should specify name of the grid" unless @options[:name] end def verify_that_columns_for_show_are_defined raise ColumnsForShowAreNotDefined, "You should define columns to show" unless @columns[:show] || !@columns[:show].empty? end def verify_that_sort_columns_are_included_to_show_columns check_column_including(@columns[:sort]) end def verify_that_there_are_no_unexisted_actions @options[:actions].each do |action| unless SolutionsGrid::Actions.instance_methods.include?("action_" + action) raise UnexistedAction, "You are trying to show unexisted action '#{h(action)}'" end end end def verify_that_date_from_less_than_date_to(from_date, to_date) if from_date && to_date && (from_date > to_date) raise IncorrectDate, "Date From must be less than Date To" end end def verify_that_column_to_sort_is_included_to_sort_columns if @options[:sorted] && !@options[:sorted][:by_column].blank? unless @columns[:sort].include?(@options[:sorted][:by_column]) raise UnexistedColumn, "You can't sort by column #{h(@options[:sorted][:by_column])}" end end end def verify_that_type_of_date_filtering_is_specified(option) unless option raise DateTypeIsNotSpecified, "You should specify date type, especially if you are using hashes (by :type_of_date_filtering option)" end end def verify_that_array_contains_date_from_and_date_to(from_and_to_date_columns) unless from_and_to_date_columns.size == 2 raise IncorrectSpanDate, "You should specify array of two elements as column - from_date and to_date" end end def check_column_including(given_columns) given_columns.each do |columns| columns = Array(columns) columns.each do |column| unless @columns[:show].include?(column) raise ColumnIsNotIncludedToShow, "Column #{h(column)} is not included to show columns" end end end end def h(msg) CGI.escapeHTML(msg.to_s) end # Exception will be raised when +@records+ has records of different classes class DifferentTypesOfRecords < StandardError; end; # Exception will be raised when filter or sort columns contain columns not included to show class ColumnIsNotIncludedToShow < StandardError; end; # Exception will be raised when there is no proper method of action in SolutionsGrid::GridHelper class UnexistedAction < StandardError; end; # Exception will be raised when some column doesn't exist. class UnexistedColumn < StandardError; end; # Exception will be raised when date type is not specified. class DateTypeIsNotSpecified < StandardError; end; # Exception will be raised when something wrong with date. class IncorrectDate < StandardError; end; # Exception will be raised when span of date doesn't consist of 2 array elements class IncorrectSpanDate < StandardError; end; # Exception will be raised when show_columns are not defined. class ColumnsForShowAreNotDefined < StandardError; end; # Exception will be raised when model or show_columns are not defined. class ModelIsNotDefined < StandardError; end; # Exception will be raised when 'will_paginate' plugin is not installed, but user try to paginate records. class WillPaginateIsNotInstalled < StandardError; end; # Exception will be raised when user didn't give a name to the grid. class NameIsntSpecified < StandardError; end; end \ No newline at end of file diff --git a/lib/solutions_grid/grid.rb b/lib/solutions_grid/grid.rb index c631261..164d827 100644 --- a/lib/solutions_grid/grid.rb +++ b/lib/solutions_grid/grid.rb @@ -1,404 +1,450 @@ # Main class of the SolutionGrid plugin. It stores array of records (ActiveRecord # objects or simple hashes). It can construct SQL query with different operations with # these records, such as sorting and filtering. With help of GridHelper it can # show these records as table with sortable headers, show filters. class Grid include SolutionsGrid::ErrorsHandling attr_accessor :view attr_reader :records, :options, :columns, :conditions, :values, :include, :order # Grid initialization. It constructs SQL query (with sorting and filtering # conditions, optionally), then fill @records by result of query. This # array of records you can use in helper, show_grid(). # # == Options # # === Required # # 1. <tt>[:name]</tt> # Set name of the grid. This parameter will be used for storing sorted and # filtered info of this grid. # 2. <tt>[:model]</tt> # Set model. It will be used for constructing SQL query. # 3. <tt>[:columns][:show]</tt> # Columns that you need to show, pass as array, e.g. %w{ name body } # # === Optional # # 1. <tt>[:columns][:sort]</tt> # Pass columns you need to allow sorting. Default is columns to show. # 2. <tt>[:columns][:filter][something]</tt> # Pass columns you need to allow filtering by string. # 3. <tt>[:columns][:filter][:by_date]</tt> # Pass columns you need to allow filtering by date. # 4. <tt>[:columns][:filter][:by_span_date]</tt> # Pass columns you need to allow filtering by span of date. You should pass # columns as array of arrays (format of arrays - [ start_date_column, # end_date_column ]), e.g. [ [start_date_column, end_date_column] ]. # 5. <tt>[:actions]</tt> # Pass necessary actions (such as 'edit', 'destroy', 'duplicate'). # Details about actions see below. # 6. <tt>[:sorted]</tt> # Pass column to SQL query that will be sorted and order of sorting. Example: # [:sorted] = { :by_column => "name", :order => "asc" } # 6. <tt>[:filtered]</tt> # Pass hash with parameters: # * <tt>[:filtered][:from_date] and [:filtered][:end_date]</tt> # [:columns][:filter][:by_date] should have date that is in range # of these dates (otherwise, it will not be in @records array). # [:columns][:filter][:by_span_date] should have date range that intersects # with range of these dates. # * <tt>[:filtered][something]</tt> # It should contain hash with parameters: # * <tt>[:text]</tt> - text you want to search # * <tt>[:strict] -> :strict or :match. If you specify :strict, it will # construct SQL WHERE query like 'something = 'value', if you specify # :match, it will construct like 'something LIKE '%value%' # * <tt>[:convert_id] -> if set to false, it will not convert columns # like 'content_item_id_body' to SQL WHERE queries like # 'content_items.body = 'value'. Default is true. # Example: # :model => Post # :columns => { :filter => { :by_text => %w{name body}, :by_article => %w{article_id} } # :filtered => { :by_text => { :text => "smthg", :type => :match }, # { :by_article => { :text => "artcl", :type => :strict } # will create SQL query like # '((`posts`.`name` LIKE '%smthg%' OR `posts`.`body` LIKE '%smthg%') AND (`articles`.`name` = 'artcl') # - # 7. <tt>[:conditions]</tt>, <tt>[:values]</tt>, <tt>[:include]</tt>, <tt>[:joins]</tt> + # 7. <tt>[:conditions]</tt>, <tt>[:values]</tt>, <tt>[:include]</tt>, <tt>[:joins]</tt>, <tt>[:select] # You can pass additional conditions to grid's SQL query. E.g., # [:conditions] = "user_id = :user_id" # [:values] = { :user_id => "1" } # [:include] = [ :user ] - # will select and add to @records only records of user with id = 1. + # [:select] = "id" + # will select and add to @records only ids of records of user with id = 1. # 8. <tt>[:paginate]</tt> # If you pass [:paginate] parameter, #paginate method will be used instead of # #find (i.e., you need will_paginate plugin). [:paginate] is a hash: # [:paginate][:page] - page you want to see # [:paginate][:per_page] - number of records per page # 9. <tt>[:template]</tt> # What template use for displaying the grid. Default is 'grid/grid' # # # == Default values of the options # # * <tt>[:columns][:show]</tt> - all columns of the table, except 'id', 'updated_at', 'created_at'. # * <tt>[:columns][:sort]</tt> - default is equal [:columns][:show] # * <tt>[:columns][:filter][:by_string]</tt> - default is empty array # * <tt>[:columns][:filter][:by_date]</tt> - default is empty array # * <tt>[:columns][:filter][:by_span_date]</tt> - default is empty array # * <tt>[:actions]</tt> - default is empty array # * <tt>[:filtered]</tt> - default is empty hash # * <tt>[:sorted]</tt> - default is empty hash # # # == User-defined display of actions and values # # You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean # column is true, and 'No' if it is false). For that, you should add method with name # gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in # app/helper and create file with filename gridname.rb. Let's implement example above: # # We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb # # module SolutionsGrid::Feeds # def feeds_restricted(record = nil) # value = record ? record.restricted : nil # { :key => "Restricted", :value => value ? "Yes" : "No" } # end # end # # Function should take one parameter (default is nil) and return hash with keys # <tt>:key</tt> - value will be used for the headers of the table # <tt>:value</tt> - value will be user for cells of the table # # If such method will not be founded, there are two ways to display values. # # * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. # * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. # * If column doesn't look like 'something_id' the plugin just display value of this column. # # You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. # Example for 'edit' action, file 'app/helpers/attributes/actions.rb': # # module SolutionsGrid::Actions # def action_edit(record = nil) # if record # url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') # value = link_to("Edit", url) # else # value = nil # end # { :key => "Edit", :value => value } # end # end # # # == Sort and filter # # To sort and filter records of the grid you *must* pass options <tt>:filtered</tt> or <tt>:sorted</tt>. # # == Examples of using the SolutionGrid # # <i>in controller:</i> # # def index # @table = Grid.new(:name => "feeds", :model => Feed, :columns => { :show => %{name body}}) # end # # <i>in view:</i> # # show_grid(@table) # # It will display feeds with 'name' and 'body'. There will be no actions and # filterable columns, all columns will be sortable, but because you don't pass # <tt>:sorted</tt> option, sort will not work. # # # <i>in controller:</i> # def index # @table = Grid.new( # :columns => { # :show => %w{name description}, # :sort => %w{name} # }, # :sorted => session[:sort] ? session[:sort][:feeds] : nil, # :name => "feeds", # :model => Feed # ) # end # # <i>in view:</i> # show_grid(@table) # # It will display feeds with columns 'name' and 'description'. There will be no actions and # filterable columns, 'name' column will be sortable, sort info is stored in # session[:sort][:feeds][:by_column] (session[:sort][:feeds] hash can be automatically # generated by grid_contoller of SolutionsGrid. Just add :sorted => session[:sort][:feeds], # and all other work will be done by the SolutionsGrid plugin) # # # <i>in controller:</i> # def index # @table = Grid.new( # :columns => { # :show => %w{name description}, # :filter => { # :by_string => %w{name} # }, # }, # :name => "feeds", # :model => Feed # :sorted => session[:sort][:feeds], # :filtered => session[:filter][:feeds], # :actions => %w{edit delete} # ) # end # # <i>in view:</i> # show_grid(@table, [ :text ]) # # It will display feeds with columns 'name' and 'description'. These columns will be sortable. # There will be actions 'edit' and 'delete' (but remember, you need action methods # 'action_edit' and 'action_delete' in SolutionGrid::Actions in 'app/helpers/attributes/actions.rb'). # There will be filterable column 'name', and it will be filtered by session[:filter][:feed][:by_string] value. # (that will be automatically generated by SolutionsGrid's grid_controller def initialize(options = {}) @options = {} @options[:name] = options[:name].to_s if options[:name] @options[:model] = options[:model] @options[:modelname] = @options[:model].to_s.underscore @options[:actions] = Array(options[:actions]) || [] @options[:conditions] = options[:conditions] @options[:values] = options[:values] || {} @options[:include] = Array(options[:include]) || [] @options[:joins] = options[:joins] + @options[:select] = options[:select] @options[:paginate] = options[:paginate] @options[:template] = options[:template] || 'grid/grid' options[:columns] ||= {} @columns = {} @columns[:show] = Array(options[:columns][:show] || []) @columns[:sort] = options[:columns][:sort] || @columns[:show].dup @columns[:filter] = options[:columns][:filter] @options[:sorted] = options[:sorted] @options[:filtered] = options[:filtered] + @options[:sphinx] = options[:sphinx] check_for_errors @records = get_records @view = {} end def get_belonged_model_and_column(column) column_with_table = column.match(/(.*)\.(.*)/) if column_with_table table = column_with_table[1] column = column_with_table[2] return [ table, column ] else position_match = column.index('_id') if position_match model = column[0..position_match - 1] model_column = column[(position_match + 4)..-1] if !model.blank? && !model_column.blank? return [ model.camelize.constantize, model_column ] elsif !model.blank? && model_column.blank? return [ model.camelize.constantize, 'name' ] end else return [ nil, nil ] end end end def get_association(belonged_model) belonged_model.to_s.underscore.to_sym end def get_date(params) return nil if !params || params[:year].blank? params[:month] = params[:month].blank? ? 1 : params[:month] params[:day] = params[:day].blank? ? 1 : params[:day] conditions = [ params[:year].to_i, params[:month].to_i, params[:day].to_i ] conditions += [ params[:hour].to_i, params[:minute].to_i ] if params[:hour] DateTime.civil(*conditions) end private def get_records + @options[:sphinx] ? get_sphinx_records : get_usual_records + end + + def get_usual_records @include ||= [] method = @options[:paginate] ? :paginate : :find conditions = {} conditions.merge!(filter(@options[:filtered])) conditions.merge!(sort(@options[:sorted])) include_belonged_models_from_show_columns @include += @options[:include] conditions[:include] = @include conditions[:joins] = @options[:joins] if @options[:joins] + conditions[:select] = @options[:select] if @options[:select] if @options[:paginate] method = :paginate conditions.merge!(@options[:paginate]) else method = :find end @options[:model].send(method, :all, conditions) end + def get_sphinx_records + options = {} + value = '' + @options[:filtered].each do |key, filter| + if !filter[:from].blank? || !filter[:to].blank? + options[:with] ||= {} + unless filter[:from]['year'].blank? + from_year = "%04d" % filter[:from]['year'].to_i + from_month = "%02d" % filter[:from]['month'].to_i + from_day = "%02d" % filter[:from]['day'].to_i + from_date = (from_year + from_month + from_day).to_i + end + unless filter[:to]['year'].blank? + to_year = "%04d" % filter[:to]['year'].to_i + to_month = "%02d" % filter[:to]['month'].to_i + to_day = "%02d" % filter[:to]['day'].to_i + to_date = (to_year + to_month + to_day).to_i + end + options[:with][key] = (from_date || 0)..(to_date || 100000000) + elsif filter[:type] == :strict && !filter[:text].blank? + options[:with] ||= {} + options[:with][key] = filter[:text] + elsif filter[:type] == :match && !filter[:text].blank? + options[:conditions] ||= {} + options[:conditions][key] = filter[:text] + end + end + options.merge!(@options[:paginate]) + if @options[:sorted] + options.merge!( + :order => @options[:sorted][:by_column].to_sym, + :sort_mode => (@options[:sorted][:order] == 'asc' ? :asc : :desc) + ) + end + @options[:model].search(value, options) + end + + def sort(options) return {} unless options order = (options[:order] == 'asc') ? "ASC" : "DESC" table_with_column = get_correct_table_with_column(options[:by_column]) @order = "#{table_with_column} #{order}" { :order => @order } end def filter(options) @conditions ||= [] @values ||= {} if options filter_by_strings filter_by_date end @conditions << "(" + @options[:conditions] + ")" if @options[:conditions] @values.merge!(@options[:values]) @conditions = @conditions.join(" AND ") { :conditions => [ @conditions, @values ] } end def filter_by_strings filters = @options[:filtered].dup filter_conditions = [] filters.each do |name, filter| string = filter ? filter[:text] : nil next if string.blank? conditions = [] Array(@columns[:filter][name]).each do |column| convert_to_belonged_model = filter.has_key?(:convert_id) ? filter[:convert_id] : true table_with_column = get_correct_table_with_column(column, convert_to_belonged_model) column = column.match(/\.(.*)/)[1] if column.match(/\.(.*)/) if filter[:type] == :strict conditions << "#{table_with_column} = :#{column}" @values[column.to_sym] = string else conditions << "#{table_with_column} LIKE :#{column}" @values[column.to_sym] = "%#{string}%" end end filter_conditions << "(" + conditions.join(" OR ") + ")" end @conditions << "(" + filter_conditions.join(" AND ") + ")" unless filter_conditions.empty? end def filter_by_date from_date = @options[:filtered][:from_date] from_date = get_date(from_date) to_date = @options[:filtered][:to_date] to_date = get_date(to_date) return unless from_date || to_date date_conditions = [] Array(@columns[:filter][:by_date]).each do |column| conditions = [] table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} >= :#{column}_from_date" if from_date conditions << "#{table_with_column} <= :#{column}_to_date" if to_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{column}_from_date".to_sym] = from_date if from_date @values["#{column}_to_date".to_sym] = to_date if to_date end Array(@columns[:filter][:by_span_date]).each do |columns| conditions = [] table_with_column_from = get_correct_table_with_column(columns[0]) table_with_column_to = get_correct_table_with_column(columns[1]) conditions << "#{table_with_column_from} <= :#{columns[0]}_to_date" if to_date conditions << "#{table_with_column_to} >= :#{columns[1]}_from_date" if from_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{columns[0]}_to_date".to_sym] = to_date if to_date @values["#{columns[1]}_from_date".to_sym] = from_date if from_date end @conditions << date_conditions.join(" OR ") end def get_correct_table_with_column(column, convert_to_belonged_model = true) belonged_model, belonged_column = get_belonged_model_and_column(column) if belonged_model && convert_to_belonged_model by_column = ActiveRecord::Base.connection.quote_column_name(belonged_column) unless belonged_model.is_a?(String) association = get_association(belonged_model) @include << association unless @include.include?(association) return "#{belonged_model.table_name}.#{by_column}" else by_model = ActiveRecord::Base.connection.quote_column_name(belonged_model) return "#{by_model}.#{by_column}" end else by_column = ActiveRecord::Base.connection.quote_column_name(column) return "#{@options[:model].table_name}.#{by_column}" end end def include_belonged_models_from_show_columns Array(@columns[:show]).each do |column| get_correct_table_with_column(column) end end end diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index da29c5b..783912f 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,133 +1,129 @@ module SolutionsGrid module GridHelper # This helper shows generated grid. It takes two arguments: # * grid - grid's object that you created in controller # * filter - array with filters (need for showing filter forms). It can contain: # * :text - show form with filter by string # * :date - show form with filter by date # You should have partial 'grid/grid' in your app/views directory with # template of the grid. You can get example of this grid in # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) render :partial => grid.options[:template], :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] - grid.columns[:show].each do |column| + grid.columns[:sort].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end - show_value = if grid.columns[:sort].include?(column) - link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") - else - h(show_value) - end + show_value = link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? h(associated_record.send(belonged_column)) : "" else h(record.send(column)) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" additional_params[:params] = { :grid => grid.options[:name] } grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end end end
astashov/solutions_grid
0919952af7376139618c43500ca46b39b7d2ae88
Fixed initialization for Rails > 2.1
diff --git a/init.rb b/init.rb index d1bf4b3..c58af76 100644 --- a/init.rb +++ b/init.rb @@ -1,7 +1,7 @@ # Enable our grid_controller controller_path = RAILS_ROOT + '/vendor/plugins/solutions_grid/lib/solutions_grid/controllers' $LOAD_PATH << controller_path -Dependencies.load_paths << controller_path +ActiveSupport::Dependencies.load_paths << controller_path config.controller_paths << controller_path -SolutionsGrid.enable \ No newline at end of file +SolutionsGrid.enable
astashov/solutions_grid
237f0b417214046835bbd663532b7543a5daa9fa
Added support of many filters (they will be combined by 'AND'). Added support of strict ( = 'value') or match ( LIKE '%value%') filtering. Added possibility to set table and column to filter by table_name.column (with dot), it will avoid to add table_name to :includes, you should add this table manually. Added possibility to disable converting something_id column to . conditions
diff --git a/lib/solutions_grid/controllers/grid_controller.rb b/lib/solutions_grid/controllers/grid_controller.rb index 3077fa2..9b53fc5 100644 --- a/lib/solutions_grid/controllers/grid_controller.rb +++ b/lib/solutions_grid/controllers/grid_controller.rb @@ -1,83 +1,85 @@ class GridController < ApplicationController def sort raise "You don't specify column to sort" unless params[:column] name = params[:grid_name].to_sym session[:sort] ||= {} controller = params[:controller].to_sym session[:sort][name] ||= {} # If we sorted records by this column before, then just change sort order if session[:sort][name][:by_column] && session[:sort][name][:by_column] == params[:column] previous_order = session[:sort][name][:order] session[:sort][name][:order] = (previous_order == 'asc') ? 'desc' : 'asc' else session[:sort][name][:order] = 'asc' session[:sort][name][:by_column] = params[:column] end flash[:notice] = "Data was sorted by #{CGI.escapeHTML(params[:column]).humanize}" respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end def filter name = params[:grid_name].to_sym session[:filter] ||= {} session[:filter][name] ||= {} session[:page].delete(name) if session[:page] if params[:commit] == 'Clear' session[:filter][name] = nil flash[:notice] = "Filter was cleared" else - from_date = params[(name.to_s + '_from_date').to_sym] - to_date = params[(name.to_s + '_to_date').to_sym] - by_string = params[(name.to_s + '_string_filter').to_sym] || "" + from_date = params.delete((name.to_s + '_from_date').to_sym) + to_date = params.delete((name.to_s + '_to_date').to_sym) session[:filter][name][:from_date] = from_date session[:filter][name][:to_date] = to_date - session[:filter][name][:by_string] = by_string - flash[:notice] = "Data was filtered by #{CGI.escapeHTML(by_string).humanize}" + params.each do |key, value| + name_match = key.match(/#{name.to_s}_(.*)_filter/) + session[:filter][name][name_match[1].to_sym] = value || "" if name_match + end + flash[:notice] = "Data was filtered" end respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end private def error_handling(msg) msg = msg.to_s[0..1000] + "..." if msg.to_s.length > 1000 flash[:error] = CGI.escapeHTML(msg.to_s) request.env["HTTP_REFERER"] ||= root_url redirect_to :back end end diff --git a/lib/solutions_grid/errors_handling.rb b/lib/solutions_grid/errors_handling.rb index 7a0f877..07f2688 100644 --- a/lib/solutions_grid/errors_handling.rb +++ b/lib/solutions_grid/errors_handling.rb @@ -1,124 +1,119 @@ module SolutionsGrid::ErrorsHandling def check_for_errors verify_that_model_is_specified verify_that_name_is_specified verify_that_columns_for_show_are_defined - verify_that_sort_and_filter_columns_are_included_to_show_columns + verify_that_sort_columns_are_included_to_show_columns verify_that_there_are_no_unexisted_actions verify_that_column_to_sort_is_included_to_sort_columns # if @options[:filtered] && @options[:filtered][:from_date] && @options[:filtered][:to_date] # verify_that_date_from_less_than_date_to(@options[:filtered][:from_date], @options[:filtered][:to_date]) # end end private def verify_that_model_is_specified raise ModelIsNotDefined, "You should specify model" unless @options[:model] end def verify_that_name_is_specified raise NameIsntSpecified, "You should specify name of the grid" unless @options[:name] end def verify_that_columns_for_show_are_defined raise ColumnsForShowAreNotDefined, "You should define columns to show" unless @columns[:show] || !@columns[:show].empty? end - def verify_that_sort_and_filter_columns_are_included_to_show_columns + def verify_that_sort_columns_are_included_to_show_columns check_column_including(@columns[:sort]) - if @columns[:filter] - @columns[:filter].each do |key, columns| - check_column_including(columns) - end - end end def verify_that_there_are_no_unexisted_actions @options[:actions].each do |action| unless SolutionsGrid::Actions.instance_methods.include?("action_" + action) raise UnexistedAction, "You are trying to show unexisted action '#{h(action)}'" end end end def verify_that_date_from_less_than_date_to(from_date, to_date) if from_date && to_date && (from_date > to_date) raise IncorrectDate, "Date From must be less than Date To" end end def verify_that_column_to_sort_is_included_to_sort_columns if @options[:sorted] && !@options[:sorted][:by_column].blank? unless @columns[:sort].include?(@options[:sorted][:by_column]) raise UnexistedColumn, "You can't sort by column #{h(@options[:sorted][:by_column])}" end end end def verify_that_type_of_date_filtering_is_specified(option) unless option raise DateTypeIsNotSpecified, "You should specify date type, especially if you are using hashes (by :type_of_date_filtering option)" end end def verify_that_array_contains_date_from_and_date_to(from_and_to_date_columns) unless from_and_to_date_columns.size == 2 raise IncorrectSpanDate, "You should specify array of two elements as column - from_date and to_date" end end def check_column_including(given_columns) given_columns.each do |columns| columns = Array(columns) columns.each do |column| unless @columns[:show].include?(column) raise ColumnIsNotIncludedToShow, "Column #{h(column)} is not included to show columns" end end end end def h(msg) CGI.escapeHTML(msg.to_s) end # Exception will be raised when +@records+ has records of different classes class DifferentTypesOfRecords < StandardError; end; # Exception will be raised when filter or sort columns contain columns not included to show class ColumnIsNotIncludedToShow < StandardError; end; # Exception will be raised when there is no proper method of action in SolutionsGrid::GridHelper class UnexistedAction < StandardError; end; # Exception will be raised when some column doesn't exist. class UnexistedColumn < StandardError; end; # Exception will be raised when date type is not specified. class DateTypeIsNotSpecified < StandardError; end; # Exception will be raised when something wrong with date. class IncorrectDate < StandardError; end; # Exception will be raised when span of date doesn't consist of 2 array elements class IncorrectSpanDate < StandardError; end; # Exception will be raised when show_columns are not defined. class ColumnsForShowAreNotDefined < StandardError; end; # Exception will be raised when model or show_columns are not defined. class ModelIsNotDefined < StandardError; end; # Exception will be raised when 'will_paginate' plugin is not installed, but user try to paginate records. class WillPaginateIsNotInstalled < StandardError; end; # Exception will be raised when user didn't give a name to the grid. class NameIsntSpecified < StandardError; end; end \ No newline at end of file diff --git a/lib/solutions_grid/grid.rb b/lib/solutions_grid/grid.rb index 40ccfbe..c631261 100644 --- a/lib/solutions_grid/grid.rb +++ b/lib/solutions_grid/grid.rb @@ -1,359 +1,404 @@ # Main class of the SolutionGrid plugin. It stores array of records (ActiveRecord # objects or simple hashes). It can construct SQL query with different operations with # these records, such as sorting and filtering. With help of GridHelper it can # show these records as table with sortable headers, show filters. class Grid include SolutionsGrid::ErrorsHandling attr_accessor :view attr_reader :records, :options, :columns, :conditions, :values, :include, :order # Grid initialization. It constructs SQL query (with sorting and filtering # conditions, optionally), then fill @records by result of query. This # array of records you can use in helper, show_grid(). # # == Options # # === Required # # 1. <tt>[:name]</tt> # Set name of the grid. This parameter will be used for storing sorted and # filtered info of this grid. # 2. <tt>[:model]</tt> # Set model. It will be used for constructing SQL query. # 3. <tt>[:columns][:show]</tt> # Columns that you need to show, pass as array, e.g. %w{ name body } # # === Optional # # 1. <tt>[:columns][:sort]</tt> # Pass columns you need to allow sorting. Default is columns to show. - # 2. <tt>[:columns][:filter][:by_string]</tt> + # 2. <tt>[:columns][:filter][something]</tt> # Pass columns you need to allow filtering by string. # 3. <tt>[:columns][:filter][:by_date]</tt> # Pass columns you need to allow filtering by date. # 4. <tt>[:columns][:filter][:by_span_date]</tt> # Pass columns you need to allow filtering by span of date. You should pass # columns as array of arrays (format of arrays - [ start_date_column, # end_date_column ]), e.g. [ [start_date_column, end_date_column] ]. # 5. <tt>[:actions]</tt> # Pass necessary actions (such as 'edit', 'destroy', 'duplicate'). # Details about actions see below. # 6. <tt>[:sorted]</tt> # Pass column to SQL query that will be sorted and order of sorting. Example: # [:sorted] = { :by_column => "name", :order => "asc" } # 6. <tt>[:filtered]</tt> # Pass hash with parameters: - # * <tt>[:filtered][:by_string]</tt> - # If you pass string, all 'filtered by string' columns will be filtered by this string - # * <tt>[:filtered][:from_date]</tt> and [:filtered][:end_date] + # * <tt>[:filtered][:from_date] and [:filtered][:end_date]</tt> # [:columns][:filter][:by_date] should have date that is in range # of these dates (otherwise, it will not be in @records array). # [:columns][:filter][:by_span_date] should have date range that intersects # with range of these dates. + # * <tt>[:filtered][something]</tt> + # It should contain hash with parameters: + # * <tt>[:text]</tt> - text you want to search + # * <tt>[:strict] -> :strict or :match. If you specify :strict, it will + # construct SQL WHERE query like 'something = 'value', if you specify + # :match, it will construct like 'something LIKE '%value%' + # * <tt>[:convert_id] -> if set to false, it will not convert columns + # like 'content_item_id_body' to SQL WHERE queries like + # 'content_items.body = 'value'. Default is true. + # Example: + # :model => Post + # :columns => { :filter => { :by_text => %w{name body}, :by_article => %w{article_id} } + # :filtered => { :by_text => { :text => "smthg", :type => :match }, + # { :by_article => { :text => "artcl", :type => :strict } + # will create SQL query like + # '((`posts`.`name` LIKE '%smthg%' OR `posts`.`body` LIKE '%smthg%') AND (`articles`.`name` = 'artcl') + # # 7. <tt>[:conditions]</tt>, <tt>[:values]</tt>, <tt>[:include]</tt>, <tt>[:joins]</tt> # You can pass additional conditions to grid's SQL query. E.g., # [:conditions] = "user_id = :user_id" # [:values] = { :user_id => "1" } # [:include] = [ :user ] # will select and add to @records only records of user with id = 1. # 8. <tt>[:paginate]</tt> # If you pass [:paginate] parameter, #paginate method will be used instead of # #find (i.e., you need will_paginate plugin). [:paginate] is a hash: # [:paginate][:page] - page you want to see # [:paginate][:per_page] - number of records per page + # 9. <tt>[:template]</tt> + # What template use for displaying the grid. Default is 'grid/grid' # # # == Default values of the options # # * <tt>[:columns][:show]</tt> - all columns of the table, except 'id', 'updated_at', 'created_at'. # * <tt>[:columns][:sort]</tt> - default is equal [:columns][:show] # * <tt>[:columns][:filter][:by_string]</tt> - default is empty array # * <tt>[:columns][:filter][:by_date]</tt> - default is empty array # * <tt>[:columns][:filter][:by_span_date]</tt> - default is empty array # * <tt>[:actions]</tt> - default is empty array # * <tt>[:filtered]</tt> - default is empty hash # * <tt>[:sorted]</tt> - default is empty hash # # # == User-defined display of actions and values # # You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean # column is true, and 'No' if it is false). For that, you should add method with name # gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in # app/helper and create file with filename gridname.rb. Let's implement example above: # # We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb # # module SolutionsGrid::Feeds # def feeds_restricted(record = nil) # value = record ? record.restricted : nil # { :key => "Restricted", :value => value ? "Yes" : "No" } # end # end # # Function should take one parameter (default is nil) and return hash with keys # <tt>:key</tt> - value will be used for the headers of the table # <tt>:value</tt> - value will be user for cells of the table # # If such method will not be founded, there are two ways to display values. # # * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. # * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. # * If column doesn't look like 'something_id' the plugin just display value of this column. # # You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. # Example for 'edit' action, file 'app/helpers/attributes/actions.rb': # # module SolutionsGrid::Actions # def action_edit(record = nil) # if record # url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') # value = link_to("Edit", url) # else # value = nil # end # { :key => "Edit", :value => value } # end # end # # # == Sort and filter # # To sort and filter records of the grid you *must* pass options <tt>:filtered</tt> or <tt>:sorted</tt>. # # == Examples of using the SolutionGrid # # <i>in controller:</i> # # def index # @table = Grid.new(:name => "feeds", :model => Feed, :columns => { :show => %{name body}}) # end # # <i>in view:</i> # # show_grid(@table) # # It will display feeds with 'name' and 'body'. There will be no actions and # filterable columns, all columns will be sortable, but because you don't pass # <tt>:sorted</tt> option, sort will not work. # # # <i>in controller:</i> # def index # @table = Grid.new( # :columns => { # :show => %w{name description}, # :sort => %w{name} # }, # :sorted => session[:sort] ? session[:sort][:feeds] : nil, # :name => "feeds", # :model => Feed # ) # end # # <i>in view:</i> # show_grid(@table) # # It will display feeds with columns 'name' and 'description'. There will be no actions and # filterable columns, 'name' column will be sortable, sort info is stored in # session[:sort][:feeds][:by_column] (session[:sort][:feeds] hash can be automatically # generated by grid_contoller of SolutionsGrid. Just add :sorted => session[:sort][:feeds], # and all other work will be done by the SolutionsGrid plugin) # # # <i>in controller:</i> # def index # @table = Grid.new( # :columns => { # :show => %w{name description}, # :filter => { # :by_string => %w{name} # }, # }, # :name => "feeds", # :model => Feed # :sorted => session[:sort][:feeds], # :filtered => session[:filter][:feeds], # :actions => %w{edit delete} # ) # end # # <i>in view:</i> # show_grid(@table, [ :text ]) # # It will display feeds with columns 'name' and 'description'. These columns will be sortable. # There will be actions 'edit' and 'delete' (but remember, you need action methods # 'action_edit' and 'action_delete' in SolutionGrid::Actions in 'app/helpers/attributes/actions.rb'). # There will be filterable column 'name', and it will be filtered by session[:filter][:feed][:by_string] value. # (that will be automatically generated by SolutionsGrid's grid_controller def initialize(options = {}) @options = {} @options[:name] = options[:name].to_s if options[:name] @options[:model] = options[:model] @options[:modelname] = @options[:model].to_s.underscore @options[:actions] = Array(options[:actions]) || [] @options[:conditions] = options[:conditions] @options[:values] = options[:values] || {} @options[:include] = Array(options[:include]) || [] @options[:joins] = options[:joins] @options[:paginate] = options[:paginate] + @options[:template] = options[:template] || 'grid/grid' options[:columns] ||= {} @columns = {} @columns[:show] = Array(options[:columns][:show] || []) @columns[:sort] = options[:columns][:sort] || @columns[:show].dup @columns[:filter] = options[:columns][:filter] @options[:sorted] = options[:sorted] @options[:filtered] = options[:filtered] check_for_errors @records = get_records @view = {} end def get_belonged_model_and_column(column) - belonged_column = column.match(/(.*)_id(.*)/) - if belonged_column && !belonged_column[2].blank? - column = belonged_column[2].gsub(/^(_)/, '') - [ belonged_column[1].camelize.constantize, column ] - elsif belonged_column && !belonged_column[1].blank? - [ belonged_column[1].camelize.constantize, 'name' ] + column_with_table = column.match(/(.*)\.(.*)/) + if column_with_table + table = column_with_table[1] + column = column_with_table[2] + return [ table, column ] else - [ nil, nil ] + position_match = column.index('_id') + if position_match + model = column[0..position_match - 1] + model_column = column[(position_match + 4)..-1] + if !model.blank? && !model_column.blank? + return [ model.camelize.constantize, model_column ] + elsif !model.blank? && model_column.blank? + return [ model.camelize.constantize, 'name' ] + end + else + return [ nil, nil ] + end end end def get_association(belonged_model) belonged_model.to_s.underscore.to_sym end def get_date(params) return nil if !params || params[:year].blank? params[:month] = params[:month].blank? ? 1 : params[:month] params[:day] = params[:day].blank? ? 1 : params[:day] conditions = [ params[:year].to_i, params[:month].to_i, params[:day].to_i ] conditions += [ params[:hour].to_i, params[:minute].to_i ] if params[:hour] DateTime.civil(*conditions) end private def get_records @include ||= [] method = @options[:paginate] ? :paginate : :find conditions = {} conditions.merge!(filter(@options[:filtered])) conditions.merge!(sort(@options[:sorted])) include_belonged_models_from_show_columns @include += @options[:include] conditions[:include] = @include conditions[:joins] = @options[:joins] if @options[:joins] if @options[:paginate] method = :paginate conditions.merge!(@options[:paginate]) else method = :find end @options[:model].send(method, :all, conditions) end def sort(options) return {} unless options order = (options[:order] == 'asc') ? "ASC" : "DESC" table_with_column = get_correct_table_with_column(options[:by_column]) @order = "#{table_with_column} #{order}" { :order => @order } end def filter(options) @conditions ||= [] @values ||= {} if options - filter_by_string + filter_by_strings filter_by_date end @conditions << "(" + @options[:conditions] + ")" if @options[:conditions] @values.merge!(@options[:values]) @conditions = @conditions.join(" AND ") { :conditions => [ @conditions, @values ] } end - def filter_by_string - string = @options[:filtered] ? @options[:filtered][:by_string] : nil - return if string.blank? - conditions = [] - Array(@columns[:filter][:by_string]).each do |column| - table_with_column = get_correct_table_with_column(column) - conditions << "#{table_with_column} LIKE :#{column}" - @values[column.to_sym] = "%#{string}%" + def filter_by_strings + filters = @options[:filtered].dup + filter_conditions = [] + filters.each do |name, filter| + string = filter ? filter[:text] : nil + next if string.blank? + conditions = [] + Array(@columns[:filter][name]).each do |column| + convert_to_belonged_model = filter.has_key?(:convert_id) ? filter[:convert_id] : true + table_with_column = get_correct_table_with_column(column, convert_to_belonged_model) + column = column.match(/\.(.*)/)[1] if column.match(/\.(.*)/) + if filter[:type] == :strict + conditions << "#{table_with_column} = :#{column}" + @values[column.to_sym] = string + else + conditions << "#{table_with_column} LIKE :#{column}" + @values[column.to_sym] = "%#{string}%" + end + end + filter_conditions << "(" + conditions.join(" OR ") + ")" end - @conditions << "(" + conditions.join(" OR ") + ")" + @conditions << "(" + filter_conditions.join(" AND ") + ")" unless filter_conditions.empty? end def filter_by_date from_date = @options[:filtered][:from_date] from_date = get_date(from_date) to_date = @options[:filtered][:to_date] to_date = get_date(to_date) return unless from_date || to_date date_conditions = [] Array(@columns[:filter][:by_date]).each do |column| conditions = [] table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} >= :#{column}_from_date" if from_date conditions << "#{table_with_column} <= :#{column}_to_date" if to_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{column}_from_date".to_sym] = from_date if from_date @values["#{column}_to_date".to_sym] = to_date if to_date end Array(@columns[:filter][:by_span_date]).each do |columns| conditions = [] table_with_column_from = get_correct_table_with_column(columns[0]) table_with_column_to = get_correct_table_with_column(columns[1]) conditions << "#{table_with_column_from} <= :#{columns[0]}_to_date" if to_date conditions << "#{table_with_column_to} >= :#{columns[1]}_from_date" if from_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{columns[0]}_to_date".to_sym] = to_date if to_date @values["#{columns[1]}_from_date".to_sym] = from_date if from_date end @conditions << date_conditions.join(" OR ") end - def get_correct_table_with_column(column) + def get_correct_table_with_column(column, convert_to_belonged_model = true) belonged_model, belonged_column = get_belonged_model_and_column(column) - if belonged_model + if belonged_model && convert_to_belonged_model by_column = ActiveRecord::Base.connection.quote_column_name(belonged_column) - association = get_association(belonged_model) - @include << association unless @include.include?(association) - return "#{belonged_model.table_name}.#{by_column}" + unless belonged_model.is_a?(String) + association = get_association(belonged_model) + @include << association unless @include.include?(association) + return "#{belonged_model.table_name}.#{by_column}" + else + by_model = ActiveRecord::Base.connection.quote_column_name(belonged_model) + return "#{by_model}.#{by_column}" + end else by_column = ActiveRecord::Base.connection.quote_column_name(column) return "#{@options[:model].table_name}.#{by_column}" end end def include_belonged_models_from_show_columns Array(@columns[:show]).each do |column| get_correct_table_with_column(column) end end end diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index d1eab74..da29c5b 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,133 +1,133 @@ module SolutionsGrid module GridHelper # This helper shows generated grid. It takes two arguments: # * grid - grid's object that you created in controller # * filter - array with filters (need for showing filter forms). It can contain: # * :text - show form with filter by string # * :date - show form with filter by date # You should have partial 'grid/grid' in your app/views directory with # template of the grid. You can get example of this grid in # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) - render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } + render :partial => grid.options[:template], :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? h(associated_record.send(belonged_column)) : "" else h(record.send(column)) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" additional_params[:params] = { :grid => grid.options[:name] } grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end end end diff --git a/spec/helpers/grid_helper_spec.rb b/spec/helpers/grid_helper_spec.rb index 657a84d..47ce175 100644 --- a/spec/helpers/grid_helper_spec.rb +++ b/spec/helpers/grid_helper_spec.rb @@ -1,83 +1,85 @@ require File.dirname(__FILE__) + '/../spec_helper' module SolutionsGrid::FeedExamples; end describe SolutionsGrid::GridHelper do before do @category = mock_model(CategoryExample, :name => "somecategory") - @feed = mock_model(FeedExample, :name => "somefeed", :category_id => @category.id, - :category => @category, :restricted => false, :descriptions => "Desc") + @feed = mock_model(FeedExample, :name => "somefeed", :category_example_id => @category.id, + :category_example => @category, :restricted => false, :descriptions => "Desc") FeedExample.stub!(:find).and_return([@feed]) FeedExample.stub!(:table_name).and_return("feeds") - set_column_names_and_hashes(FeedExample, :string => %w{name category_id restricted description}) + CategoryExample.stub!(:find).and_return([@category]) + CategoryExample.stub!(:table_name).and_return("category_examples") + set_column_names_and_hashes(FeedExample, :string => %w{name category_example_id restricted description}) set_column_names_and_hashes(DateExample, :string => %w{description}, :date => %w{date}) set_column_names_and_hashes(SpanDateExample, :string => %w{description}, :datetime => %w{start_datetime end_datetime}) helper.stub!(:render) end it "should display usual columns of model" do grid = Grid.new({ :columns => {:show => %w{name}}, :name => 'feed_examples', :model => FeedExample}) helper.show_grid(grid) grid.view[:headers].should == [ '<a href="http://test.host/grid/feed_examples/sort_by/name" class="sorted">Name</a>' ] grid.view[:records].should == [ [ 'somefeed' ] ] end it "should display user defined columns of model" do SolutionsGrid::FeedExamples.class_eval do define_method(:feed_examples_name) do |record| if record url = url_for(:controller => record.class.to_s.underscore, :action => 'edit', :id => record.id, :only_path => true) value = link_to(h(record.name), url) else value = nil end { :key => "Name", :value => value } end end - grid = Grid.new({ :columns => {:show => %w{name category_id}}, :name => 'feed_examples', :model => FeedExample}) + grid = Grid.new({ :columns => {:show => %w{name category_example_id}}, :name => 'feed_examples', :model => FeedExample}) helper.show_grid(grid) grid.view[:headers].should include('<a href="http://test.host/grid/feed_examples/sort_by/name" class="sorted">Name</a>') grid.view[:records][0][0].should match(/a href=\"\/feed_example\/edit\/\d+\">somefeed<\/a>/) SolutionsGrid::FeedExamples.class_eval do remove_method(:feed_examples_name) end end it "should display columns with actions" do SolutionsGrid::Actions.class_eval do define_method(:action_edit) do |record| if record url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') value = link_to("Edit", url) else value = nil end { :key => "Edit", :value => value } end end - grid = Grid.new({ :columns => {:show => %w{name category_id}}, :actions => [ 'edit' ], :name => 'feed_examples', :model => FeedExample}) + grid = Grid.new({ :columns => {:show => %w{name category_example_id}}, :actions => [ 'edit' ], :name => 'feed_examples', :model => FeedExample}) helper.show_grid(grid) grid.view[:headers].should include("Edit") grid.view[:records].should == [["somefeed", "somecategory", "<a href=\"/feed_examples/edit\">Edit</a>"]] SolutionsGrid::Actions.class_eval do remove_method(:action_edit) end end it "should display sorting up arrow (&#8595;) if sorted as 'asc'" do - grid = Grid.new({ :columns => {:show => %w{name category_id}}, :sorted => {:by_column => 'name', :order => 'asc'}, :name => 'feed_examples', :model => FeedExample}) + grid = Grid.new({ :columns => {:show => %w{name category_example_id}}, :sorted => {:by_column => 'name', :order => 'asc'}, :name => 'feed_examples', :model => FeedExample}) helper.show_grid(grid) grid.view[:headers].should include("<a href=\"http://test.host/grid/feed_examples/sort_by/name\" class=\"sorted\">Name</a> &#8595;") end it "should display sorting up arrow (&#8595;) if sorted as 'asc'" do - grid = Grid.new({ :columns => {:show => %w{name category_id}}, :sorted => {:by_column => 'name'}, :name => 'feed_examples', :model => FeedExample}) + grid = Grid.new({ :columns => {:show => %w{name category_example_id}}, :sorted => {:by_column => 'name'}, :name => 'feed_examples', :model => FeedExample}) helper.show_grid(grid) grid.view[:headers].should include("<a href=\"http://test.host/grid/feed_examples/sort_by/name\" class=\"sorted\">Name</a> &#8593;") end end \ No newline at end of file diff --git a/spec/models/grid_spec.rb b/spec/models/grid_spec.rb index 4e47da4..0b521b9 100644 --- a/spec/models/grid_spec.rb +++ b/spec/models/grid_spec.rb @@ -1,285 +1,340 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Grid do before do @category = mock_model(CategoryExample, :name => "somecategory", :description => "category description") - @feed = mock_model(FeedExample, :name => "somefeed", :category_id => @category.id, :category => @category, :restricted => false, :description => "Description") + @feed = mock_model(FeedExample, :name => "somefeed", :category_example_id => @category.id, :category => @category, :restricted => false, :description => "Description") FeedExample.stub!(:find).and_return([@feed]) FeedExample.stub!(:table_name).and_return("feeds") - set_column_names_and_hashes(FeedExample, :string => %w{name category_id restricted description}) + CategoryExample.stub!(:find).and_return([@category]) + CategoryExample.stub!(:table_name).and_return("categories") + set_column_names_and_hashes(FeedExample, :string => %w{name category_example_id restricted description}) set_column_names_and_hashes(DateExample, :string => %w{description}, :date => %w{date}) set_column_names_and_hashes(SpanDateExample, :string => %w{description}, :datetime => %w{start_datetime end_datetime}) set_column_names_and_hashes(HABTMExample, :string => %w{description}) - @columns = %w{name category_id restricted} + @columns = %w{name category_example_id restricted} end describe "common operations" do it "should copy option 'columns to show' to 'columns to sort' if 'columns to sort' is not specified" do grid = Grid.new(default_options.merge({ :columns => {:show => @columns.dup}})) grid.columns[:sort].all? { |c| @columns.include?(c) }.should be_true end it "should not copy option 'columns to show' to 'columns to sort' or 'columns to filter' if they are specified" do grid = Grid.new(default_options({ :columns => { :show => @columns.dup, - :filter => { :by_string => @columns.dup.delete_if {|column| column == 'category_id'}}, + :filter => { :by_string => @columns.dup.delete_if {|column| column == 'category_example_id'}}, :sort => @columns.dup.delete_if {|column| column == 'restricted'}, }})) - grid.columns[:sort].all? { |c| %w{name category_id}.include?(c) }.should be_true + grid.columns[:sort].all? { |c| %w{name category_example_id}.include?(c) }.should be_true grid.columns[:filter][:by_string].all? { |c| %w{name restricted}.include?(c) }.should be_true end end describe "errors handling" do it "should raise an error if model is not defined" do lambda { Grid.new() }.should raise_error(SolutionsGrid::ErrorsHandling::ModelIsNotDefined) end - it "should raise an error if we try to filter by column that not included to 'show'" do - lambda do - Grid.new(default_options.merge({ :columns => { :show => @columns, :filter => { :by_string => @columns + [ 'something' ]}}})) - end.should raise_error(SolutionsGrid::ErrorsHandling::ColumnIsNotIncludedToShow) - end - it "should raise an error if we try to sort by column that not included to 'show'" do lambda do Grid.new(default_options.merge({ :columns => { :show => @columns, :sort => @columns + [ 'something' ]}})) end.should raise_error(SolutionsGrid::ErrorsHandling::ColumnIsNotIncludedToShow) end it "should raise an error if we try show unexisted action" do lambda do Grid.new(default_options.merge(:actions => %w{unexisted})) end.should raise_error(SolutionsGrid::ErrorsHandling::UnexistedAction) end it "should raise an error when we trying to sort by column that forbidden to sort" do lambda do - Grid.new(default_options.merge(:columns => { :show => @columns, :sort => %w{category_id}}, :sorted => { :by_column => "name"})) + Grid.new(default_options.merge(:columns => { :show => @columns, :sort => %w{category_example_id}}, :sorted => { :by_column => "name"})) end.should raise_error(SolutionsGrid::ErrorsHandling::UnexistedColumn) end # it "should raise an error when :filter_by_span_date contains not 2 dates" do # span_dates = create_ten_span_date_mocks # lambda do # grid = Grid.new(span_dates, { :columns => { :filter => { :by_span_date => [['start_datetime', 'end_datetime', 'start_datetime']]}}}.merge(default_options)) # end.should raise_error(SolutionsGrid::ErrorsHandling::IncorrectSpanDate) # end # it "should raise an error if Date To < Date From" do # grid = Grid.new(default_options.merge({ # :columns => { # :show => @columns, # :filter => { :by_date => %w{date} } # }, # :filtered => { :from_date => } # })) # lambda do # grid.filter_by_dates({'year' => default_date.year, 'month' => default_date.month, 'day' => default_date.day + 2}, # {'year' => default_date.year, 'month' => default_date.month, 'day' => default_date.day}) # end.should raise_error(SolutionsGrid::ErrorsHandling::IncorrectDate) # end it "should raise an error if user didn't give a name to the grid." do lambda { Grid.new(:model => FeedExample) }.should raise_error(SolutionsGrid::ErrorsHandling::NameIsntSpecified) end end describe "sorting" do it "should sort records by usual column (i.e, by feed name)" do sort("name", 'asc') do |grid| grid.order.should == "feeds.`name` ASC" end end it "should sort records by calculated column (i.e, by feed category)" do - sort("category_id", 'asc') do |grid| + sort("category_example_id", 'asc') do |grid| grid.order.should == "categories.`name` ASC" - grid.include.should include(:category) + grid.include.should include(:category_example) end end it "should sort records by calculated column with specified name (i.e, by feed's category description)" do - sort("category_id_description", 'asc', { :columns => { :show => @columns + ['category_id_description']}}) do |grid| + sort("category_example_id_description", 'asc', { :columns => { :show => @columns + ['category_example_id_description']}}) do |grid| grid.order.should == "categories.`description` ASC" - grid.include.should include(:category) + grid.include.should include(:category_example) end end it "should sort records by calculated column (i.e, by feed category)" do - sort("category_id", 'asc') do |grid| + sort("category_example_id", 'asc') do |grid| grid.order.should == "categories.`name` ASC" - grid.include.should include(:category) + grid.include.should include(:category_example) end end it "should sort by 'desc' if other is not specified" do sort("name") do |grid| grid.order.should == "feeds.`name` DESC" end end it "should sort records by reverse order" do sort("name", 'desc') do |grid| grid.order.should == "feeds.`name` DESC" end end end describe "filtering" do it "should filter by usual column" do usual_filter('junk') do |grid| - grid.conditions.should == '(feeds.`name` LIKE :name OR categories.`name` LIKE :category_id OR categories.`description` LIKE :category_id_description)' - grid.values.keys.all? {|k| [ :name, :category_id, :category_id_description ].include?(k) }.should be_true + grid.conditions.should == '((feeds.`name` LIKE :name OR categories.`name` LIKE :category_example_id OR categories.`description` LIKE :category_example_id_description))' + grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description ].include?(k) }.should be_true grid.values[:name].should == '%junk%' - grid.include.should == [ :category ] + grid.include.should == [ :category_example ] + end + end + + it "should filter by some usual columns" do + grid = Grid.new(default_options( + :columns => { + :show => @columns + [ "category_example_id_description" ], + :filter => { + :by_string => %w{name category_example_id_description}, + :by_category_example_id => %w{category_example_id} + } + }, + :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict, :convert_id => false } } + )) + grid.conditions.split(" AND ").all? do |a| + [ + '((feeds.`name` LIKE :name OR categories.`description` LIKE :category_example_id_description)', + '(feeds.`category_example_id` = :category_example_id))' + ].should include(a) end + grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description ].include?(k) }.should be_true + grid.values[:name].should == '%junk%' + grid.values[:category_example_id].should == '4' + grid.include.should == [ :category_example ] + end + + it "should filter by belonged column that contains _id" do + grid = Grid.new(default_options( + :columns => { + :show => @columns + [ "category_example_id_description_id" ], + :filter => { + :by_string => %w{name}, + :by_category_example_id => %w{category_example_id_description_id} + } + }, + :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict } } + )) + grid.conditions.should == "((feeds.`name` LIKE :name) AND (categories.`description_id` = :category_example_id_description_id))" + grid.values.keys.all? {|k| [ :name, :category_example_id, :category_example_id_description_id ].include?(k) }.should be_true + grid.values[:name].should == '%junk%' + grid.values[:category_example_id_description_id].should == '4' + grid.include.should == [ :category_example ] + end + + it "should filter by table.column if dot is presented" do + grid = Grid.new(default_options( + :columns => { + :show => @columns + [ "category_example_id" ], + :filter => { + :by_string => %w{name}, + :by_category_example_id => %w{category_examples.description_id} + } + }, + :filtered => { :by_string => { :text => "junk", :type => :match }, :by_category_example_id => { :text => "4", :type => :strict } } + )) + grid.conditions.should == "((feeds.`name` LIKE :name) AND (`category_examples`.`description_id` = :description_id))" + grid.values.keys.all? {|k| [ :name, :description_id ].include?(k) }.should be_true + grid.values[:name].should == '%junk%' + grid.values[:description_id].should == '4' + grid.include.should == [ :category_example ] end it "should filter with user-defined conditions" do grid = Grid.new(default_options( :columns => { :show => @columns, - :filter => { :by_string => %w{name category_id} } + :filter => { :by_string => %w{name category_example_id} } }, - :filtered => { :by_string => 'smt' }, + :filtered => { :by_string => { :text => 'smt', :type => :match } }, :conditions => "feeds_partners.partner_id = :partner_id", :values => { :partner_id => 1 }, :include => [ :partners ] )) - grid.conditions.should == '(feeds.`name` LIKE :name OR categories.`name` LIKE :category_id) AND (feeds_partners.partner_id = :partner_id)' - grid.values.keys.all? {|k| [ :name, :category_id, :partner_id ].include?(k) }.should be_true + grid.conditions.should == '((feeds.`name` LIKE :name OR categories.`name` LIKE :category_example_id)) AND (feeds_partners.partner_id = :partner_id)' + grid.values.keys.all? {|k| [ :name, :category_example_id, :partner_id ].include?(k) }.should be_true grid.values[:partner_id].should == 1 - grid.include.should == [ :category, :partners ] + grid.include.should == [ :category_example, :partners ] end it "should save all records when usual filter is empty" do usual_filter('') do |grid| grid.conditions.should == '' grid.values.should == {} - grid.include.should == [:category] + grid.include.should == [:category_example] end end it "should filter records by date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{date description}, :filter => { :by_date => %w{date} }}, :filtered => { :from_date => { :year => "2006" }, :to_date => { :year => "2008", :month => "12" }} )) grid.conditions.should == '(date_examples.`date` >= :date_from_date AND date_examples.`date` <= :date_to_date)' grid.values.keys.all? {|k| [ :date_from_date, :date_to_date ].include?(k) }.should be_true grid.values[:date_from_date].should == DateTime.civil(2006, 1, 1) grid.include.should == [ ] end it "should filter records with overlapping span of date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :year => "2006", :day => "12" }, :to_date => { :year => "2008", :month => "12", :day => "15" }} )) grid.conditions.should == "(date_examples.`start_date` <= :start_date_to_date AND date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.all? {|k| [ :start_date_to_date, :end_date_from_date ].include?(k) }.should be_true grid.values[:end_date_from_date].should == DateTime.civil(2006, 1, 12) grid.include.should == [ ] end it "should filter records with overlapping span of date without start date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :day => "12" }, :to_date => { :year => "2008", :month => "12", :day => "15" }} )) grid.conditions.should == "(date_examples.`start_date` <= :start_date_to_date)" grid.values.keys.should == [ :start_date_to_date ] grid.values[:start_date_to_date].should == DateTime.civil(2008, 12, 15) grid.include.should == [ ] end it "should filter records with overlapping span of date without end date" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_span_date => [ %w{start_date end_date} ] }}, :filtered => { :from_date => { :year => "2008", :day => "12" } } )) grid.conditions.should == "(date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.should == [ :end_date_from_date ] grid.values[:end_date_from_date].should == DateTime.civil(2008, 1, 12) grid.include.should == [ ] end it "should filter records with overlapping span of date with string" do filter_date_example_expectations grid = Grid.new(default_options.merge( :model => DateExample, :columns => { :show => %w{start_date end_date description}, :filter => { :by_string => [ 'description' ], :by_span_date => [ %w{start_date end_date} ] }}, - :filtered => { :by_string => "text", :from_date => { :year => "2008", :day => "12" }, :to_date => { :year => "2008", :day => "16" } } + :filtered => { :by_string => {:text => "text", :type => :match }, :from_date => { :year => "2008", :day => "12" }, :to_date => { :year => "2008", :day => "16" } } )) - grid.conditions.should == "(date_examples.`description` LIKE :description) AND (date_examples.`start_date` <= :start_date_to_date AND date_examples.`end_date` >= :end_date_from_date)" + grid.conditions.should == "((date_examples.`description` LIKE :description)) AND (date_examples.`start_date` <= :start_date_to_date AND date_examples.`end_date` >= :end_date_from_date)" grid.values.keys.all? {|k| [:end_date_from_date, :description, :start_date_to_date].include?(k) }.should be_true grid.values[:end_date_from_date].should == DateTime.civil(2008, 1, 12) grid.include.should == [ ] end end def sort(by_column, order = nil, options = {}) raise "Block should be given" unless block_given? grid = Grid.new(default_options.merge(:sorted => { :by_column => by_column, :order => order}).merge(options)) yield(grid) end def usual_filter(by_string) raise "Block should be given" unless block_given? grid = Grid.new(default_options( :columns => { - :show => @columns + [ "category_id_description" ], - :filter => { :by_string => %w{name category_id category_id_description} } + :show => @columns + [ "category_example_id_description" ], + :filter => { :by_string => %w{name category_example_id category_example_id_description} } }, - :filtered => { :by_string => by_string } + :filtered => { :by_string => { :text => by_string, :type => :match } } )) yield(grid) end def default_options(options = {}) { :name => 'feed', :model => FeedExample, :columns => { :show => @columns.dup, - :sort => %w{name category_id}, - :filter => {:by_string => %w{name category_id}} + :sort => %w{name category_example_id}, + :filter => {:by_string => %w{name category_example_id}} } }.merge(options) end def default_date Date.civil(2008, 10, 5) end def default_datetime DateTime.civil(2008, 10, 5, 15, 15, 0) end def filter_date_example_expectations date = mock_model(DateExample, :start_date => default_date, :end_date => default_date + 3.months, :description => "Desc") DateExample.should_receive(:find).and_return([date]) DateExample.stub!(:table_name).and_return("date_examples") end end \ No newline at end of file
astashov/solutions_grid
c9aec199d2d51db99e42ba5cf8c58a05d194861f
Added escaping to output values of grid
diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index b4c043a..d1eab74 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,133 +1,133 @@ module SolutionsGrid module GridHelper # This helper shows generated grid. It takes two arguments: # * grid - grid's object that you created in controller # * filter - array with filters (need for showing filter forms). It can contain: # * :text - show form with filter by string # * :date - show form with filter by date # You should have partial 'grid/grid' in your app/views directory with # template of the grid. You can get example of this grid in # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) - associated_record.respond_to?(belonged_column) ? associated_record.send(belonged_column) : "" + associated_record.respond_to?(belonged_column) ? h(associated_record.send(belonged_column)) : "" else - record.send(column) + h(record.send(column)) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" additional_params[:params] = { :grid => grid.options[:name] } grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end end end
astashov/solutions_grid
a100bf0478e24b835e0506504706dab262bd41fd
Fixed README. Added destroying of session[:page][grid_name] while filtering %grid_name%.
diff --git a/README b/README index 8f52005..1a4468b 100644 --- a/README +++ b/README @@ -1,111 +1,115 @@ == Description This is Ruby On Rails plugin, implementing AJAXed grid with sorting, filtering and paginating (with help of will_paginate plugin). == Features * AJAXed Sorting and Filtering (works only with jQuery). * Sorting and Filtering without AJAX. * User-defined grid templates * User-defined actions and record's values. == Installation git clone git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid or as submodule git submodule add git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid == Using For using of this plugin, you should do 3 steps: 1. Create grid object in your controller. @grid = Grid.new(:name => "users", :model => User, :columns => { :show => %w{login email} }) 2. Show this grid object by show_grid helper in your view show_grid(@grid) 3. Create 'grid/grid' partial in your app/views directory with template of the grid (you can find examples in files/app/views/grid directory) + 4. Add plugin's routes to your routes.rb + + map.grid_routes + Also, there are optional additional features: 4. Get jquery and livequery javascript libraries. Copy files/public/javascripts/solutions_grid.js to your javascript directory and add to your layout: javascript_include_tag "jquery" javascript_include_tag "jquery.livequery" javascript_include_tag "solutions_grid" It will add AJAXed sorting and filtering to your grid. 5. Create your own rules to display fields and actions of the grid by creating files in app/helpers/attributes (see below) 6. You can tweak the grid object by many additional parameters (look at documentation to Grid.new and show_grid). == User-defined display of actions and values You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean column is true, and 'No' if it is false). For that, you should add method with name gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in app/helper and create file with filename gridname.rb. Let's implement example above: We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb module SolutionsGrid::Feeds def feeds_restricted(record = nil) value = record ? record.restricted : nil { :key => "Restricted", :value => value ? "Yes" : "No" } end end Function should take one parameter (default is nil) and return hash with keys :key - value will be used for the headers of the table :value - value will be user for cells of the table If such method will not be founded, there are two ways to display values. * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. * If column doesn't look like 'something_id' the plugin just display value of this column. You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. Example for 'edit' action, file 'app/helpers/attributes/actions.rb': module SolutionsGrid::Actions def action_edit(record = nil) if record url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') value = link_to("Edit", url) else value = nil end { :key => "Edit", :value => value } end end == TODO 1. Make AJAX support with Prototype library too. == Bugreporting Please, post bugs here: http://astashov.lighthouseapp.com/projects/20777-solutions-grid == Authors and Credits Written by Anton Astashov, with Brenton Cheng, for Astrology.com (a division of iVillage Inc.) Released under the MIT license. \ No newline at end of file diff --git a/lib/solutions_grid/controllers/grid_controller.rb b/lib/solutions_grid/controllers/grid_controller.rb index fc614c3..3077fa2 100644 --- a/lib/solutions_grid/controllers/grid_controller.rb +++ b/lib/solutions_grid/controllers/grid_controller.rb @@ -1,82 +1,83 @@ class GridController < ApplicationController def sort raise "You don't specify column to sort" unless params[:column] name = params[:grid_name].to_sym session[:sort] ||= {} controller = params[:controller].to_sym session[:sort][name] ||= {} # If we sorted records by this column before, then just change sort order if session[:sort][name][:by_column] && session[:sort][name][:by_column] == params[:column] previous_order = session[:sort][name][:order] session[:sort][name][:order] = (previous_order == 'asc') ? 'desc' : 'asc' else session[:sort][name][:order] = 'asc' session[:sort][name][:by_column] = params[:column] end flash[:notice] = "Data was sorted by #{CGI.escapeHTML(params[:column]).humanize}" respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end def filter name = params[:grid_name].to_sym session[:filter] ||= {} session[:filter][name] ||= {} + session[:page].delete(name) if session[:page] if params[:commit] == 'Clear' session[:filter][name] = nil flash[:notice] = "Filter was cleared" else from_date = params[(name.to_s + '_from_date').to_sym] to_date = params[(name.to_s + '_to_date').to_sym] by_string = params[(name.to_s + '_string_filter').to_sym] || "" session[:filter][name][:from_date] = from_date session[:filter][name][:to_date] = to_date session[:filter][name][:by_string] = by_string flash[:notice] = "Data was filtered by #{CGI.escapeHTML(by_string).humanize}" end respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end private def error_handling(msg) msg = msg.to_s[0..1000] + "..." if msg.to_s.length > 1000 flash[:error] = CGI.escapeHTML(msg.to_s) request.env["HTTP_REFERER"] ||= root_url redirect_to :back end end
astashov/solutions_grid
5d2ee354dd16fdfb8799338b8b077335d45819e8
Fixed pagination - added grid name to params
diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index f900fed..b4c043a 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,132 +1,133 @@ module SolutionsGrid module GridHelper # This helper shows generated grid. It takes two arguments: # * grid - grid's object that you created in controller # * filter - array with filters (need for showing filter forms). It can contain: # * :text - show form with filter by string # * :date - show form with filter by date # You should have partial 'grid/grid' in your app/views directory with # template of the grid. You can get example of this grid in # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? associated_record.send(belonged_column) : "" else record.send(column) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" + additional_params[:params] = { :grid => grid.options[:name] } grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end end end
astashov/solutions_grid
ab905811f925aee0c4f928304c8d275f4d27dd9e
Removed old code from grid_helper
diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index d6882e8..f900fed 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,151 +1,132 @@ module SolutionsGrid module GridHelper # This helper shows generated grid. It takes two arguments: # * grid - grid's object that you created in controller # * filter - array with filters (need for showing filter forms). It can contain: # * :text - show form with filter by string # * :date - show form with filter by date # You should have partial 'grid/grid' in your app/views directory with # template of the grid. You can get example of this grid in # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? associated_record.send(belonged_column) : "" else record.send(column) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end -# def add_select_tags(grid) -# prefix = set_name_prefix(grid) -# type = grid.options[:type_of_date_filtering] -# klass = (type == :datetime) ? DateTime : type.to_s.camelize.constantize -# output = "<label for=\"date_filter\">#{klass.to_s} Filter:</label><br />" -# now = klass.today rescue klass.now -# -# from_date = grid.convert_to_date(grid.options[:filtered][:from_date], type) rescue now -# to_date = grid.convert_to_date(grid.options[:filtered][:to_date], type) rescue now -# helper_name = "select_#{type}".to_sym -# -# output += send(helper_name, from_date, :prefix => "#{prefix}from_date") + "<br />" -# output += send(helper_name, to_date, :prefix => "#{prefix}to_date") + "<br />" -# output -# end -# -# def set_name_prefix(grid) -# grid.options[:name] + "_" -# end end end
astashov/solutions_grid
72c1f1d1a170cd7e3ba39e130dd7ebefb781c3b0
Fixed README
diff --git a/README b/README index 5c6edf8..8f52005 100644 --- a/README +++ b/README @@ -1,111 +1,111 @@ == Description This is Ruby On Rails plugin, implementing AJAXed grid with sorting, filtering and paginating (with help of will_paginate plugin). == Features * AJAXed Sorting and Filtering (works only with jQuery). * Sorting and Filtering without AJAX. * User-defined grid templates * User-defined actions and record's values. == Installation git clone git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid or as submodule git submodule add git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid == Using For using of this plugin, you should do 3 steps: 1. Create grid object in your controller. @grid = Grid.new(:name => "users", :model => User, :columns => { :show => %w{login email} }) 2. Show this grid object by show_grid helper in your view show_grid(@grid) 3. Create 'grid/grid' partial in your app/views directory with template of the grid (you can find examples in files/app/views/grid directory) Also, there are optional additional features: 4. Get jquery and livequery javascript libraries. Copy files/public/javascripts/solutions_grid.js to your javascript directory and add to your layout: - = javascript_include_tag "jquery" - = javascript_include_tag "jquery.livequery" - = javascript_include_tag "solutions_grid" + javascript_include_tag "jquery" + javascript_include_tag "jquery.livequery" + javascript_include_tag "solutions_grid" It will add AJAXed sorting and filtering to your grid. 5. Create your own rules to display fields and actions of the grid by creating files in app/helpers/attributes (see below) 6. You can tweak the grid object by many additional parameters (look at documentation to Grid.new and show_grid). == User-defined display of actions and values You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean column is true, and 'No' if it is false). For that, you should add method with name gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in app/helper and create file with filename gridname.rb. Let's implement example above: We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb module SolutionsGrid::Feeds def feeds_restricted(record = nil) value = record ? record.restricted : nil { :key => "Restricted", :value => value ? "Yes" : "No" } end end Function should take one parameter (default is nil) and return hash with keys :key - value will be used for the headers of the table :value - value will be user for cells of the table If such method will not be founded, there are two ways to display values. * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. * If column doesn't look like 'something_id' the plugin just display value of this column. You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. Example for 'edit' action, file 'app/helpers/attributes/actions.rb': module SolutionsGrid::Actions def action_edit(record = nil) if record url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') value = link_to("Edit", url) else value = nil end { :key => "Edit", :value => value } end end == TODO 1. Make AJAX support with Prototype library too. == Bugreporting Please, post bugs here: http://astashov.lighthouseapp.com/projects/20777-solutions-grid == Authors and Credits Written by Anton Astashov, with Brenton Cheng, for Astrology.com (a division of iVillage Inc.) Released under the MIT license. \ No newline at end of file
astashov/solutions_grid
59cfc6087e86c220713358809c673496cf950111
Added LICENSE
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fe97a2f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +== MIT License + +Copyright (c) 2008 iVillage Inc (http://www.ivillage.com/). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file
astashov/solutions_grid
1c78dda00c52b2aa751a20f44f203a06be29700c
Wrote documentation to the plugin
diff --git a/README b/README index 8ea319e..5c6edf8 100644 --- a/README +++ b/README @@ -1,13 +1,111 @@ -SolutionsGrid -============= +== Description -Introduction goes here. +This is Ruby On Rails plugin, implementing AJAXed grid with sorting, filtering and +paginating (with help of will_paginate plugin). -Example -======= +== Features -Example goes here. + * AJAXed Sorting and Filtering (works only with jQuery). + * Sorting and Filtering without AJAX. + * User-defined grid templates + * User-defined actions and record's values. -Copyright (c) 2008 [name of plugin creator], released under the MIT license +== Installation + + git clone git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid + +or as submodule + + git submodule add git://github.com/astashov/solutions_grid.git vendor/plugins/solutions_grid + + +== Using + +For using of this plugin, you should do 3 steps: + + 1. Create grid object in your controller. + + @grid = Grid.new(:name => "users", :model => User, :columns => { :show => %w{login email} }) + + 2. Show this grid object by show_grid helper in your view + + show_grid(@grid) + + 3. Create 'grid/grid' partial in your app/views directory with template of the grid + (you can find examples in files/app/views/grid directory) + +Also, there are optional additional features: + + 4. Get jquery and livequery javascript libraries. Copy + files/public/javascripts/solutions_grid.js to your javascript directory + and add to your layout: + + = javascript_include_tag "jquery" + = javascript_include_tag "jquery.livequery" + = javascript_include_tag "solutions_grid" + + It will add AJAXed sorting and filtering to your grid. + + 5. Create your own rules to display fields and actions of the grid by creating + files in app/helpers/attributes (see below) + + 6. You can tweak the grid object by many additional parameters (look at documentation + to Grid.new and show_grid). + + +== User-defined display of actions and values + + You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean + column is true, and 'No' if it is false). For that, you should add method with name + gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in + app/helper and create file with filename gridname.rb. Let's implement example above: + + We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb + + module SolutionsGrid::Feeds + def feeds_restricted(record = nil) + value = record ? record.restricted : nil + { :key => "Restricted", :value => value ? "Yes" : "No" } + end + end + + Function should take one parameter (default is nil) and return hash with keys + :key - value will be used for the headers of the table + :value - value will be user for cells of the table + + If such method will not be founded, there are two ways to display values. + + * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. + * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. + * If column doesn't look like 'something_id' the plugin just display value of this column. + + You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. + Example for 'edit' action, file 'app/helpers/attributes/actions.rb': + + module SolutionsGrid::Actions + def action_edit(record = nil) + if record + url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') + value = link_to("Edit", url) + else + value = nil + end + { :key => "Edit", :value => value } + end + end + + +== TODO + +1. Make AJAX support with Prototype library too. + +== Bugreporting + +Please, post bugs here: http://astashov.lighthouseapp.com/projects/20777-solutions-grid + +== Authors and Credits + +Written by Anton Astashov, with Brenton Cheng, for Astrology.com (a division of iVillage Inc.) +Released under the MIT license. \ No newline at end of file diff --git a/lib/solutions_grid/grid.rb b/lib/solutions_grid/grid.rb index e894f13..40ccfbe 100644 --- a/lib/solutions_grid/grid.rb +++ b/lib/solutions_grid/grid.rb @@ -1,345 +1,359 @@ # Main class of the SolutionGrid plugin. It stores array of records (ActiveRecord # objects or simple hashes). It can construct SQL query with different operations with # these records, such as sorting and filtering. With help of GridHelper it can # show these records as table with sortable headers, show filters. class Grid include SolutionsGrid::ErrorsHandling attr_accessor :view attr_reader :records, :options, :columns, :conditions, :values, :include, :order - # To initialize grid, you should pass and +options+ as parameter. + # Grid initialization. It constructs SQL query (with sorting and filtering + # conditions, optionally), then fill @records by result of query. This + # array of records you can use in helper, show_grid(). # # == Options # # === Required # - # These options you *must* to set - # * <tt>:name</tt> - set name of the grid. This parameter will be used for storing - # sorted and filtered info if there are more than one grid on the page. - # * <tt>:model</tt> - set model. It will be used for constructing column names, - # if columns is not specified obviously and there are no records - # specified for displaying. - # * <tt>:columns</tt> - sets columns of records to show, filter and sort. Pass columns as arrays. - # * -> <tt>[:columns][:show]</tt> - pass columns you need to show (as array, do you remember? :)) - # * -> <tt>[:columns][:sort]</tt> - pass columns you need to allow sorting. - # * -> <tt>[:columns][:filter][:by_string]</tt> - pass columns you need to allow filtering by string. - # * -> <tt>[:columns][:filter][:by_date]</tt> - pass columns you need to allow filtering by date. - # * -> <tt>[:columns][:filter][:by_span_date]</tt> - pass columns you need to allow filtering by span of date. - # You should pass columns as array of arrays - # (format of arrays - [ start_date_column, end_date_column ]) - # * <tt>:filter_path</tt> - set path to send filter requests. This path should lead to action, - # that write filter to session. You should pass hash with keys: - # <tt>:controller</tt> - the controller that contains the sort action, - # <tt>:action</tt> - # See details below. - # * <tt>:sort_path</tt> - set path to send sort requests. This path should lead to action, - # that write sort column to session. See details below. Syntax is similar to <tt>:filter_path</tt> - # * <tt>:actions</tt> - pass necessary actions (such as 'edit', 'destroy', 'duplicate'). Details about actions see below. - # * <tt>:filtered</tt> - pass hash with parameters: - # * -> <tt>[:filtered][:by_string]</tt> - if you pass string, all 'filtered by string' columns will be filtered by this string - # * -> <tt>[:filtered][:by_date]</tt> - if you pass date (in Date or DateTime format), all - # 'filtered by date' columns will be filtered by this date - # * -> <tt>[:filtered][:by_span_date]</tt> - if you pass array of 2 dates (start date and end date) - # (in Date or DateTime format), all 'filtered by span of date' - # columns will be filtered by this span - # * <tt>:type_of_date_filtering</tt> - show filter form with date or datetime select boxes. If you display Hashes, - # it will show Date by default. If you display ActiveRecord objects, - # there will try to decide about select boxed automatically. - # You can pass Date or DateTime parameters. + # 1. <tt>[:name]</tt> + # Set name of the grid. This parameter will be used for storing sorted and + # filtered info of this grid. + # 2. <tt>[:model]</tt> + # Set model. It will be used for constructing SQL query. + # 3. <tt>[:columns][:show]</tt> + # Columns that you need to show, pass as array, e.g. %w{ name body } # - # + # === Optional + # + # 1. <tt>[:columns][:sort]</tt> + # Pass columns you need to allow sorting. Default is columns to show. + # 2. <tt>[:columns][:filter][:by_string]</tt> + # Pass columns you need to allow filtering by string. + # 3. <tt>[:columns][:filter][:by_date]</tt> + # Pass columns you need to allow filtering by date. + # 4. <tt>[:columns][:filter][:by_span_date]</tt> + # Pass columns you need to allow filtering by span of date. You should pass + # columns as array of arrays (format of arrays - [ start_date_column, + # end_date_column ]), e.g. [ [start_date_column, end_date_column] ]. + # 5. <tt>[:actions]</tt> + # Pass necessary actions (such as 'edit', 'destroy', 'duplicate'). + # Details about actions see below. + # 6. <tt>[:sorted]</tt> + # Pass column to SQL query that will be sorted and order of sorting. Example: + # [:sorted] = { :by_column => "name", :order => "asc" } + # 6. <tt>[:filtered]</tt> + # Pass hash with parameters: + # * <tt>[:filtered][:by_string]</tt> + # If you pass string, all 'filtered by string' columns will be filtered by this string + # * <tt>[:filtered][:from_date]</tt> and [:filtered][:end_date] + # [:columns][:filter][:by_date] should have date that is in range + # of these dates (otherwise, it will not be in @records array). + # [:columns][:filter][:by_span_date] should have date range that intersects + # with range of these dates. + # 7. <tt>[:conditions]</tt>, <tt>[:values]</tt>, <tt>[:include]</tt>, <tt>[:joins]</tt> + # You can pass additional conditions to grid's SQL query. E.g., + # [:conditions] = "user_id = :user_id" + # [:values] = { :user_id => "1" } + # [:include] = [ :user ] + # will select and add to @records only records of user with id = 1. + # 8. <tt>[:paginate]</tt> + # If you pass [:paginate] parameter, #paginate method will be used instead of + # #find (i.e., you need will_paginate plugin). [:paginate] is a hash: + # [:paginate][:page] - page you want to see + # [:paginate][:per_page] - number of records per page + # + # # == Default values of the options + # # * <tt>[:columns][:show]</tt> - all columns of the table, except 'id', 'updated_at', 'created_at'. # * <tt>[:columns][:sort]</tt> - default is equal [:columns][:show] - # * <tt>[:columns][:filter][:by_string]</tt> - default is equal [:columns][:show] + # * <tt>[:columns][:filter][:by_string]</tt> - default is empty array # * <tt>[:columns][:filter][:by_date]</tt> - default is empty array # * <tt>[:columns][:filter][:by_span_date]</tt> - default is empty array # * <tt>[:actions]</tt> - default is empty array # * <tt>[:filtered]</tt> - default is empty hash # * <tt>[:sorted]</tt> - default is empty hash # # - # == About custom display of actions and values - # You can create your own rules to display columns (i.e., you need to show 'Yes' if some boolean + # == User-defined display of actions and values + # + # You can create your own rules to display columns (e.g., you need to show 'Yes' if some boolean # column is true, and 'No' if it is false). For that, you should add method with name - # modelname_columnname to SolutionGrid::GridHelper. You should create 'attributes' folder in - # app/helper and create file with filename modelname.rb. Let's implement example above: + # gridname_columnname to SolutionGrid::'GridName'. You should create 'attributes' folder in + # app/helper and create file with filename gridname.rb. Let's implement example above: # - # We have model Feed with boolean column 'restricted'. We should write in /app/helpers/attributes/feed.rb + # We have grid with name 'feeds' and boolean column 'restricted'. We should write in /app/helpers/attributes/feeds.rb # - # module SolutionsGrid::GridHelper - # def feed_restricted(record = nil) + # module SolutionsGrid::Feeds + # def feeds_restricted(record = nil) # value = record ? record.restricted : nil # { :key => "Restricted", :value => value ? "Yes" : "No" } # end # end # # Function should take one parameter (default is nil) and return hash with keys # <tt>:key</tt> - value will be used for the headers of the table # <tt>:value</tt> - value will be user for cells of the table # # If such method will not be founded, there are two ways to display values. # - # * If column looks like 'category_id', the plugin will try to display 'name' column of belonging table 'categories'. - # * If column doesn't look like 'something_id' or there is no column 'name' of belonging table, or there is no - # belonging table, the plugin just display value of this column. + # * If column looks like 'category_id', the plugin will try to display 'name' column of belonged table 'categories'. + # * If column looks like 'category_id_something', the plugin will try to display 'something' column of belonged table 'categories'. + # * If column doesn't look like 'something_id' the plugin just display value of this column. # - # You should add actions that you plan to use to module SolutionsGrid::GridHelper by similar way. + # You should add actions that you plan to use to module SolutionsGrid::Actions by similar way. # Example for 'edit' action, file 'app/helpers/attributes/actions.rb': # - # module SolutionsGrid::GridHelper + # module SolutionsGrid::Actions # def action_edit(record = nil) # if record # url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') # value = link_to("Edit", url) # else # value = nil # end # { :key => "Edit", :value => value } # end # end # # # == Sort and filter - # To sort and filter records of the grid you MUST pass options <tt>:filtered</tt> or <tt>:sorted</tt>. This parameters contain: - # * <tt>[:sorted][:by_column]</tt> - you should pass column you want to sort - # * <tt>[:sorted][:order]</tt> - you can pass order of sorting ('asc' or 'desc'). Default is 'asc'. - # * <tt>[:filtered][:by_string] - you can pass string, and columns you described in [:column][:filter][:by_string] will be filtered by this string. - # * <tt>[:filtered][:by_date] - you can pass date, and columns you described in [:column][:filter][:by_date] will be filtered by this date. - # * <tt>[:filtered][:by_span_date] - you can pass array [ start_date, end_date ], and columns you described in [:column][:filter][:by_span_date] will be filtered by overlapping this span. # - # == Examples of use the SolutionGrid + # To sort and filter records of the grid you *must* pass options <tt>:filtered</tt> or <tt>:sorted</tt>. + # + # == Examples of using the SolutionGrid + # # <i>in controller:</i> # # def index - # @feeds = Feed.find(:all) - # @table = Grid.new(@feeds, :name => "feeds") + # @table = Grid.new(:name => "feeds", :model => Feed, :columns => { :show => %{name body}}) # end # # <i>in view:</i> # # show_grid(@table) # - # It will display feeds with all columns defined in Feed model, except 'id', 'updated_at' - # and 'created_at'. There will be no actions and filterable columns, all columns will be sortable, - # but because you don't pass <tt>:sorted</tt> option, sort will not work. + # It will display feeds with 'name' and 'body'. There will be no actions and + # filterable columns, all columns will be sortable, but because you don't pass + # <tt>:sorted</tt> option, sort will not work. # # # <i>in controller:</i> # def index - # @feeds = Feed.find(:all) # @table = Grid.new( - # @feeds, { - # :columns => { - # :show => %w{name description}, - # :sort => %w{name} - # }, - # :sorted => session[:sort][:feed], - # :name => "feeds" - # } + # :columns => { + # :show => %w{name description}, + # :sort => %w{name} + # }, + # :sorted => session[:sort] ? session[:sort][:feeds] : nil, + # :name => "feeds", + # :model => Feed # ) # end # # <i>in view:</i> # show_grid(@table) # # It will display feeds with columns 'name' and 'description'. There will be no actions and - # filterable columns, 'name' column will be sortable, column to sort stores in session[:sort][:feed][:by_column]. + # filterable columns, 'name' column will be sortable, sort info is stored in + # session[:sort][:feeds][:by_column] (session[:sort][:feeds] hash can be automatically + # generated by grid_contoller of SolutionsGrid. Just add :sorted => session[:sort][:feeds], + # and all other work will be done by the SolutionsGrid plugin) # # # <i>in controller:</i> # def index - # @feeds = Feed.find(:all) # @table = Grid.new( - # @feeds, { - # :columns => { - # :show => %w{name description}, - # :filter => { - # :by_string => %w{name} - # }, - # }, - # :sorted => session[:sort][:feed], - # :filtered => session[:filter][:feed], - # :actions => %w{edit delete} - # } + # :columns => { + # :show => %w{name description}, + # :filter => { + # :by_string => %w{name} + # }, + # }, + # :name => "feeds", + # :model => Feed + # :sorted => session[:sort][:feeds], + # :filtered => session[:filter][:feeds], + # :actions => %w{edit delete} # ) # end # # <i>in view:</i> - # show_grid(@table) + # show_grid(@table, [ :text ]) # # It will display feeds with columns 'name' and 'description'. These columns will be sortable. # There will be actions 'edit' and 'delete' (but remember, you need action methods - # 'action_edit' and 'action_delete' in SolutionGrid::GridHelper in 'app/helpers/attributes/actions.rb'). + # 'action_edit' and 'action_delete' in SolutionGrid::Actions in 'app/helpers/attributes/actions.rb'). # There will be filterable column 'name', and it will be filtered by session[:filter][:feed][:by_string] value. + # (that will be automatically generated by SolutionsGrid's grid_controller def initialize(options = {}) @options = {} @options[:name] = options[:name].to_s if options[:name] @options[:model] = options[:model] @options[:modelname] = @options[:model].to_s.underscore @options[:actions] = Array(options[:actions]) || [] @options[:conditions] = options[:conditions] @options[:values] = options[:values] || {} @options[:include] = Array(options[:include]) || [] @options[:joins] = options[:joins] @options[:paginate] = options[:paginate] options[:columns] ||= {} @columns = {} @columns[:show] = Array(options[:columns][:show] || []) @columns[:sort] = options[:columns][:sort] || @columns[:show].dup @columns[:filter] = options[:columns][:filter] @options[:sorted] = options[:sorted] @options[:filtered] = options[:filtered] check_for_errors @records = get_records @view = {} end def get_belonged_model_and_column(column) belonged_column = column.match(/(.*)_id(.*)/) if belonged_column && !belonged_column[2].blank? column = belonged_column[2].gsub(/^(_)/, '') [ belonged_column[1].camelize.constantize, column ] elsif belonged_column && !belonged_column[1].blank? [ belonged_column[1].camelize.constantize, 'name' ] else [ nil, nil ] end end def get_association(belonged_model) belonged_model.to_s.underscore.to_sym end def get_date(params) return nil if !params || params[:year].blank? params[:month] = params[:month].blank? ? 1 : params[:month] params[:day] = params[:day].blank? ? 1 : params[:day] conditions = [ params[:year].to_i, params[:month].to_i, params[:day].to_i ] conditions += [ params[:hour].to_i, params[:minute].to_i ] if params[:hour] DateTime.civil(*conditions) end private def get_records @include ||= [] method = @options[:paginate] ? :paginate : :find conditions = {} conditions.merge!(filter(@options[:filtered])) conditions.merge!(sort(@options[:sorted])) include_belonged_models_from_show_columns @include += @options[:include] conditions[:include] = @include conditions[:joins] = @options[:joins] if @options[:joins] if @options[:paginate] method = :paginate conditions.merge!(@options[:paginate]) else method = :find end @options[:model].send(method, :all, conditions) end def sort(options) return {} unless options order = (options[:order] == 'asc') ? "ASC" : "DESC" table_with_column = get_correct_table_with_column(options[:by_column]) @order = "#{table_with_column} #{order}" { :order => @order } end def filter(options) @conditions ||= [] @values ||= {} if options filter_by_string filter_by_date end @conditions << "(" + @options[:conditions] + ")" if @options[:conditions] @values.merge!(@options[:values]) @conditions = @conditions.join(" AND ") { :conditions => [ @conditions, @values ] } end def filter_by_string string = @options[:filtered] ? @options[:filtered][:by_string] : nil return if string.blank? conditions = [] Array(@columns[:filter][:by_string]).each do |column| table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} LIKE :#{column}" @values[column.to_sym] = "%#{string}%" end @conditions << "(" + conditions.join(" OR ") + ")" end def filter_by_date from_date = @options[:filtered][:from_date] from_date = get_date(from_date) to_date = @options[:filtered][:to_date] to_date = get_date(to_date) return unless from_date || to_date date_conditions = [] Array(@columns[:filter][:by_date]).each do |column| conditions = [] table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} >= :#{column}_from_date" if from_date conditions << "#{table_with_column} <= :#{column}_to_date" if to_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{column}_from_date".to_sym] = from_date if from_date @values["#{column}_to_date".to_sym] = to_date if to_date end Array(@columns[:filter][:by_span_date]).each do |columns| conditions = [] table_with_column_from = get_correct_table_with_column(columns[0]) table_with_column_to = get_correct_table_with_column(columns[1]) conditions << "#{table_with_column_from} <= :#{columns[0]}_to_date" if to_date conditions << "#{table_with_column_to} >= :#{columns[1]}_from_date" if from_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{columns[0]}_to_date".to_sym] = to_date if to_date @values["#{columns[1]}_from_date".to_sym] = from_date if from_date end @conditions << date_conditions.join(" OR ") end def get_correct_table_with_column(column) belonged_model, belonged_column = get_belonged_model_and_column(column) if belonged_model by_column = ActiveRecord::Base.connection.quote_column_name(belonged_column) association = get_association(belonged_model) @include << association unless @include.include?(association) return "#{belonged_model.table_name}.#{by_column}" else by_column = ActiveRecord::Base.connection.quote_column_name(column) return "#{@options[:model].table_name}.#{by_column}" end end def include_belonged_models_from_show_columns Array(@columns[:show]).each do |column| get_correct_table_with_column(column) end end end diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index f8f342b..d6882e8 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,143 +1,151 @@ module SolutionsGrid module GridHelper + # This helper shows generated grid. It takes two arguments: + # * grid - grid's object that you created in controller + # * filter - array with filters (need for showing filter forms). It can contain: + # * :text - show form with filter by string + # * :date - show form with filter by date + # You should have partial 'grid/grid' in your app/views directory with + # template of the grid. You can get example of this grid in + # files/app/views/grid/_grid.html.haml or .html.erb def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? associated_record.send(belonged_column) : "" else record.send(column) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end # def add_select_tags(grid) # prefix = set_name_prefix(grid) # type = grid.options[:type_of_date_filtering] # klass = (type == :datetime) ? DateTime : type.to_s.camelize.constantize # output = "<label for=\"date_filter\">#{klass.to_s} Filter:</label><br />" # now = klass.today rescue klass.now # # from_date = grid.convert_to_date(grid.options[:filtered][:from_date], type) rescue now # to_date = grid.convert_to_date(grid.options[:filtered][:to_date], type) rescue now # helper_name = "select_#{type}".to_sym # # output += send(helper_name, from_date, :prefix => "#{prefix}from_date") + "<br />" # output += send(helper_name, to_date, :prefix => "#{prefix}to_date") + "<br />" # output # end # # def set_name_prefix(grid) # grid.options[:name] + "_" # end end end
astashov/solutions_grid
1ebabc34730fadf24e0e1c939e10541e7b50af28
Added /files - examples of configs for the plugin
diff --git a/files/app/attributes/actions.rb b/files/app/attributes/actions.rb new file mode 100644 index 0000000..606b840 --- /dev/null +++ b/files/app/attributes/actions.rb @@ -0,0 +1,36 @@ +module SolutionsGrid::Actions + + def action_edit(record = nil) + if record + url = generate_url(record.class, "edit", record) + value = link_to("Edit", url) + else + value = nil + end + { :key => "Edit", :value => value } + end + + + def action_destroy(record = nil) + if record + url = generate_url(record.class, "confirm_destroy", record) + value = link_to("Delete", url) + else + value = nil + end + { :key => "Delete", :value => value } + end + + + def action_restrict(record = nil) + if record + url = generate_url(record.class, "restrict", record) + value = link_to(record.restricted? ? "Unrestrict" : "Restrict", url) + else + value = nil + end + { :key => "Restrict", :value => value } + end + + +end diff --git a/files/app/attributes/feeds.rb b/files/app/attributes/feeds.rb new file mode 100644 index 0000000..7095af4 --- /dev/null +++ b/files/app/attributes/feeds.rb @@ -0,0 +1,13 @@ +module SolutionsGrid::Feeds + + def feeds_restricted(record = nil) + value = record ? record.restricted : nil + { :key => "Restricted", :value => value ? "Yes" : "No" } + end + + def feeds_name(record = nil) + value = record ? link_to(record.name, feed_path(record)) : "" + { :key => "Name", :value => value } + end + +end diff --git a/files/app/views/grid/_filter.html.erb b/files/app/views/grid/_filter.html.erb new file mode 100644 index 0000000..7d38439 --- /dev/null +++ b/files/app/views/grid/_filter.html.erb @@ -0,0 +1,23 @@ +<% form_tag filter_url(:grid_name => grid.options[:name]), :method => :get, :id => "#{grid.options[:name]}_filter", :class => "grid_filter" do -%> + <%= hidden_field_tag 'grid_name', grid.options[:name], :class => "grid_name" %> + <% if filter.include?(:date) -%> + <div class="date_filter"> + <div class="date_from"> + <label for="<%= grid.options[:name] + "_date_filter" %>">From:</label> + <%= place_date(grid, :from_date, session[:filter]) %> + </div> + <div class="date_to"> + <label for="<%= grid.options[:name] + "_date_filter" %>">To:</label> + <%= place_date(grid, :to_date, session[:filter]) %> + </div> + <% end -%> + <% if filter.include?(:text) -%> + <div class="text_filter"> + <label for="<%= grid.options[:name] + "_string_filter" %>">Text Filter:</label> + <%= text_field_tag "#{grid.options[:name]}_string_filter", grid.options[:filtered] ? grid.options[:filtered][:by_string] : '', :size => 20, :maxlength => 200 %> + </div> + <% end -%> + <%= submit_tag 'Filter', :class => "filter_button" %> + <%= submit_tag 'Clear' %> +<% end -%> +<div id="<%= grid.options[:name] + "_filter_indicator" %>"><%= grid.options[:filtered] ? 'Filtered' : '' %></div> diff --git a/files/app/views/grid/_filter.html.haml b/files/app/views/grid/_filter.html.haml new file mode 100644 index 0000000..cb8c1b3 --- /dev/null +++ b/files/app/views/grid/_filter.html.haml @@ -0,0 +1,17 @@ +- form_tag filter_url(:grid_name => grid.options[:name]), :method => :get, :id => "#{grid.options[:name]}_filter", :class => "grid_filter" do + = hidden_field_tag 'grid_name', grid.options[:name], :class => "grid_name" + - if filter.include?(:date) + .date_filter + .date_from + %label{ :for => "#{grid.options[:name]}_date_filter" } From: + = place_date(grid, :from_date, session[:filter]) + .date_to + %label{ :for => "#{grid.options[:name]}_date_filter" } To: + = place_date(grid, :to_date, session[:filter]) + - if filter.include?(:text) + .text_filter + %label{ :for => "#{grid.options[:name]}_string_filter" } Text Filter: + = text_field_tag "#{grid.options[:name]}_string_filter", grid.options[:filtered] ? grid.options[:filtered][:by_string] : '', :size => 20, :maxlength => 200 + = submit_tag 'Filter', :class => "filter_button" + = submit_tag 'Clear' +%div{ :id => "#{grid.options[:name]}_filter_indicator" }= grid.options[:filtered] ? 'Filtered' : '' diff --git a/files/app/views/grid/_grid.html.erb b/files/app/views/grid/_grid.html.erb new file mode 100644 index 0000000..a53917e --- /dev/null +++ b/files/app/views/grid/_grid.html.erb @@ -0,0 +1,6 @@ +<div id="<%= grid.options[:name] + "_spinner" %>"></div> +<div id="<%= grid.options[:name] + "_grid" %>"> + <%= render :partial => 'grid/filter', :locals => { :grid => grid, :filter => filter } unless filter.empty? %> + <%= render :partial => 'grid/table', :locals => { :grid => grid } %> + <%= grid.view[:paginate] %> +</div> diff --git a/files/app/views/grid/_grid.html.haml b/files/app/views/grid/_grid.html.haml new file mode 100644 index 0000000..8f24cfd --- /dev/null +++ b/files/app/views/grid/_grid.html.haml @@ -0,0 +1,5 @@ +%div{ :id => grid.options[:name] + "_spinner" } +%div{ :id => grid.options[:name] + "_grid" } + = render :partial => 'grid/filter', :locals => { :grid => grid, :filter => filter } unless filter.empty? + = render :partial => 'grid/table', :locals => { :grid => grid } + = grid.view[:paginate] diff --git a/files/app/views/grid/_table.html.erb b/files/app/views/grid/_table.html.erb new file mode 100644 index 0000000..9c1fe61 --- /dev/null +++ b/files/app/views/grid/_table.html.erb @@ -0,0 +1,14 @@ +<table class="grid"> + <tr class="header"> + <% grid.view[:headers].each do |header| -%> + <th><%= header %></th> + <% end -%> + </tr> + <% grid.view[:records].each do |record| -%> + <tr> + <% record.each do |value| -%> + <td><%= value %></td> + <% end -%> + </tr> + <% end -%> +</table> diff --git a/files/app/views/grid/_table.html.haml b/files/app/views/grid/_table.html.haml new file mode 100644 index 0000000..4176cb4 --- /dev/null +++ b/files/app/views/grid/_table.html.haml @@ -0,0 +1,8 @@ +%table.grid + %tr.header + - grid.view[:headers].each do |header| + %th= header + - grid.view[:records].each do |record| + %tr + - record.each do |value| + %td= value \ No newline at end of file diff --git a/files/public/javascripts/solutions_grid.js b/files/public/javascripts/solutions_grid.js new file mode 100644 index 0000000..542d394 --- /dev/null +++ b/files/public/javascripts/solutions_grid.js @@ -0,0 +1,75 @@ +/** + * Solution Grid JavaScript module for AJAXed pagination, sorting and filtering. + * Require jQuery library for correct working. + */ + +jQuery(document).ready(function($) { + + $('.grid_pagination a').livequery('click', function() { return solutionsGrid.paginate(this); }); + $('.filter_button').livequery('click', function() { return solutionsGrid.filter(this); }); + $('.sorted').livequery('click', function() { return solutionsGrid.sort(this); }) + +}); + +(function() { + + window.solutionsGrid = { + + paginate: function(that) { + var name = $(that).parent().attr('id').match(/(.*)_grid_pagination/)[1]; + replace_grid_by_ajax(name, that); + return false; + }, + + sort: function(that) { + // parents: a -> th -> tr -> tbody -> table -> div + var name = jQuery(that).parent().parent().parent().parent().parent().attr('id').match(/(.*)_grid/)[1]; + replace_grid_by_ajax(name, that); + return false; + }, + + filter: function(that) { + var form = that.form; + var grid_name_element = jQuery('.grid_name', form); + var name = grid_name_element.val(); + create_spinner(name); + var data = jQuery(form).serialize(); + var url = form.action + '.js?' + data; + load_grid(name, url); + return false; + } + + }; + + function replace_grid_by_ajax(name, that) { + create_spinner(name); + var parts_of_url = separate_url_from_params(that.href); + var url = parts_of_url[0] + ".js" + ((parts_of_url.length > 1) ? ("?" + parts_of_url[1]) : ""); + load_grid(name, url); + }; + + function create_spinner(name) { + jQuery('#' + name + '_spinner').append("<span class='spinner_wrapper'><img src='/images/spinner.gif' " + + "alt='' title='spinner' /> Loading...</span>"); + }; + + function destroy_spinners() { + jQuery('.spinner_wrapper').remove(); + }; + + function separate_url_from_params(url) { + var separated_url = url.match(/(.*)\/?\?(.*)/); + if(separated_url) { + separated_url[1] = separated_url[1].replace(/(.js|.xml|.html|.htm)/i, "") + return [separated_url[1], separated_url[2]]; + } else { + return [url]; + } + }; + + function load_grid(name, url) { + jQuery('#' + name + '_grid').load(url, function() { + destroy_spinners(); + }); + }; +})(); \ No newline at end of file diff --git a/lib/solutions_grid/controllers/grid_controller.rb b/lib/solutions_grid/controllers/grid_controller.rb index 8eb61d5..fc614c3 100644 --- a/lib/solutions_grid/controllers/grid_controller.rb +++ b/lib/solutions_grid/controllers/grid_controller.rb @@ -1,93 +1,82 @@ class GridController < ApplicationController def sort raise "You don't specify column to sort" unless params[:column] name = params[:grid_name].to_sym session[:sort] ||= {} controller = params[:controller].to_sym session[:sort][name] ||= {} # If we sorted records by this column before, then just change sort order if session[:sort][name][:by_column] && session[:sort][name][:by_column] == params[:column] previous_order = session[:sort][name][:order] session[:sort][name][:order] = (previous_order == 'asc') ? 'desc' : 'asc' else session[:sort][name][:order] = 'asc' session[:sort][name][:by_column] = params[:column] end flash[:notice] = "Data was sorted by #{CGI.escapeHTML(params[:column]).humanize}" respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end def filter name = params[:grid_name].to_sym session[:filter] ||= {} session[:filter][name] ||= {} if params[:commit] == 'Clear' session[:filter][name] = nil flash[:notice] = "Filter was cleared" else from_date = params[(name.to_s + '_from_date').to_sym] to_date = params[(name.to_s + '_to_date').to_sym] by_string = params[(name.to_s + '_string_filter').to_sym] || "" session[:filter][name][:from_date] = from_date session[:filter][name][:to_date] = to_date session[:filter][name][:by_string] = by_string flash[:notice] = "Data was filtered by #{CGI.escapeHTML(by_string).humanize}" end respond_to do |format| format.html do request.env["HTTP_REFERER"] ||= root_url redirect_to :back end format.js do controller = session[:grid][name][:controller] action = session[:grid][name][:action] redirect_to url_for(:controller => controller, :action => action, :format => 'js', :grid => name) end end rescue => msg error_handling(msg) end private - - def grid_parameters(page = nil) - { - :columns => { :filter => {:by_string => [], :by_date => %w{date}}}, - :sorted => session[:sort] ? session[:sort][:grid_example] : nil, - :filtered => session[:filter] ? session[:filter][:grid_example] : nil, - :paginate => { :enabled => true, :page => page, :per_page => 20 }, - :name => 'grid_example', - :type_of_date_filtering => :date - } - end - + def error_handling(msg) msg = msg.to_s[0..1000] + "..." if msg.to_s.length > 1000 flash[:error] = CGI.escapeHTML(msg.to_s) request.env["HTTP_REFERER"] ||= root_url redirect_to :back end -end \ No newline at end of file +end diff --git a/lib/solutions_grid/grid.rb b/lib/solutions_grid/grid.rb index 4188a6b..e894f13 100644 --- a/lib/solutions_grid/grid.rb +++ b/lib/solutions_grid/grid.rb @@ -1,346 +1,345 @@ -# Main class of the SolutionGrid plugin. It stores array of records (records can be -# ActiveRecord objects or simple hashes). It can execute different operations with +# Main class of the SolutionGrid plugin. It stores array of records (ActiveRecord +# objects or simple hashes). It can construct SQL query with different operations with # these records, such as sorting and filtering. With help of GridHelper it can # show these records as table with sortable headers, show filters. class Grid include SolutionsGrid::ErrorsHandling attr_accessor :view attr_reader :records, :options, :columns, :conditions, :values, :include, :order -# include SolutionsGrid::GridHelper -# include SolutionsGrid::Sort -# include SolutionsGrid::Filter - # To initialize grid, you should pass +records+ and +options+ as parameters. - # +Records+ can be ActiveRecord objects or just simple hashes. +Options+ change - # default options, it is not required parameter. - # + # To initialize grid, you should pass and +options+ as parameter. # # == Options - # * <tt>:name</tt> - set name if there are more than one grid on the page. It's <b>required</b> parameter. + # + # === Required + # + # These options you *must* to set + # * <tt>:name</tt> - set name of the grid. This parameter will be used for storing + # sorted and filtered info if there are more than one grid on the page. # * <tt>:model</tt> - set model. It will be used for constructing column names, # if columns is not specified obviously and there are no records # specified for displaying. # * <tt>:columns</tt> - sets columns of records to show, filter and sort. Pass columns as arrays. # * -> <tt>[:columns][:show]</tt> - pass columns you need to show (as array, do you remember? :)) # * -> <tt>[:columns][:sort]</tt> - pass columns you need to allow sorting. # * -> <tt>[:columns][:filter][:by_string]</tt> - pass columns you need to allow filtering by string. # * -> <tt>[:columns][:filter][:by_date]</tt> - pass columns you need to allow filtering by date. # * -> <tt>[:columns][:filter][:by_span_date]</tt> - pass columns you need to allow filtering by span of date. # You should pass columns as array of arrays # (format of arrays - [ start_date_column, end_date_column ]) # * <tt>:filter_path</tt> - set path to send filter requests. This path should lead to action, # that write filter to session. You should pass hash with keys: # <tt>:controller</tt> - the controller that contains the sort action, # <tt>:action</tt> # See details below. # * <tt>:sort_path</tt> - set path to send sort requests. This path should lead to action, # that write sort column to session. See details below. Syntax is similar to <tt>:filter_path</tt> # * <tt>:actions</tt> - pass necessary actions (such as 'edit', 'destroy', 'duplicate'). Details about actions see below. # * <tt>:filtered</tt> - pass hash with parameters: # * -> <tt>[:filtered][:by_string]</tt> - if you pass string, all 'filtered by string' columns will be filtered by this string # * -> <tt>[:filtered][:by_date]</tt> - if you pass date (in Date or DateTime format), all # 'filtered by date' columns will be filtered by this date # * -> <tt>[:filtered][:by_span_date]</tt> - if you pass array of 2 dates (start date and end date) # (in Date or DateTime format), all 'filtered by span of date' # columns will be filtered by this span # * <tt>:type_of_date_filtering</tt> - show filter form with date or datetime select boxes. If you display Hashes, # it will show Date by default. If you display ActiveRecord objects, # there will try to decide about select boxed automatically. # You can pass Date or DateTime parameters. # # # == Default values of the options # * <tt>[:columns][:show]</tt> - all columns of the table, except 'id', 'updated_at', 'created_at'. # * <tt>[:columns][:sort]</tt> - default is equal [:columns][:show] # * <tt>[:columns][:filter][:by_string]</tt> - default is equal [:columns][:show] # * <tt>[:columns][:filter][:by_date]</tt> - default is empty array # * <tt>[:columns][:filter][:by_span_date]</tt> - default is empty array # * <tt>[:actions]</tt> - default is empty array # * <tt>[:filtered]</tt> - default is empty hash # * <tt>[:sorted]</tt> - default is empty hash # # # == About custom display of actions and values # You can create your own rules to display columns (i.e., you need to show 'Yes' if some boolean # column is true, and 'No' if it is false). For that, you should add method with name # modelname_columnname to SolutionGrid::GridHelper. You should create 'attributes' folder in # app/helper and create file with filename modelname.rb. Let's implement example above: # # We have model Feed with boolean column 'restricted'. We should write in /app/helpers/attributes/feed.rb # # module SolutionsGrid::GridHelper # def feed_restricted(record = nil) # value = record ? record.restricted : nil # { :key => "Restricted", :value => value ? "Yes" : "No" } # end # end # # Function should take one parameter (default is nil) and return hash with keys # <tt>:key</tt> - value will be used for the headers of the table # <tt>:value</tt> - value will be user for cells of the table # # If such method will not be founded, there are two ways to display values. # # * If column looks like 'category_id', the plugin will try to display 'name' column of belonging table 'categories'. # * If column doesn't look like 'something_id' or there is no column 'name' of belonging table, or there is no # belonging table, the plugin just display value of this column. # # You should add actions that you plan to use to module SolutionsGrid::GridHelper by similar way. # Example for 'edit' action, file 'app/helpers/attributes/actions.rb': # # module SolutionsGrid::GridHelper # def action_edit(record = nil) # if record # url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') # value = link_to("Edit", url) # else # value = nil # end # { :key => "Edit", :value => value } # end # end # # # == Sort and filter # To sort and filter records of the grid you MUST pass options <tt>:filtered</tt> or <tt>:sorted</tt>. This parameters contain: # * <tt>[:sorted][:by_column]</tt> - you should pass column you want to sort # * <tt>[:sorted][:order]</tt> - you can pass order of sorting ('asc' or 'desc'). Default is 'asc'. # * <tt>[:filtered][:by_string] - you can pass string, and columns you described in [:column][:filter][:by_string] will be filtered by this string. # * <tt>[:filtered][:by_date] - you can pass date, and columns you described in [:column][:filter][:by_date] will be filtered by this date. # * <tt>[:filtered][:by_span_date] - you can pass array [ start_date, end_date ], and columns you described in [:column][:filter][:by_span_date] will be filtered by overlapping this span. # # == Examples of use the SolutionGrid # <i>in controller:</i> # # def index # @feeds = Feed.find(:all) # @table = Grid.new(@feeds, :name => "feeds") # end # # <i>in view:</i> # # show_grid(@table) # # It will display feeds with all columns defined in Feed model, except 'id', 'updated_at' # and 'created_at'. There will be no actions and filterable columns, all columns will be sortable, # but because you don't pass <tt>:sorted</tt> option, sort will not work. # # # <i>in controller:</i> # def index # @feeds = Feed.find(:all) # @table = Grid.new( # @feeds, { # :columns => { # :show => %w{name description}, # :sort => %w{name} # }, # :sorted => session[:sort][:feed], # :name => "feeds" # } # ) # end # # <i>in view:</i> # show_grid(@table) # # It will display feeds with columns 'name' and 'description'. There will be no actions and # filterable columns, 'name' column will be sortable, column to sort stores in session[:sort][:feed][:by_column]. # # # <i>in controller:</i> # def index # @feeds = Feed.find(:all) # @table = Grid.new( # @feeds, { # :columns => { # :show => %w{name description}, # :filter => { # :by_string => %w{name} # }, # }, # :sorted => session[:sort][:feed], # :filtered => session[:filter][:feed], # :actions => %w{edit delete} # } # ) # end # # <i>in view:</i> # show_grid(@table) # # It will display feeds with columns 'name' and 'description'. These columns will be sortable. # There will be actions 'edit' and 'delete' (but remember, you need action methods # 'action_edit' and 'action_delete' in SolutionGrid::GridHelper in 'app/helpers/attributes/actions.rb'). # There will be filterable column 'name', and it will be filtered by session[:filter][:feed][:by_string] value. def initialize(options = {}) @options = {} @options[:name] = options[:name].to_s if options[:name] @options[:model] = options[:model] @options[:modelname] = @options[:model].to_s.underscore @options[:actions] = Array(options[:actions]) || [] @options[:conditions] = options[:conditions] @options[:values] = options[:values] || {} @options[:include] = Array(options[:include]) || [] @options[:joins] = options[:joins] @options[:paginate] = options[:paginate] options[:columns] ||= {} @columns = {} @columns[:show] = Array(options[:columns][:show] || []) @columns[:sort] = options[:columns][:sort] || @columns[:show].dup @columns[:filter] = options[:columns][:filter] @options[:sorted] = options[:sorted] @options[:filtered] = options[:filtered] check_for_errors @records = get_records @view = {} end def get_belonged_model_and_column(column) belonged_column = column.match(/(.*)_id(.*)/) if belonged_column && !belonged_column[2].blank? column = belonged_column[2].gsub(/^(_)/, '') [ belonged_column[1].camelize.constantize, column ] elsif belonged_column && !belonged_column[1].blank? [ belonged_column[1].camelize.constantize, 'name' ] else [ nil, nil ] end end def get_association(belonged_model) belonged_model.to_s.underscore.to_sym end def get_date(params) return nil if !params || params[:year].blank? params[:month] = params[:month].blank? ? 1 : params[:month] params[:day] = params[:day].blank? ? 1 : params[:day] conditions = [ params[:year].to_i, params[:month].to_i, params[:day].to_i ] conditions += [ params[:hour].to_i, params[:minute].to_i ] if params[:hour] DateTime.civil(*conditions) end private def get_records @include ||= [] method = @options[:paginate] ? :paginate : :find conditions = {} conditions.merge!(filter(@options[:filtered])) conditions.merge!(sort(@options[:sorted])) include_belonged_models_from_show_columns @include += @options[:include] conditions[:include] = @include conditions[:joins] = @options[:joins] if @options[:joins] if @options[:paginate] method = :paginate conditions.merge!(@options[:paginate]) else method = :find end @options[:model].send(method, :all, conditions) end def sort(options) return {} unless options order = (options[:order] == 'asc') ? "ASC" : "DESC" table_with_column = get_correct_table_with_column(options[:by_column]) @order = "#{table_with_column} #{order}" { :order => @order } end def filter(options) @conditions ||= [] @values ||= {} if options filter_by_string filter_by_date end @conditions << "(" + @options[:conditions] + ")" if @options[:conditions] @values.merge!(@options[:values]) @conditions = @conditions.join(" AND ") { :conditions => [ @conditions, @values ] } end def filter_by_string string = @options[:filtered] ? @options[:filtered][:by_string] : nil return if string.blank? conditions = [] Array(@columns[:filter][:by_string]).each do |column| table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} LIKE :#{column}" @values[column.to_sym] = "%#{string}%" end @conditions << "(" + conditions.join(" OR ") + ")" end def filter_by_date from_date = @options[:filtered][:from_date] from_date = get_date(from_date) to_date = @options[:filtered][:to_date] to_date = get_date(to_date) return unless from_date || to_date date_conditions = [] Array(@columns[:filter][:by_date]).each do |column| conditions = [] table_with_column = get_correct_table_with_column(column) conditions << "#{table_with_column} >= :#{column}_from_date" if from_date conditions << "#{table_with_column} <= :#{column}_to_date" if to_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{column}_from_date".to_sym] = from_date if from_date @values["#{column}_to_date".to_sym] = to_date if to_date end Array(@columns[:filter][:by_span_date]).each do |columns| conditions = [] table_with_column_from = get_correct_table_with_column(columns[0]) table_with_column_to = get_correct_table_with_column(columns[1]) conditions << "#{table_with_column_from} <= :#{columns[0]}_to_date" if to_date conditions << "#{table_with_column_to} >= :#{columns[1]}_from_date" if from_date date_conditions << "(" + conditions.join(" AND ") + ")" @values["#{columns[0]}_to_date".to_sym] = to_date if to_date @values["#{columns[1]}_from_date".to_sym] = from_date if from_date end @conditions << date_conditions.join(" OR ") end def get_correct_table_with_column(column) belonged_model, belonged_column = get_belonged_model_and_column(column) if belonged_model by_column = ActiveRecord::Base.connection.quote_column_name(belonged_column) association = get_association(belonged_model) @include << association unless @include.include?(association) return "#{belonged_model.table_name}.#{by_column}" else by_column = ActiveRecord::Base.connection.quote_column_name(column) return "#{@options[:model].table_name}.#{by_column}" end end def include_belonged_models_from_show_columns Array(@columns[:show]).each do |column| get_correct_table_with_column(column) end end -end \ No newline at end of file +end diff --git a/lib/solutions_grid/helpers/grid_helper.rb b/lib/solutions_grid/helpers/grid_helper.rb index 462f2c5..f8f342b 100644 --- a/lib/solutions_grid/helpers/grid_helper.rb +++ b/lib/solutions_grid/helpers/grid_helper.rb @@ -1,143 +1,143 @@ module SolutionsGrid module GridHelper def show_grid(grid, filter = []) session[:grid] ||= {} name = grid.options[:name].to_sym session[:grid][name] ||= {} session[:grid][name][:controller] = params[:controller] session[:grid][name][:action] = params[:action] helper_module_name = grid.options[:name].camelize.to_s model_helpers_module = "SolutionsGrid::#{helper_module_name}" if SolutionsGrid.const_defined?(helper_module_name) self.class.send(:include, model_helpers_module.constantize) end self.class.send(:include, SolutionsGrid::Actions) prepare_headers_of_values(grid) prepare_headers_of_actions(grid) prepare_values(grid) prepare_paginate(grid) - render :partial => 'grid/grid.html.haml', :locals => { :grid => grid, :filter => filter } + render :partial => 'grid/grid', :locals => { :grid => grid, :filter => filter } end private # Showing headers of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just humanized. def prepare_headers_of_values(grid) grid.view[:headers] ||= [] grid.columns[:show].each do |column| show_value = case when self.class.instance_methods.include?(grid.options[:name] + "_" + column) send(grid.options[:name] + "_" + column)[:key] when column =~ /_id/ column.gsub('_id', '').humanize else column.humanize end show_value = if grid.columns[:sort].include?(column) link_to(h(show_value), sort_url(:column => column, :grid_name => grid.options[:name]), :class => "sorted") else h(show_value) end if grid.options[:sorted] && grid.options[:sorted][:by_column] == column show_value += grid.options[:sorted][:order] == 'asc' ? " &#8595;" : " &#8593;" end grid.view[:headers] << show_value end end def prepare_headers_of_actions(grid) grid.view[:headers] ||= [] grid.options[:actions].each do |action| grid.view[:headers] << send("action_" + action)[:key] end end # Show contents of table, attributes is being taken from # /helpers/attributes/'something'.rb too or just escaped. def prepare_values(grid) grid.view[:records] ||= [] grid.records.each do |record| show_values = [] grid.columns[:show].each do |column| name = grid.options[:name] method = grid.options[:name] + "_" + column show_values << case when self.class.instance_methods.include?(method) send(grid.options[:name] + "_" + column, record)[:value] when column =~ /_id/ belonged_model, belonged_column = grid.get_belonged_model_and_column(column) association = grid.get_association(belonged_model) associated_record = record.send(association) associated_record.respond_to?(belonged_column) ? associated_record.send(belonged_column) : "" else record.send(column) end end grid.options[:actions].each do |action| show_values << send("action_" + action, record)[:value] end grid.view[:records] << show_values end end def prepare_paginate(grid) if grid.options[:paginate] additional_params = {:class => "grid_pagination", :id => "#{grid.options[:name]}_grid_pagination"} additional_params[:param_name] = "#{grid.options[:name]}_page" grid.view[:paginate] = will_paginate(grid.records, additional_params) else grid.view[:paginate] = "" end end def place_date(grid, type, filter) name = grid.options[:name] default_date = if filter && filter[name.to_sym] grid.get_date(filter[name.to_sym][type]) else nil end prefix = name + "_" + type.to_s select_date(default_date, :order => [:year, :month, :day], :prefix => prefix, :include_blank => true) end # def add_select_tags(grid) # prefix = set_name_prefix(grid) # type = grid.options[:type_of_date_filtering] # klass = (type == :datetime) ? DateTime : type.to_s.camelize.constantize # output = "<label for=\"date_filter\">#{klass.to_s} Filter:</label><br />" # now = klass.today rescue klass.now # # from_date = grid.convert_to_date(grid.options[:filtered][:from_date], type) rescue now # to_date = grid.convert_to_date(grid.options[:filtered][:to_date], type) rescue now # helper_name = "select_#{type}".to_sym # # output += send(helper_name, from_date, :prefix => "#{prefix}from_date") + "<br />" # output += send(helper_name, to_date, :prefix => "#{prefix}to_date") + "<br />" # output # end # # def set_name_prefix(grid) # grid.options[:name] + "_" # end end end
astashov/solutions_grid
9b22e28b0f3b0c4074aa16c45ab11a0a0e4d0c1a
Added possibility to use url_for() and h() in user-defined columns
diff --git a/lib/solutions_grid/column/column.rb b/lib/solutions_grid/column/column.rb index 5208ed4..6992f0c 100644 --- a/lib/solutions_grid/column/column.rb +++ b/lib/solutions_grid/column/column.rb @@ -1,110 +1,114 @@ require "solutions_grid/helpers/grid_helper.rb" class SolutionsGrid::Column - attr_reader :name, :modelname - attr_accessor :type + include ActionView::Helpers::UrlHelper + include ActionController::UrlWriter include SolutionsGrid::GridHelper + include ERB::Util + + attr_reader :name, :modelname + attr_accessor :type, :default_url_options def initialize(name, model, record = nil) @name = name.to_s @model = model @modelname = model.to_s.underscore @methodname = @modelname + "_" + @name @type = :string @example_of_record = record raise SolutionsGrid::ErrorsHandling::UnexistedColumn, "You try to specify unexisted column '#{self.name}'" unless does_column_exist? end def to_s @name end def change_type(type) @type = type end def convert_to_date(date) if date.is_a?(Date) || date.is_a?(Time) || date.is_a?(DateTime) return date elsif date.is_a?(Hash) case @type when :date return Date.civil(date['year'].to_i, date['month'].to_i, date['day'].to_i) when :datetime return DateTime.civil(date['year'].to_i, date['month'].to_i, date['day'].to_i, date['hour'].to_i, date['minute'].to_i) end else raise end rescue return nil end # Show header of the column. Header is calculated from the current column such way: # 1. At first, the plugin try to find helper method modelname_column (i.e., feed_name). # If the method exists, header value will be the <tt>:key</tt> of returned value. # 2. If the method doesn't exist, the plugin will check column name. If it has format 'something_id', # the plugin will try to find belonged table 'somethings' and display humanized classname of the model, belonged with table. # 3. If the table or its column 'name' doesn't exist, the plugin just display humanized name of the column def show_header(record = nil) if respond_to?(@methodname) value = send(@methodname, nil)[:key] elsif @methodname.match(/_id$/) && record belongs = @methodname.gsub(/(#{self.modelname}_|_id$)/, '') value = get_value_of_record(record, belongs).class.to_s.underscore.humanize rescue false value = self.name.humanize unless value end value ||= self.name.humanize end # Show value of the column. Value is calculated from the current column such way: # 1. At first, the plugin try to find helper method modelname_column (i.e., feed_name). # If the method exists, value will be the <tt>:value</tt> of returned value. # 2. If the method doesn't exist, the plugin will check column name. If it has format 'something_id', # the plugin will try to find belonged table 'somethings' and display 'somethings.name' value. # 3. If the table or its column 'name' doesn't exist, the plugin just display contents of the column. def show_value(record) record = record.stringify_keys if record.is_a? Hash if respond_to?(@methodname) value = send(@methodname, record)[:value] elsif @methodname.match(/_id$/) belongs = @methodname.gsub(/(#{self.modelname}_|_id$)/, '') value = get_value_of_record(record, belongs).name rescue false end value ||= get_value_of_record(record, self.name) end def self.drop_unsignificant_columns(columns) unsignificant_columns = %w{id updated_at created_at} if columns.is_a? Hash columns.delete_if { |column, values| unsignificant_columns.include?(column) } else columns.delete_if { |column| unsignificant_columns.include?(column) } end end def self.find(column_name, array) column = array.select {|c| c.name == column_name}.first raise SolutionsGrid::ErrorsHandling::UnexistedColumn, "There are no columns with name #{column_name} here" unless column column end end class Hash def stringify_keys record_with_stringified_keys = {} self.each do |key, value| record_with_stringified_keys[key.to_s] = value end record_with_stringified_keys end end \ No newline at end of file diff --git a/spec/helpers/grid_helper_spec.rb b/spec/helpers/grid_helper_spec.rb index a11cf9e..268de28 100644 --- a/spec/helpers/grid_helper_spec.rb +++ b/spec/helpers/grid_helper_spec.rb @@ -1,139 +1,149 @@ require File.dirname(__FILE__) + '/../spec_helper' describe SolutionsGrid::GridHelper do before do @category = mock_model(CategoryExample, :name => "somecategory") @feed = mock_model(FeedExample, :name => "somefeed", :category_id => @category.id, :category => @category, :restricted => false, :descriptions => "Desc") set_column_names_and_hashes(FeedExample, :string => %w{name category_id restricted description}) set_column_names_and_hashes(DateExample, :string => %w{description}, :date => %w{date}) set_column_names_and_hashes(SpanDateExample, :string => %w{description}, :datetime => %w{start_datetime end_datetime}) end it "should display usual columns of model" do grid = Grid.new(@feed, { :columns => {:show => %w{name}}, :name => 'feed'}) output = helper.show_grid(grid) output.should match(/table.*tr.*th.*Name.*td.*somefeed/m) end it "should display calculated columns of model" do grid = Grid.new(@feed, { :columns => {:show => %w{category_id}}, :name => 'feed'}) output = helper.show_grid(grid) output.should match(/table.*tr.*th.*Category example.*td.*somecategory/m) end it "should display user defined columns of model" do SolutionsGrid::GridHelper.class_eval do - define_method(:feed_example_restricted) do |model| - value = model ? model.restricted : nil - { :key => "Restricted", :value => value ? "Yes" : "No" } + define_method(:feed_example_name) do |record| + if record + url = url_for(:controller => record.class.to_s.underscore, :action => 'edit', :id => record.id, :only_path => true) + value = link_to(h(record.name), url) + else + value = nil + end + { :key => "Name", :value => value } end end - grid = Grid.new(@feed, { :columns => {:show => %w{restricted}}, :name => 'feed'}) + + grid = Grid.new(@feed, { :columns => {:show => %w{name category_id}}, :name => 'feed'}) output = helper.show_grid(grid) - output.should match(/table.*tr.*th.*Restricted.*td.*No/m) + output.should match(/table.*tr.*th.*Name.*Category example.*td.*<a href=\"\/feed_example\/edit\/\d+\">somefeed<\/a>/m) + + SolutionsGrid::GridHelper.class_eval do + remove_method(:feed_example_name) + end end it "should display columns with actions" do SolutionsGrid::GridHelper.class_eval do define_method(:action_edit) do |record| if record url = url_for(:controller => record.class.to_s.underscore.pluralize, :action => 'edit') value = link_to("Edit", url) else value = nil end { :key => "Edit", :value => value } end end grid = Grid.new(@feed, { :columns => {:show => %w{name category_id}}, - :actions => %w{edit delete duplicate}, :name => 'feed'}) + :actions => %w{edit}, :name => 'feed'}) output = helper.show_grid(grid) output.should match(/table.*tr.*th.*Name.*Category example.*Edit.*td.*Edit/m) end - + it "should display sorting up arrow (&#8595;) if sorted as 'asc'" do grid = Grid.new(@feed, { :columns => {:show => %w{name category_id restricted}}, :name => 'feed'}) grid.sort('name', 'asc') output = helper.show_grid(grid) output.should have_tag("a[href*=/grid/feed/sort_by/name]", "Name") output.should include_text("&#8595;") output.should have_tag("a[href*=/grid/feed/sort_by/category_id]", "Category example") end it "should display sorting down arrow (&#8593;) if sorted as 'desc'" do grid = Grid.new(@feed, { :columns => {:show => %w{name category_id restricted}}, :name => 'feed'}) grid.sort('name', 'desc') output = helper.show_grid(grid) output.should have_tag("a[href*=/grid/feed/sort_by/name]", "Name") output.should include_text("&#8593;") output.should have_tag("a[href*=/grid/feed/sort_by/category_id]", "Category example") end it "should display filter form" do grid = Grid.new(@feed, { :columns => {:show => %w{name category_id restricted}}, :filtered => { :by_string => 'some'}, :name => 'feed'}) output = helper.show_filter(grid) output.should match(/form.*\/grid\/feed\/filter.*<input.*value=\"some\".*.*type=\"submit\" value=\"Filter\".*type=\"submit\" value=\"Clear\"/m) end it "should display filter form with date by default" do date = mock_model(DateExample, :date => Date.today, :description => "Desc") grid = Grid.new(date, { :columns => {:show => %w{date description}}, :name => 'date'}) output = helper.show_filter(grid, true) output.should match(/form.*Date Filter.*from_date_year.*from_date_month.*from_date_day.*Filter"/m) end it "should display filter form with datetime" do date = mock_model(DateExample, :date => Date.today, :description => "Desc") grid = Grid.new(date, { :columns => {:show => %w{date description}}, :type_of_date_filtering => :datetime, :name => 'date' }) output = helper.show_filter(grid, true) output.should match(/form.*DateTime Filter/m) end it "should display filter form with date" do DateExample.stub!(:column_names).and_return(%w{date description}) date = mock_model(DateExample, :date => Date.today, :description => "Desc") grid = Grid.new(date, { :columns => {:show => %w{date description}, :filter => {:by_date => %w{date}}}, :name => 'date'}) output = helper.show_filter(grid, true) output.should match(/form.*Date Filter.*from_date_year.*from_date_month.*from_date_day.*to_date_year.*to_date_month.*to_date_day.*Filter"/m) end it "should display filter form with datetime for span of dates" do SpanDateExample.stub!(:column_names).and_return(%w{start_datetime end_datetime description}) span_date = mock_model(SpanDateExample, :start_datetime => DateTime.now, :end_datetime => DateTime.now + 2.days, :description => "Desc") grid = Grid.new(span_date, { :columns => {:show => %w{start_datetime start_datetime description}, :filter => { :by_span_date => [%w{start_datetime start_datetime}]}}, :name => 'span_date'}) output = helper.show_filter(grid, true) output.should match(/form.*DateTime Filter.*from_date_year.*from_date_minute.*to_date_year.*to_date_minute.*Filter"/m) end it "should display table from hash" do dates = [] 3.times do |i| dates << { :date => Date.civil(2008, 8, 5) + i.days, :description => "some description" } end grid = Grid.new(dates, :name => 'date') output = helper.show_grid(grid) output.should match(/table.*tr.*th.*Date.*th.*Description.*td.*2008-08-05.*td.*some description/m) end it "should display will_paginate helper after the table if WillPaginate is installed" do if Object.const_defined? "WillPaginate" dates = [:date => 'asdf'] grid = Grid.new(dates, :paginate => { :enabled => true, :per_page => 5, :page => 2 }, :name => 'date') helper.should_receive(:will_paginate).and_return("There will 'will_paginate' work") output = helper.show_grid(grid) end end it "should not display will_paginate if we disable 'will_paginate'" do if Object.const_defined? "WillPaginate" dates = [:date => 'asdf'] grid = Grid.new(dates, :paginate => { :enabled => false }, :name => 'date') helper.should_not_receive(:will_paginate) output = helper.show_grid(grid) end end end \ No newline at end of file