repo
string | commit
string | message
string | diff
string |
---|---|---|---|
Perl-Email-Project/Email-Folder-IMAP
|
be50e2bcabaa84baf1d4dad9899b02e1390642ae
|
v1.105
|
diff --git a/Changes b/Changes
index cf68b73..16ff580 100644
--- a/Changes
+++ b/Changes
@@ -1,24 +1,26 @@
{{$NEXT}}
+
+1.105 2014-04-04 22:27:01-04:00 America/New_York
- require URI::imap
1.104 2014-01-03 19:41:26 America/New_York
fix VERSION mismatch error
1.103 2013-08-05 18:18:20 America/New_York
repackage to update repo, bugtracker
1.102 2007-04-01
avoid use of package variables for configuration; seriously, guys
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
|
Perl-Email-Project/Email-Folder-IMAP
|
7658e15801897461cd6706f75adf5361fd3f09ba
|
require URI::imap
|
diff --git a/Changes b/Changes
index de27334..cf68b73 100644
--- a/Changes
+++ b/Changes
@@ -1,23 +1,24 @@
{{$NEXT}}
+ - require URI::imap
1.104 2014-01-03 19:41:26 America/New_York
fix VERSION mismatch error
1.103 2013-08-05 18:18:20 America/New_York
repackage to update repo, bugtracker
1.102 2007-04-01
avoid use of package variables for configuration; seriously, guys
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
diff --git a/dist.ini b/dist.ini
index dee6611..cc1d47d 100644
--- a/dist.ini
+++ b/dist.ini
@@ -1,10 +1,11 @@
name = Email-Folder-IMAP
author = Casey West <[email protected]>
license = Perl_5
copyright_holder = Casey West <[email protected]>
copyright_year = 2004
[@RJBS]
[Prereqs]
Email::FolderType::Net = 0
Email::Folder::Reader = 0
+URI::imap = 0
|
Perl-Email-Project/Email-Folder-IMAP
|
47b177544b80cce8aade2de378af7e9521045944
|
v1.104
|
diff --git a/Changes b/Changes
index 88484d7..de27334 100644
--- a/Changes
+++ b/Changes
@@ -1,21 +1,23 @@
{{$NEXT}}
+
+1.104 2014-01-03 19:41:26 America/New_York
fix VERSION mismatch error
1.103 2013-08-05 18:18:20 America/New_York
repackage to update repo, bugtracker
1.102 2007-04-01
avoid use of package variables for configuration; seriously, guys
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
|
Perl-Email-Project/Email-Folder-IMAP
|
4e100fab75cd94f32b545884baa5d15e7b59bbf2
|
prep next release
|
diff --git a/Changes b/Changes
index c98de00..88484d7 100644
--- a/Changes
+++ b/Changes
@@ -1,20 +1,21 @@
{{$NEXT}}
+ fix VERSION mismatch error
1.103 2013-08-05 18:18:20 America/New_York
repackage to update repo, bugtracker
1.102 2007-04-01
avoid use of package variables for configuration; seriously, guys
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index 125abeb..fe9c15e 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,101 +1,99 @@
use strict;
use warnings;
package Email::Folder::IMAP;
# ABSTRACT: Email::Folder Access to IMAP Folders
-our $VERSION = '1.102';
-
use parent qw[Email::Folder::Reader];
use Net::IMAP::Simple 0.95; # :port support
use URI;
sub _imap_class {
'Net::IMAP::Simple';
}
sub _uri {
my $self = shift;
return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
my $self = shift;
return $self->{_server} if $self->{_server};
my $uri = $self->_uri;
my $host = $uri->host_port;
my $server = $self->_imap_class->new($host);
my ($user, $pass) = @{$self}{qw[username password]};
($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
$server->login($user, $pass) if $user;
my $box = substr $uri->path, 1;
$server->select($box) if $box;
$self->{_next} = 1;
return $self->{_server} = $server;
}
sub next_message {
my $self = shift;
my $message = $self->_server->get($self->{_next});
if ($message) {
++$self->{_next};
return join '', @{$message};
}
$self->{_next} = 1;
return;
}
1;
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
imap://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
imap://user:[email protected]
Selecting the p5p list.
imap://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
|
Perl-Email-Project/Email-Folder-IMAP
|
2681ac63fa3847adaf098977ec6fd9cf997705fe
|
v1.103
|
diff --git a/Changes b/Changes
index b6f8d2e..c98de00 100644
--- a/Changes
+++ b/Changes
@@ -1,15 +1,20 @@
+{{$NEXT}}
+
+1.103 2013-08-05 18:18:20 America/New_York
+ repackage to update repo, bugtracker
+
1.102 2007-04-01
avoid use of package variables for configuration; seriously, guys
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
|
Perl-Email-Project/Email-Folder-IMAP
|
46da302e218c1e3d556877beb56185325e3db1b4
|
dzilify
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ec8a339
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.build
+Email-Folder-IMAP-*
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 05e86e0..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,378 +0,0 @@
-
-Terms of Perl itself
-
-a) the GNU General Public License as published by the Free
- Software Foundation; either version 1, or (at your option) any
- later version, or
-b) the "Artistic License"
-
-----------------------------------------------------------------------------
-
-The General Public License (GPL)
-Version 2, June 1991
-
-Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
-Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
-verbatim copies of this license document, but changing it is not allowed.
-
-Preamble
-
-The licenses for most software are designed to take away your freedom to share
-and change it. By contrast, the GNU General Public License is intended to
-guarantee your freedom to share and change free software--to make sure the
-software is free for all its users. This General Public License applies to most of
-the Free Software Foundation's software and to any other program whose
-authors commit to using it. (Some other Free Software Foundation software is
-covered by the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
-When we speak of free software, we are referring to freedom, not price. Our
-General Public Licenses are designed to make sure that you have the freedom
-to distribute copies of free software (and charge for this service if you wish), that
-you receive source code or can get it if you want it, that you can change the
-software or use pieces of it in new free programs; and that you know you can do
-these things.
-
-To protect your rights, we need to make restrictions that forbid anyone to deny
-you these rights or to ask you to surrender the rights. These restrictions
-translate to certain responsibilities for you if you distribute copies of the
-software, or if you modify it.
-
-For example, if you distribute copies of such a program, whether gratis or for a
-fee, you must give the recipients all the rights that you have. You must make
-sure that they, too, receive or can get the source code. And you must show
-them these terms so they know their rights.
-
-We protect your rights with two steps: (1) copyright the software, and (2) offer
-you this license which gives you legal permission to copy, distribute and/or
-modify the software.
-
-Also, for each author's protection and ours, we want to make certain that
-everyone understands that there is no warranty for this free software. If the
-software is modified by someone else and passed on, we want its recipients to
-know that what they have is not the original, so that any problems introduced by
-others will not reflect on the original authors' reputations.
-
-Finally, any free program is threatened constantly by software patents. We wish
-to avoid the danger that redistributors of a free program will individually obtain
-patent licenses, in effect making the program proprietary. To prevent this, we
-have made it clear that any patent must be licensed for everyone's free use or
-not licensed at all.
-
-The precise terms and conditions for copying, distribution and modification
-follow.
-
-GNU GENERAL PUBLIC LICENSE
-TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
-MODIFICATION
-
-0. This License applies to any program or other work which contains a notice
-placed by the copyright holder saying it may be distributed under the terms of
-this General Public License. The "Program", below, refers to any such program
-or work, and a "work based on the Program" means either the Program or any
-derivative work under copyright law: that is to say, a work containing the
-Program or a portion of it, either verbatim or with modifications and/or translated
-into another language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not covered by
-this License; they are outside its scope. The act of running the Program is not
-restricted, and the output from the Program is covered only if its contents
-constitute a work based on the Program (independent of having been made by
-running the Program). Whether that is true depends on what the Program does.
-
-1. You may copy and distribute verbatim copies of the Program's source code as
-you receive it, in any medium, provided that you conspicuously and appropriately
-publish on each copy an appropriate copyright notice and disclaimer of warranty;
-keep intact all the notices that refer to this License and to the absence of any
-warranty; and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and you may at
-your option offer warranty protection in exchange for a fee.
-
-2. You may modify your copy or copies of the Program or any portion of it, thus
-forming a work based on the Program, and copy and distribute such
-modifications or work under the terms of Section 1 above, provided that you also
-meet all of these conditions:
-
-a) You must cause the modified files to carry prominent notices stating that you
-changed the files and the date of any change.
-
-b) You must cause any work that you distribute or publish, that in whole or in
-part contains or is derived from the Program or any part thereof, to be licensed
-as a whole at no charge to all third parties under the terms of this License.
-
-c) If the modified program normally reads commands interactively when run, you
-must cause it, when started running for such interactive use in the most ordinary
-way, to print or display an announcement including an appropriate copyright
-notice and a notice that there is no warranty (or else, saying that you provide a
-warranty) and that users may redistribute the program under these conditions,
-and telling the user how to view a copy of this License. (Exception: if the
-Program itself is interactive but does not normally print such an announcement,
-your work based on the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If identifiable
-sections of that work are not derived from the Program, and can be reasonably
-considered independent and separate works in themselves, then this License,
-and its terms, do not apply to those sections when you distribute them as
-separate works. But when you distribute the same sections as part of a whole
-which is a work based on the Program, the distribution of the whole must be on
-the terms of this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest your rights to
-work written entirely by you; rather, the intent is to exercise the right to control
-the distribution of derivative or collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program with the
-Program (or with a work based on the Program) on a volume of a storage or
-distribution medium does not bring the other work under the scope of this
-License.
-
-3. You may copy and distribute the Program (or a work based on it, under
-Section 2) in object code or executable form under the terms of Sections 1 and 2
-above provided that you also do one of the following:
-
-a) Accompany it with the complete corresponding machine-readable source
-code, which must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange; or,
-
-b) Accompany it with a written offer, valid for at least three years, to give any
-third party, for a charge no more than your cost of physically performing source
-distribution, a complete machine-readable copy of the corresponding source
-code, to be distributed under the terms of Sections 1 and 2 above on a medium
-customarily used for software interchange; or,
-
-c) Accompany it with the information you received as to the offer to distribute
-corresponding source code. (This alternative is allowed only for noncommercial
-distribution and only if you received the program in object code or executable
-form with such an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for making
-modifications to it. For an executable work, complete source code means all the
-source code for all modules it contains, plus any associated interface definition
-files, plus the scripts used to control compilation and installation of the
-executable. However, as a special exception, the source code distributed need
-not include anything that is normally distributed (in either source or binary form)
-with the major components (compiler, kernel, and so on) of the operating system
-on which the executable runs, unless that component itself accompanies the
-executable.
-
-If distribution of executable or object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the source
-code from the same place counts as distribution of the source code, even though
-third parties are not compelled to copy the source along with the object code.
-
-4. You may not copy, modify, sublicense, or distribute the Program except as
-expressly provided under this License. Any attempt otherwise to copy, modify,
-sublicense or distribute the Program is void, and will automatically terminate
-your rights under this License. However, parties who have received copies, or
-rights, from you under this License will not have their licenses terminated so long
-as such parties remain in full compliance.
-
-5. You are not required to accept this License, since you have not signed it.
-However, nothing else grants you permission to modify or distribute the Program
-or its derivative works. These actions are prohibited by law if you do not accept
-this License. Therefore, by modifying or distributing the Program (or any work
-based on the Program), you indicate your acceptance of this License to do so,
-and all its terms and conditions for copying, distributing or modifying the
-Program or works based on it.
-
-6. Each time you redistribute the Program (or any work based on the Program),
-the recipient automatically receives a license from the original licensor to copy,
-distribute or modify the Program subject to these terms and conditions. You
-may not impose any further restrictions on the recipients' exercise of the rights
-granted herein. You are not responsible for enforcing compliance by third parties
-to this License.
-
-7. If, as a consequence of a court judgment or allegation of patent infringement
-or for any other reason (not limited to patent issues), conditions are imposed on
-you (whether by court order, agreement or otherwise) that contradict the
-conditions of this License, they do not excuse you from the conditions of this
-License. If you cannot distribute so as to satisfy simultaneously your obligations
-under this License and any other pertinent obligations, then as a consequence
-you may not distribute the Program at all. For example, if a patent license would
-not permit royalty-free redistribution of the Program by all those who receive
-copies directly or indirectly through you, then the only way you could satisfy
-both it and this License would be to refrain entirely from distribution of the
-Program.
-
-If any portion of this section is held invalid or unenforceable under any particular
-circumstance, the balance of the section is intended to apply and the section as
-a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any patents or other
-property right claims or to contest validity of any such claims; this section has
-the sole purpose of protecting the integrity of the free software distribution
-system, which is implemented by public license practices. Many people have
-made generous contributions to the wide range of software distributed through
-that system in reliance on consistent application of that system; it is up to the
-author/donor to decide if he or she is willing to distribute software through any
-other system and a licensee cannot impose that choice.
-
-This section is intended to make thoroughly clear what is believed to be a
-consequence of the rest of this License.
-
-8. If the distribution and/or use of the Program is restricted in certain countries
-either by patents or by copyrighted interfaces, the original copyright holder who
-places the Program under this License may add an explicit geographical
-distribution limitation excluding those countries, so that distribution is permitted
-only in or among countries not thus excluded. In such case, this License
-incorporates the limitation as if written in the body of this License.
-
-9. The Free Software Foundation may publish revised and/or new versions of the
-General Public License from time to time. Such new versions will be similar in
-spirit to the present version, but may differ in detail to address new problems or
-concerns.
-
-Each version is given a distinguishing version number. If the Program specifies a
-version number of this License which applies to it and "any later version", you
-have the option of following the terms and conditions either of that version or of
-any later version published by the Free Software Foundation. If the Program does
-not specify a version number of this License, you may choose any version ever
-published by the Free Software Foundation.
-
-10. If you wish to incorporate parts of the Program into other free programs
-whose distribution conditions are different, write to the author to ask for
-permission. For software which is copyrighted by the Free Software Foundation,
-write to the Free Software Foundation; we sometimes make exceptions for this.
-Our decision will be guided by the two goals of preserving the free status of all
-derivatives of our free software and of promoting the sharing and reuse of
-software generally.
-
-NO WARRANTY
-
-11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS
-NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
-COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
-"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
-IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
-ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
-YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
-CORRECTION.
-
-12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED
-TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY
-WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS
-PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
-ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
-(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
-OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS
-BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-END OF TERMS AND CONDITIONS
-
-
-----------------------------------------------------------------------------
-
-The Artistic License
-
-Preamble
-
-The intent of this document is to state the conditions under which a Package
-may be copied, such that the Copyright Holder maintains some semblance of
-artistic control over the development of the package, while giving the users of the
-package the right to use and distribute the Package in a more-or-less customary
-fashion, plus the right to make reasonable modifications.
-
-Definitions:
-
-- "Package" refers to the collection of files distributed by the Copyright
- Holder, and derivatives of that collection of files created through textual
- modification.
-- "Standard Version" refers to such a Package if it has not been modified,
- or has been modified in accordance with the wishes of the Copyright
- Holder.
-- "Copyright Holder" is whoever is named in the copyright or copyrights for
- the package.
-- "You" is you, if you're thinking about copying or distributing this Package.
-- "Reasonable copying fee" is whatever you can justify on the basis of
- media cost, duplication charges, time of people involved, and so on. (You
- will not be required to justify it to the Copyright Holder, but only to the
- computing community at large as a market that must bear the fee.)
-- "Freely Available" means that no fee is charged for the item itself, though
- there may be fees involved in handling the item. It also means that
- recipients of the item may redistribute it under the same conditions they
- received it.
-
-1. You may make and give away verbatim copies of the source form of the
-Standard Version of this Package without restriction, provided that you duplicate
-all of the original copyright notices and associated disclaimers.
-
-2. You may apply bug fixes, portability fixes and other modifications derived from
-the Public Domain or from the Copyright Holder. A Package modified in such a
-way shall still be considered the Standard Version.
-
-3. You may otherwise modify your copy of this Package in any way, provided
-that you insert a prominent notice in each changed file stating how and when
-you changed that file, and provided that you do at least ONE of the following:
-
- a) place your modifications in the Public Domain or otherwise
- make them Freely Available, such as by posting said modifications
- to Usenet or an equivalent medium, or placing the modifications on
- a major archive site such as ftp.uu.net, or by allowing the
- Copyright Holder to include your modifications in the Standard
- Version of the Package.
-
- b) use the modified Package only within your corporation or
- organization.
-
- c) rename any non-standard executables so the names do not
- conflict with standard executables, which must also be provided,
- and provide a separate manual page for each non-standard
- executable that clearly documents how it differs from the Standard
- Version.
-
- d) make other distribution arrangements with the Copyright Holder.
-
-4. You may distribute the programs of this Package in object code or executable
-form, provided that you do at least ONE of the following:
-
- a) distribute a Standard Version of the executables and library
- files, together with instructions (in the manual page or equivalent)
- on where to get the Standard Version.
-
- b) accompany the distribution with the machine-readable source of
- the Package with your modifications.
-
- c) accompany any non-standard executables with their
- corresponding Standard Version executables, giving the
- non-standard executables non-standard names, and clearly
- documenting the differences in manual pages (or equivalent),
- together with instructions on where to get the Standard Version.
-
- d) make other distribution arrangements with the Copyright Holder.
-
-5. You may charge a reasonable copying fee for any distribution of this Package.
-You may charge any fee you choose for support of this Package. You may not
-charge a fee for this Package itself. However, you may distribute this Package in
-aggregate with other (possibly commercial) programs as part of a larger
-(possibly commercial) software distribution provided that you do not advertise
-this Package as a product of your own.
-
-6. The scripts and library files supplied as input to or produced as output from
-the programs of this Package do not automatically fall under the copyright of this
-Package, but belong to whomever generated them, and may be sold
-commercially, and may be aggregated with this Package.
-
-7. C or perl subroutines supplied by you and linked into this Package shall not
-be considered part of this Package.
-
-8. The name of the Copyright Holder may not be used to endorse or promote
-products derived from this software without specific prior written permission.
-
-9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
-IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.
-
-The End
-
-
diff --git a/MANIFEST b/MANIFEST
deleted file mode 100644
index e50ad78..0000000
--- a/MANIFEST
+++ /dev/null
@@ -1,9 +0,0 @@
-Changes
-lib/Email/Folder/IMAP.pm
-Makefile.PL
-MANIFEST This list of files
-README
-t/pod.t
-t/pod-coverage.t
-t/test.t
-LICENSE
diff --git a/Makefile.PL b/Makefile.PL
deleted file mode 100644
index ce92014..0000000
--- a/Makefile.PL
+++ /dev/null
@@ -1,17 +0,0 @@
-use strict;
-use ExtUtils::MakeMaker;
-
-WriteMakefile (
- AUTHOR => 'Casey West <[email protected]>',
- ABSTRACT => "Email::Folder Access to IMAP Folders",
- NAME => 'Email::Folder::IMAP',
- (eval { ExtUtils::MakeMaker->VERSION(6.21) } ? (LICENSE => 'perl') : ()),
- PREREQ_PM => {
- 'Test::More' => '0.47',
- 'Email::FolderType::Net' => '',
- 'Email::Folder::Reader' => '',
- 'Net::IMAP::Simple' => '0.95', # :port
- 'URI::imap' => '',
- },
- VERSION_FROM => 'lib/Email/Folder/IMAP.pm',
-);
diff --git a/README b/README
deleted file mode 100644
index 1d6d818..0000000
--- a/README
+++ /dev/null
@@ -1,49 +0,0 @@
-NAME
- Email::Folder::IMAP - Email::Folder Access to IMAP Folders
-
-SYNOPSIS
- use Email::Folder;
-
- my $folder = Email::Folder->new('imap://example.com'); # read INBOX
-
- print $_->header('Subject') for $folder->messages;
-
-DESCRIPTION
- This software adds IMAP functionality to Email::Folder. Its interface is
- identical to the other Email::Folder::Reader subclasses.
-
- Parameters
- "username" and "password" parameters may be sent to "new()". If used,
- they override any user info passed in the connection URI.
-
- Folder Specification
- Folders are specified using a simplified form of the IMAP URL Scheme
- detailed in RFC 2192. Not all of that specification applies. Here are a
- few examples.
-
- Selecting the INBOX.
-
- http://foo.com
-
- Selecting the INBOX using URI based authentication. Remember that the
- "username" and "password" parameters passed to "new()" will override
- anything set in the URI.
-
- http://user:[email protected]
-
- Selecting the p5p list.
-
- http://foo.com/perl/perl5-porters
-
-SEE ALSO
- Email::Folder, Email::Folder::Reader, Email::FolderType::Net, URI::imap,
- Net::IMAP::Simple.
-
-AUTHOR
- Casey West, <[email protected]>.
-
-COPYRIGHT
- Copyright (c) 2004 Casey West. All rights reserved.
- This module is free software; you can redistribute it and/or modify it
- under the same terms as Perl itself.
-
diff --git a/dist.ini b/dist.ini
new file mode 100644
index 0000000..dee6611
--- /dev/null
+++ b/dist.ini
@@ -0,0 +1,10 @@
+name = Email-Folder-IMAP
+author = Casey West <[email protected]>
+license = Perl_5
+copyright_holder = Casey West <[email protected]>
+copyright_year = 2004
+
+[@RJBS]
+[Prereqs]
+Email::FolderType::Net = 0
+Email::Folder::Reader = 0
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index ca14fbd..125abeb 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,124 +1,101 @@
-package Email::Folder::IMAP;
use strict;
+use warnings;
+package Email::Folder::IMAP;
+# ABSTRACT: Email::Folder Access to IMAP Folders
-use vars qw[$VERSION];
-$VERSION = '1.102';
+our $VERSION = '1.102';
-use base qw[Email::Folder::Reader];
-use Net::IMAP::Simple;
+use parent qw[Email::Folder::Reader];
+use Net::IMAP::Simple 0.95; # :port support
use URI;
sub _imap_class {
'Net::IMAP::Simple';
}
sub _uri {
my $self = shift;
return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
my $self = shift;
return $self->{_server} if $self->{_server};
my $uri = $self->_uri;
my $host = $uri->host_port;
my $server = $self->_imap_class->new($host);
my ($user, $pass) = @{$self}{qw[username password]};
($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
$server->login($user, $pass) if $user;
my $box = substr $uri->path, 1;
$server->select($box) if $box;
$self->{_next} = 1;
return $self->{_server} = $server;
}
sub next_message {
my $self = shift;
my $message = $self->_server->get($self->{_next});
if ($message) {
++$self->{_next};
return join '', @{$message};
}
$self->{_next} = 1;
return;
}
1;
-__END__
-
-=head1 NAME
-
-Email::Folder::IMAP - Email::Folder Access to IMAP Folders
-
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
imap://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
imap://user:[email protected]
Selecting the p5p list.
imap://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
-
-=head1 PERL EMAIL PROJECT
-
-This module is maintained by the Perl Email Project.
-
-L<http://emailproject.perl.org/wiki/Email::Folder::IMAP>
-
-=head1 AUTHOR
-
-Casey West, <F<[email protected]>>.
-
-=head1 COPYRIGHT
-
- Copyright (c) 2004 Casey West. All rights reserved.
- This module is free software; you can redistribute it and/or modify it
- under the same terms as Perl itself.
-
-=cut
diff --git a/t/pod-coverage.t b/t/pod-coverage.t
deleted file mode 100644
index a14e699..0000000
--- a/t/pod-coverage.t
+++ /dev/null
@@ -1,10 +0,0 @@
-#!perl -T
-
-use Test::More;
-eval "use Test::Pod::Coverage 1.08";
-plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage"
- if $@;
-
-all_pod_coverage_ok({
- coverage_class => 'Pod::Coverage::CountParents'
-});
diff --git a/t/pod.t b/t/pod.t
deleted file mode 100644
index 976d7cd..0000000
--- a/t/pod.t
+++ /dev/null
@@ -1,6 +0,0 @@
-#!perl -T
-
-use Test::More;
-eval "use Test::Pod 1.14";
-plan skip_all => "Test::Pod 1.14 required for testing POD" if $@;
-all_pod_files_ok();
|
Perl-Email-Project/Email-Folder-IMAP
|
29e05ec3b19b1f038caced5ef8f5f36ef725dffc
|
r31249@knight: rjbs | 2007-04-01 11:38:42 -0400 no pkg vars
|
diff --git a/Changes b/Changes
index 6bae348..b6f8d2e 100644
--- a/Changes
+++ b/Changes
@@ -1,12 +1,15 @@
+1.102 2007-04-01
+ avoid use of package variables for configuration; seriously, guys
+
1.101 2007-03-22
fix major documentation gaffe
packaging improvements
1.10 2006-07-11
require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
Synopsis screwup.
1.01 2004-08-07
Initial version.
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index 805ed9b..ca14fbd 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,121 +1,124 @@
package Email::Folder::IMAP;
use strict;
-use vars qw[$VERSION $IMAP];
-$VERSION = '1.101';
-$IMAP ||= 'Net::IMAP::Simple';
+use vars qw[$VERSION];
+$VERSION = '1.102';
use base qw[Email::Folder::Reader];
use Net::IMAP::Simple;
use URI;
+sub _imap_class {
+ 'Net::IMAP::Simple';
+}
+
sub _uri {
- my $self = shift;
- return $self->{_uri} ||= URI->new($self->{_file});
+ my $self = shift;
+ return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
- my $self = shift;
- return $self->{_server} if $self->{_server};
+ my $self = shift;
+ return $self->{_server} if $self->{_server};
+
+ my $uri = $self->_uri;
+
+ my $host = $uri->host_port;
+ my $server = $self->_imap_class->new($host);
- my $uri = $self->_uri;
+ my ($user, $pass) = @{$self}{qw[username password]};
+ ($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
- my $host = $uri->host_port;
- my $server = $IMAP->new( $host );
+ $server->login($user, $pass) if $user;
- my ($user, $pass) = @{$self}{qw[username password]};
- ($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
+ my $box = substr $uri->path, 1;
+ $server->select($box) if $box;
- $server->login($user, $pass) if $user;
-
- my $box = substr $uri->path, 1;
- $server->select($box) if $box;
-
- $self->{_next} = 1;
- return $self->{_server} = $server;
+ $self->{_next} = 1;
+ return $self->{_server} = $server;
}
sub next_message {
- my $self = shift;
- my $message = $self->_server->get($self->{_next});
- if ( $message ) {
- ++$self->{_next};
- return join '', @{$message};
- }
- $self->{_next} = 1;
- return;
+ my $self = shift;
+ my $message = $self->_server->get($self->{_next});
+ if ($message) {
+ ++$self->{_next};
+ return join '', @{$message};
+ }
+ $self->{_next} = 1;
+ return;
}
1;
__END__
=head1 NAME
Email::Folder::IMAP - Email::Folder Access to IMAP Folders
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
imap://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
imap://user:[email protected]
Selecting the p5p list.
imap://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
=head1 PERL EMAIL PROJECT
This module is maintained by the Perl Email Project.
L<http://emailproject.perl.org/wiki/Email::Folder::IMAP>
=head1 AUTHOR
Casey West, <F<[email protected]>>.
=head1 COPYRIGHT
Copyright (c) 2004 Casey West. All rights reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
|
Perl-Email-Project/Email-Folder-IMAP
|
7ed5bcf3525da1e694f4ec8c4a02481fea198082
|
r31150@knight: rjbs | 2007-03-22 17:03:19 -0400 docs,etc
|
diff --git a/Changes b/Changes
index 74806f1..6bae348 100644
--- a/Changes
+++ b/Changes
@@ -1,11 +1,12 @@
-1.10 2006-07-11
+1.101 2007-03-22
+ fix major documentation gaffe
+ packaging improvements
- - require newer Net::IMAP::Simple to allow port numbers
+1.10 2006-07-11
+ require newer Net::IMAP::Simple to allow port numbers
-1.02 2004-08-17
+1.02 2004-08-17
+ Synopsis screwup.
- - Synopsis screwup.
-
-1.01 2004-08-07
-
- - Initial version.
+1.01 2004-08-07
+ Initial version.
diff --git a/MANIFEST b/MANIFEST
index 870621d..e50ad78 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,10 +1,9 @@
Changes
lib/Email/Folder/IMAP.pm
Makefile.PL
MANIFEST This list of files
-META.yml
README
t/pod.t
t/pod-coverage.t
t/test.t
LICENSE
diff --git a/META.yml b/META.yml
deleted file mode 100644
index be1018a..0000000
--- a/META.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-# http://module-build.sourceforge.net/META-spec.html
-#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX#
-name: Email-Folder-IMAP
-version: 1.02
-version_from: lib/Email/Folder/IMAP.pm
-installdirs: site
-requires:
- Email::Folder::Reader:
- Email::FolderType::Net:
- Net::IMAP::Simple:
- Test::More: 0.47
- URI::imap:
-
-distribution_type: module
-generated_by: ExtUtils::MakeMaker version 6.17
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index c22bb40..805ed9b 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,115 +1,121 @@
package Email::Folder::IMAP;
use strict;
use vars qw[$VERSION $IMAP];
-$VERSION = '1.10';
+$VERSION = '1.101';
$IMAP ||= 'Net::IMAP::Simple';
use base qw[Email::Folder::Reader];
use Net::IMAP::Simple;
use URI;
sub _uri {
my $self = shift;
return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
my $self = shift;
return $self->{_server} if $self->{_server};
my $uri = $self->_uri;
my $host = $uri->host_port;
my $server = $IMAP->new( $host );
my ($user, $pass) = @{$self}{qw[username password]};
($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
$server->login($user, $pass) if $user;
my $box = substr $uri->path, 1;
$server->select($box) if $box;
$self->{_next} = 1;
return $self->{_server} = $server;
}
sub next_message {
my $self = shift;
my $message = $self->_server->get($self->{_next});
if ( $message ) {
++$self->{_next};
return join '', @{$message};
}
$self->{_next} = 1;
return;
}
1;
__END__
=head1 NAME
Email::Folder::IMAP - Email::Folder Access to IMAP Folders
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
- http://foo.com
+ imap://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
- http://user:[email protected]
+ imap://user:[email protected]
Selecting the p5p list.
- http://foo.com/perl/perl5-porters
+ imap://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
+=head1 PERL EMAIL PROJECT
+
+This module is maintained by the Perl Email Project.
+
+L<http://emailproject.perl.org/wiki/Email::Folder::IMAP>
+
=head1 AUTHOR
Casey West, <F<[email protected]>>.
=head1 COPYRIGHT
Copyright (c) 2004 Casey West. All rights reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
|
Perl-Email-Project/Email-Folder-IMAP
|
5add50afe290ba8284cfaa8727e802e926420fc0
|
r28280@minion101: rjbs | 2006-11-20 07:25:54 -0500 licenses, licenses, everywhere
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..05e86e0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,378 @@
+
+Terms of Perl itself
+
+a) the GNU General Public License as published by the Free
+ Software Foundation; either version 1, or (at your option) any
+ later version, or
+b) the "Artistic License"
+
+----------------------------------------------------------------------------
+
+The General Public License (GPL)
+Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
+Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
+verbatim copies of this license document, but changing it is not allowed.
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share
+and change it. By contrast, the GNU General Public License is intended to
+guarantee your freedom to share and change free software--to make sure the
+software is free for all its users. This General Public License applies to most of
+the Free Software Foundation's software and to any other program whose
+authors commit to using it. (Some other Free Software Foundation software is
+covered by the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our
+General Public Licenses are designed to make sure that you have the freedom
+to distribute copies of free software (and charge for this service if you wish), that
+you receive source code or can get it if you want it, that you can change the
+software or use pieces of it in new free programs; and that you know you can do
+these things.
+
+To protect your rights, we need to make restrictions that forbid anyone to deny
+you these rights or to ask you to surrender the rights. These restrictions
+translate to certain responsibilities for you if you distribute copies of the
+software, or if you modify it.
+
+For example, if you distribute copies of such a program, whether gratis or for a
+fee, you must give the recipients all the rights that you have. You must make
+sure that they, too, receive or can get the source code. And you must show
+them these terms so they know their rights.
+
+We protect your rights with two steps: (1) copyright the software, and (2) offer
+you this license which gives you legal permission to copy, distribute and/or
+modify the software.
+
+Also, for each author's protection and ours, we want to make certain that
+everyone understands that there is no warranty for this free software. If the
+software is modified by someone else and passed on, we want its recipients to
+know that what they have is not the original, so that any problems introduced by
+others will not reflect on the original authors' reputations.
+
+Finally, any free program is threatened constantly by software patents. We wish
+to avoid the danger that redistributors of a free program will individually obtain
+patent licenses, in effect making the program proprietary. To prevent this, we
+have made it clear that any patent must be licensed for everyone's free use or
+not licensed at all.
+
+The precise terms and conditions for copying, distribution and modification
+follow.
+
+GNU GENERAL PUBLIC LICENSE
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
+MODIFICATION
+
+0. This License applies to any program or other work which contains a notice
+placed by the copyright holder saying it may be distributed under the terms of
+this General Public License. The "Program", below, refers to any such program
+or work, and a "work based on the Program" means either the Program or any
+derivative work under copyright law: that is to say, a work containing the
+Program or a portion of it, either verbatim or with modifications and/or translated
+into another language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not covered by
+this License; they are outside its scope. The act of running the Program is not
+restricted, and the output from the Program is covered only if its contents
+constitute a work based on the Program (independent of having been made by
+running the Program). Whether that is true depends on what the Program does.
+
+1. You may copy and distribute verbatim copies of the Program's source code as
+you receive it, in any medium, provided that you conspicuously and appropriately
+publish on each copy an appropriate copyright notice and disclaimer of warranty;
+keep intact all the notices that refer to this License and to the absence of any
+warranty; and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and you may at
+your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Program or any portion of it, thus
+forming a work based on the Program, and copy and distribute such
+modifications or work under the terms of Section 1 above, provided that you also
+meet all of these conditions:
+
+a) You must cause the modified files to carry prominent notices stating that you
+changed the files and the date of any change.
+
+b) You must cause any work that you distribute or publish, that in whole or in
+part contains or is derived from the Program or any part thereof, to be licensed
+as a whole at no charge to all third parties under the terms of this License.
+
+c) If the modified program normally reads commands interactively when run, you
+must cause it, when started running for such interactive use in the most ordinary
+way, to print or display an announcement including an appropriate copyright
+notice and a notice that there is no warranty (or else, saying that you provide a
+warranty) and that users may redistribute the program under these conditions,
+and telling the user how to view a copy of this License. (Exception: if the
+Program itself is interactive but does not normally print such an announcement,
+your work based on the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If identifiable
+sections of that work are not derived from the Program, and can be reasonably
+considered independent and separate works in themselves, then this License,
+and its terms, do not apply to those sections when you distribute them as
+separate works. But when you distribute the same sections as part of a whole
+which is a work based on the Program, the distribution of the whole must be on
+the terms of this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to
+work written entirely by you; rather, the intent is to exercise the right to control
+the distribution of derivative or collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program with the
+Program (or with a work based on the Program) on a volume of a storage or
+distribution medium does not bring the other work under the scope of this
+License.
+
+3. You may copy and distribute the Program (or a work based on it, under
+Section 2) in object code or executable form under the terms of Sections 1 and 2
+above provided that you also do one of the following:
+
+a) Accompany it with the complete corresponding machine-readable source
+code, which must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange; or,
+
+b) Accompany it with a written offer, valid for at least three years, to give any
+third party, for a charge no more than your cost of physically performing source
+distribution, a complete machine-readable copy of the corresponding source
+code, to be distributed under the terms of Sections 1 and 2 above on a medium
+customarily used for software interchange; or,
+
+c) Accompany it with the information you received as to the offer to distribute
+corresponding source code. (This alternative is allowed only for noncommercial
+distribution and only if you received the program in object code or executable
+form with such an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for making
+modifications to it. For an executable work, complete source code means all the
+source code for all modules it contains, plus any associated interface definition
+files, plus the scripts used to control compilation and installation of the
+executable. However, as a special exception, the source code distributed need
+not include anything that is normally distributed (in either source or binary form)
+with the major components (compiler, kernel, and so on) of the operating system
+on which the executable runs, unless that component itself accompanies the
+executable.
+
+If distribution of executable or object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the source
+code from the same place counts as distribution of the source code, even though
+third parties are not compelled to copy the source along with the object code.
+
+4. You may not copy, modify, sublicense, or distribute the Program except as
+expressly provided under this License. Any attempt otherwise to copy, modify,
+sublicense or distribute the Program is void, and will automatically terminate
+your rights under this License. However, parties who have received copies, or
+rights, from you under this License will not have their licenses terminated so long
+as such parties remain in full compliance.
+
+5. You are not required to accept this License, since you have not signed it.
+However, nothing else grants you permission to modify or distribute the Program
+or its derivative works. These actions are prohibited by law if you do not accept
+this License. Therefore, by modifying or distributing the Program (or any work
+based on the Program), you indicate your acceptance of this License to do so,
+and all its terms and conditions for copying, distributing or modifying the
+Program or works based on it.
+
+6. Each time you redistribute the Program (or any work based on the Program),
+the recipient automatically receives a license from the original licensor to copy,
+distribute or modify the Program subject to these terms and conditions. You
+may not impose any further restrictions on the recipients' exercise of the rights
+granted herein. You are not responsible for enforcing compliance by third parties
+to this License.
+
+7. If, as a consequence of a court judgment or allegation of patent infringement
+or for any other reason (not limited to patent issues), conditions are imposed on
+you (whether by court order, agreement or otherwise) that contradict the
+conditions of this License, they do not excuse you from the conditions of this
+License. If you cannot distribute so as to satisfy simultaneously your obligations
+under this License and any other pertinent obligations, then as a consequence
+you may not distribute the Program at all. For example, if a patent license would
+not permit royalty-free redistribution of the Program by all those who receive
+copies directly or indirectly through you, then the only way you could satisfy
+both it and this License would be to refrain entirely from distribution of the
+Program.
+
+If any portion of this section is held invalid or unenforceable under any particular
+circumstance, the balance of the section is intended to apply and the section as
+a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other
+property right claims or to contest validity of any such claims; this section has
+the sole purpose of protecting the integrity of the free software distribution
+system, which is implemented by public license practices. Many people have
+made generous contributions to the wide range of software distributed through
+that system in reliance on consistent application of that system; it is up to the
+author/donor to decide if he or she is willing to distribute software through any
+other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a
+consequence of the rest of this License.
+
+8. If the distribution and/or use of the Program is restricted in certain countries
+either by patents or by copyrighted interfaces, the original copyright holder who
+places the Program under this License may add an explicit geographical
+distribution limitation excluding those countries, so that distribution is permitted
+only in or among countries not thus excluded. In such case, this License
+incorporates the limitation as if written in the body of this License.
+
+9. The Free Software Foundation may publish revised and/or new versions of the
+General Public License from time to time. Such new versions will be similar in
+spirit to the present version, but may differ in detail to address new problems or
+concerns.
+
+Each version is given a distinguishing version number. If the Program specifies a
+version number of this License which applies to it and "any later version", you
+have the option of following the terms and conditions either of that version or of
+any later version published by the Free Software Foundation. If the Program does
+not specify a version number of this License, you may choose any version ever
+published by the Free Software Foundation.
+
+10. If you wish to incorporate parts of the Program into other free programs
+whose distribution conditions are different, write to the author to ask for
+permission. For software which is copyrighted by the Free Software Foundation,
+write to the Free Software Foundation; we sometimes make exceptions for this.
+Our decision will be guided by the two goals of preserving the free status of all
+derivatives of our free software and of promoting the sharing and reuse of
+software generally.
+
+NO WARRANTY
+
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS
+NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
+COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
+"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
+IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
+ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
+YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
+CORRECTION.
+
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED
+TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY
+WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS
+PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
+(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
+OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS
+BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+
+----------------------------------------------------------------------------
+
+The Artistic License
+
+Preamble
+
+The intent of this document is to state the conditions under which a Package
+may be copied, such that the Copyright Holder maintains some semblance of
+artistic control over the development of the package, while giving the users of the
+package the right to use and distribute the Package in a more-or-less customary
+fashion, plus the right to make reasonable modifications.
+
+Definitions:
+
+- "Package" refers to the collection of files distributed by the Copyright
+ Holder, and derivatives of that collection of files created through textual
+ modification.
+- "Standard Version" refers to such a Package if it has not been modified,
+ or has been modified in accordance with the wishes of the Copyright
+ Holder.
+- "Copyright Holder" is whoever is named in the copyright or copyrights for
+ the package.
+- "You" is you, if you're thinking about copying or distributing this Package.
+- "Reasonable copying fee" is whatever you can justify on the basis of
+ media cost, duplication charges, time of people involved, and so on. (You
+ will not be required to justify it to the Copyright Holder, but only to the
+ computing community at large as a market that must bear the fee.)
+- "Freely Available" means that no fee is charged for the item itself, though
+ there may be fees involved in handling the item. It also means that
+ recipients of the item may redistribute it under the same conditions they
+ received it.
+
+1. You may make and give away verbatim copies of the source form of the
+Standard Version of this Package without restriction, provided that you duplicate
+all of the original copyright notices and associated disclaimers.
+
+2. You may apply bug fixes, portability fixes and other modifications derived from
+the Public Domain or from the Copyright Holder. A Package modified in such a
+way shall still be considered the Standard Version.
+
+3. You may otherwise modify your copy of this Package in any way, provided
+that you insert a prominent notice in each changed file stating how and when
+you changed that file, and provided that you do at least ONE of the following:
+
+ a) place your modifications in the Public Domain or otherwise
+ make them Freely Available, such as by posting said modifications
+ to Usenet or an equivalent medium, or placing the modifications on
+ a major archive site such as ftp.uu.net, or by allowing the
+ Copyright Holder to include your modifications in the Standard
+ Version of the Package.
+
+ b) use the modified Package only within your corporation or
+ organization.
+
+ c) rename any non-standard executables so the names do not
+ conflict with standard executables, which must also be provided,
+ and provide a separate manual page for each non-standard
+ executable that clearly documents how it differs from the Standard
+ Version.
+
+ d) make other distribution arrangements with the Copyright Holder.
+
+4. You may distribute the programs of this Package in object code or executable
+form, provided that you do at least ONE of the following:
+
+ a) distribute a Standard Version of the executables and library
+ files, together with instructions (in the manual page or equivalent)
+ on where to get the Standard Version.
+
+ b) accompany the distribution with the machine-readable source of
+ the Package with your modifications.
+
+ c) accompany any non-standard executables with their
+ corresponding Standard Version executables, giving the
+ non-standard executables non-standard names, and clearly
+ documenting the differences in manual pages (or equivalent),
+ together with instructions on where to get the Standard Version.
+
+ d) make other distribution arrangements with the Copyright Holder.
+
+5. You may charge a reasonable copying fee for any distribution of this Package.
+You may charge any fee you choose for support of this Package. You may not
+charge a fee for this Package itself. However, you may distribute this Package in
+aggregate with other (possibly commercial) programs as part of a larger
+(possibly commercial) software distribution provided that you do not advertise
+this Package as a product of your own.
+
+6. The scripts and library files supplied as input to or produced as output from
+the programs of this Package do not automatically fall under the copyright of this
+Package, but belong to whomever generated them, and may be sold
+commercially, and may be aggregated with this Package.
+
+7. C or perl subroutines supplied by you and linked into this Package shall not
+be considered part of this Package.
+
+8. The name of the Copyright Holder may not be used to endorse or promote
+products derived from this software without specific prior written permission.
+
+9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.
+
+The End
+
+
diff --git a/MANIFEST b/MANIFEST
index aa40fc1..870621d 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,9 +1,10 @@
Changes
lib/Email/Folder/IMAP.pm
Makefile.PL
MANIFEST This list of files
META.yml
README
t/pod.t
t/pod-coverage.t
t/test.t
+LICENSE
diff --git a/Makefile.PL b/Makefile.PL
index 5de0b9f..ce92014 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,15 +1,17 @@
+use strict;
use ExtUtils::MakeMaker;
WriteMakefile (
- AUTHOR => 'Casey West <[email protected]>',
- ABSTRACT => "Email::Folder Access to IMAP Folders",
- NAME => 'Email::Folder::IMAP',
- PREREQ_PM => {
- 'Test::More' => '0.47',
- 'Email::FolderType::Net' => '',
- 'Email::Folder::Reader' => '',
- 'Net::IMAP::Simple' => '0.95', # :port
- 'URI::imap' => '',
- },
- VERSION_FROM => 'lib/Email/Folder/IMAP.pm',
- );
+ AUTHOR => 'Casey West <[email protected]>',
+ ABSTRACT => "Email::Folder Access to IMAP Folders",
+ NAME => 'Email::Folder::IMAP',
+ (eval { ExtUtils::MakeMaker->VERSION(6.21) } ? (LICENSE => 'perl') : ()),
+ PREREQ_PM => {
+ 'Test::More' => '0.47',
+ 'Email::FolderType::Net' => '',
+ 'Email::Folder::Reader' => '',
+ 'Net::IMAP::Simple' => '0.95', # :port
+ 'URI::imap' => '',
+ },
+ VERSION_FROM => 'lib/Email/Folder/IMAP.pm',
+);
|
Perl-Email-Project/Email-Folder-IMAP
|
d3573b8425f43a8a6a1605a62e4ef860379de70c
|
r23181@knight: rjbs | 2006-07-11 11:23:07 -0400 remove trustme
|
diff --git a/t/pod-coverage.t b/t/pod-coverage.t
index 65ac370..a14e699 100644
--- a/t/pod-coverage.t
+++ b/t/pod-coverage.t
@@ -1,13 +1,10 @@
#!perl -T
use Test::More;
eval "use Test::Pod::Coverage 1.08";
plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage"
if $@;
-# Having to trustme these is obnoxious. It would be nice if there was a base
-# class for mailers. Then again, whatever. -- rjbs, 2006-07-06
all_pod_coverage_ok({
- trustme => [ qw(send is_available) ],
coverage_class => 'Pod::Coverage::CountParents'
});
|
Perl-Email-Project/Email-Folder-IMAP
|
a9f8253d7d51988ca48e7189275a23fe18a1cf1a
|
r23175@knight: rjbs | 2006-07-11 11:10:44 -0400 pod tests
|
diff --git a/MANIFEST b/MANIFEST
index e662444..aa40fc1 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,7 +1,9 @@
Changes
lib/Email/Folder/IMAP.pm
Makefile.PL
MANIFEST This list of files
META.yml
README
+t/pod.t
+t/pod-coverage.t
t/test.t
diff --git a/t/pod-coverage.t b/t/pod-coverage.t
new file mode 100644
index 0000000..65ac370
--- /dev/null
+++ b/t/pod-coverage.t
@@ -0,0 +1,13 @@
+#!perl -T
+
+use Test::More;
+eval "use Test::Pod::Coverage 1.08";
+plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage"
+ if $@;
+
+# Having to trustme these is obnoxious. It would be nice if there was a base
+# class for mailers. Then again, whatever. -- rjbs, 2006-07-06
+all_pod_coverage_ok({
+ trustme => [ qw(send is_available) ],
+ coverage_class => 'Pod::Coverage::CountParents'
+});
diff --git a/t/pod.t b/t/pod.t
new file mode 100644
index 0000000..976d7cd
--- /dev/null
+++ b/t/pod.t
@@ -0,0 +1,6 @@
+#!perl -T
+
+use Test::More;
+eval "use Test::Pod 1.14";
+plan skip_all => "Test::Pod 1.14 required for testing POD" if $@;
+all_pod_files_ok();
|
Perl-Email-Project/Email-Folder-IMAP
|
faf379d652cb975680b297454523b164074c2faa
|
r23172@knight: rjbs | 2006-07-11 11:09:42 -0400 date
|
diff --git a/Changes b/Changes
index b45593d..74806f1 100644
--- a/Changes
+++ b/Changes
@@ -1,11 +1,11 @@
-1.10 2006-07-07
+1.10 2006-07-11
- require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
- Synopsis screwup.
1.01 2004-08-07
- Initial version.
|
Perl-Email-Project/Email-Folder-IMAP
|
a63fe5c7929b0fac37ad0c9c22dbcff136dfbb71
|
r23171@knight: rjbs | 2006-07-11 11:09:25 -0400 version deflation
|
diff --git a/Changes b/Changes
index 577d147..b45593d 100644
--- a/Changes
+++ b/Changes
@@ -1,11 +1,11 @@
-1.21 2006-07-07
+1.10 2006-07-07
- require newer Net::IMAP::Simple to allow port numbers
1.02 2004-08-17
- Synopsis screwup.
1.01 2004-08-07
- Initial version.
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index 5249332..c22bb40 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,115 +1,115 @@
package Email::Folder::IMAP;
use strict;
use vars qw[$VERSION $IMAP];
-$VERSION = '1.21';
+$VERSION = '1.10';
$IMAP ||= 'Net::IMAP::Simple';
use base qw[Email::Folder::Reader];
use Net::IMAP::Simple;
use URI;
sub _uri {
my $self = shift;
return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
my $self = shift;
return $self->{_server} if $self->{_server};
my $uri = $self->_uri;
my $host = $uri->host_port;
my $server = $IMAP->new( $host );
my ($user, $pass) = @{$self}{qw[username password]};
($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
$server->login($user, $pass) if $user;
my $box = substr $uri->path, 1;
$server->select($box) if $box;
$self->{_next} = 1;
return $self->{_server} = $server;
}
sub next_message {
my $self = shift;
my $message = $self->_server->get($self->{_next});
if ( $message ) {
++$self->{_next};
return join '', @{$message};
}
$self->{_next} = 1;
return;
}
1;
__END__
=head1 NAME
Email::Folder::IMAP - Email::Folder Access to IMAP Folders
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
http://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
http://user:[email protected]
Selecting the p5p list.
http://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
=head1 AUTHOR
Casey West, <F<[email protected]>>.
=head1 COPYRIGHT
Copyright (c) 2004 Casey West. All rights reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
|
Perl-Email-Project/Email-Folder-IMAP
|
7abe2245a21fd34d8b5515b7afc3cc3ada5fcee6
|
r23069@knight: rjbs | 2006-07-07 09:47:00 -0400 newer imap modules for :port
|
diff --git a/Changes b/Changes
index 4910a75..577d147 100644
--- a/Changes
+++ b/Changes
@@ -1,7 +1,11 @@
+1.21 2006-07-07
+
+ - require newer Net::IMAP::Simple to allow port numbers
+
1.02 2004-08-17
- Synopsis screwup.
1.01 2004-08-07
- Initial version.
diff --git a/Makefile.PL b/Makefile.PL
index 6a04fbb..5de0b9f 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,15 +1,15 @@
use ExtUtils::MakeMaker;
WriteMakefile (
AUTHOR => 'Casey West <[email protected]>',
ABSTRACT => "Email::Folder Access to IMAP Folders",
NAME => 'Email::Folder::IMAP',
PREREQ_PM => {
'Test::More' => '0.47',
'Email::FolderType::Net' => '',
'Email::Folder::Reader' => '',
- 'Net::IMAP::Simple' => '',
+ 'Net::IMAP::Simple' => '0.95', # :port
'URI::imap' => '',
},
VERSION_FROM => 'lib/Email/Folder/IMAP.pm',
);
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
index 1bce406..5249332 100644
--- a/lib/Email/Folder/IMAP.pm
+++ b/lib/Email/Folder/IMAP.pm
@@ -1,116 +1,115 @@
package Email::Folder::IMAP;
-# $Id: IMAP.pm,v 1.2 2004/08/18 00:34:53 cwest Exp $
use strict;
use vars qw[$VERSION $IMAP];
-$VERSION = sprintf "%d.%02d", split m/\./, (qw$Revision: 1.2 $)[1];
+$VERSION = '1.21';
$IMAP ||= 'Net::IMAP::Simple';
use base qw[Email::Folder::Reader];
use Net::IMAP::Simple;
use URI;
sub _uri {
my $self = shift;
return $self->{_uri} ||= URI->new($self->{_file});
}
sub _server {
my $self = shift;
return $self->{_server} if $self->{_server};
my $uri = $self->_uri;
my $host = $uri->host_port;
my $server = $IMAP->new( $host );
my ($user, $pass) = @{$self}{qw[username password]};
($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
$server->login($user, $pass) if $user;
my $box = substr $uri->path, 1;
$server->select($box) if $box;
$self->{_next} = 1;
return $self->{_server} = $server;
}
sub next_message {
my $self = shift;
my $message = $self->_server->get($self->{_next});
if ( $message ) {
++$self->{_next};
return join '', @{$message};
}
$self->{_next} = 1;
return;
}
1;
__END__
=head1 NAME
Email::Folder::IMAP - Email::Folder Access to IMAP Folders
=head1 SYNOPSIS
use Email::Folder;
use Email::FolderType::Net;
my $folder = Email::Folder->new('imap://example.com'); # read INBOX
print $_->header('Subject') for $folder->messages;
=head1 DESCRIPTION
This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
Its interface is identical to the other
L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
=head2 Parameters
C<username> and C<password> parameters may be sent to C<new()>. If
used, they override any user info passed in the connection URI.
=head2 Folder Specification
Folders are specified using a simplified form of the IMAP URL Scheme
detailed in RFC 2192. Not all of that specification applies. Here
are a few examples.
Selecting the INBOX.
http://foo.com
Selecting the INBOX using URI based authentication. Remember that the
C<username> and C<password> parameters passed to C<new()> will override
anything set in the URI.
http://user:[email protected]
Selecting the p5p list.
http://foo.com/perl/perl5-porters
=head1 SEE ALSO
L<Email::Folder>,
L<Email::Folder::Reader>,
L<Email::FolderType::Net>,
L<URI::imap>,
L<Net::IMAP::Simple>.
=head1 AUTHOR
Casey West, <F<[email protected]>>.
=head1 COPYRIGHT
Copyright (c) 2004 Casey West. All rights reserved.
This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
|
Perl-Email-Project/Email-Folder-IMAP
|
250aa4c80baa0a270ab565853f139f509040aacb
|
r22882@knight: rjbs | 2006-07-04 07:19:15 -0400 import from mailclue cvs
|
diff --git a/Changes b/Changes
new file mode 100644
index 0000000..4910a75
--- /dev/null
+++ b/Changes
@@ -0,0 +1,7 @@
+1.02 2004-08-17
+
+ - Synopsis screwup.
+
+1.01 2004-08-07
+
+ - Initial version.
diff --git a/MANIFEST b/MANIFEST
new file mode 100644
index 0000000..e662444
--- /dev/null
+++ b/MANIFEST
@@ -0,0 +1,7 @@
+Changes
+lib/Email/Folder/IMAP.pm
+Makefile.PL
+MANIFEST This list of files
+META.yml
+README
+t/test.t
diff --git a/META.yml b/META.yml
new file mode 100644
index 0000000..be1018a
--- /dev/null
+++ b/META.yml
@@ -0,0 +1,15 @@
+# http://module-build.sourceforge.net/META-spec.html
+#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX#
+name: Email-Folder-IMAP
+version: 1.02
+version_from: lib/Email/Folder/IMAP.pm
+installdirs: site
+requires:
+ Email::Folder::Reader:
+ Email::FolderType::Net:
+ Net::IMAP::Simple:
+ Test::More: 0.47
+ URI::imap:
+
+distribution_type: module
+generated_by: ExtUtils::MakeMaker version 6.17
diff --git a/Makefile.PL b/Makefile.PL
new file mode 100644
index 0000000..6a04fbb
--- /dev/null
+++ b/Makefile.PL
@@ -0,0 +1,15 @@
+use ExtUtils::MakeMaker;
+
+WriteMakefile (
+ AUTHOR => 'Casey West <[email protected]>',
+ ABSTRACT => "Email::Folder Access to IMAP Folders",
+ NAME => 'Email::Folder::IMAP',
+ PREREQ_PM => {
+ 'Test::More' => '0.47',
+ 'Email::FolderType::Net' => '',
+ 'Email::Folder::Reader' => '',
+ 'Net::IMAP::Simple' => '',
+ 'URI::imap' => '',
+ },
+ VERSION_FROM => 'lib/Email/Folder/IMAP.pm',
+ );
diff --git a/README b/README
new file mode 100644
index 0000000..1d6d818
--- /dev/null
+++ b/README
@@ -0,0 +1,49 @@
+NAME
+ Email::Folder::IMAP - Email::Folder Access to IMAP Folders
+
+SYNOPSIS
+ use Email::Folder;
+
+ my $folder = Email::Folder->new('imap://example.com'); # read INBOX
+
+ print $_->header('Subject') for $folder->messages;
+
+DESCRIPTION
+ This software adds IMAP functionality to Email::Folder. Its interface is
+ identical to the other Email::Folder::Reader subclasses.
+
+ Parameters
+ "username" and "password" parameters may be sent to "new()". If used,
+ they override any user info passed in the connection URI.
+
+ Folder Specification
+ Folders are specified using a simplified form of the IMAP URL Scheme
+ detailed in RFC 2192. Not all of that specification applies. Here are a
+ few examples.
+
+ Selecting the INBOX.
+
+ http://foo.com
+
+ Selecting the INBOX using URI based authentication. Remember that the
+ "username" and "password" parameters passed to "new()" will override
+ anything set in the URI.
+
+ http://user:[email protected]
+
+ Selecting the p5p list.
+
+ http://foo.com/perl/perl5-porters
+
+SEE ALSO
+ Email::Folder, Email::Folder::Reader, Email::FolderType::Net, URI::imap,
+ Net::IMAP::Simple.
+
+AUTHOR
+ Casey West, <[email protected]>.
+
+COPYRIGHT
+ Copyright (c) 2004 Casey West. All rights reserved.
+ This module is free software; you can redistribute it and/or modify it
+ under the same terms as Perl itself.
+
diff --git a/lib/Email/Folder/IMAP.pm b/lib/Email/Folder/IMAP.pm
new file mode 100644
index 0000000..1bce406
--- /dev/null
+++ b/lib/Email/Folder/IMAP.pm
@@ -0,0 +1,116 @@
+package Email::Folder::IMAP;
+# $Id: IMAP.pm,v 1.2 2004/08/18 00:34:53 cwest Exp $
+use strict;
+
+use vars qw[$VERSION $IMAP];
+$VERSION = sprintf "%d.%02d", split m/\./, (qw$Revision: 1.2 $)[1];
+$IMAP ||= 'Net::IMAP::Simple';
+
+use base qw[Email::Folder::Reader];
+use Net::IMAP::Simple;
+use URI;
+
+sub _uri {
+ my $self = shift;
+ return $self->{_uri} ||= URI->new($self->{_file});
+}
+
+sub _server {
+ my $self = shift;
+ return $self->{_server} if $self->{_server};
+
+ my $uri = $self->_uri;
+
+ my $host = $uri->host_port;
+ my $server = $IMAP->new( $host );
+
+ my ($user, $pass) = @{$self}{qw[username password]};
+ ($user, $pass) = split ':', $uri->userinfo, 2 unless $user;
+
+ $server->login($user, $pass) if $user;
+
+ my $box = substr $uri->path, 1;
+ $server->select($box) if $box;
+
+ $self->{_next} = 1;
+ return $self->{_server} = $server;
+}
+
+sub next_message {
+ my $self = shift;
+ my $message = $self->_server->get($self->{_next});
+ if ( $message ) {
+ ++$self->{_next};
+ return join '', @{$message};
+ }
+ $self->{_next} = 1;
+ return;
+}
+
+1;
+
+__END__
+
+=head1 NAME
+
+Email::Folder::IMAP - Email::Folder Access to IMAP Folders
+
+=head1 SYNOPSIS
+
+ use Email::Folder;
+ use Email::FolderType::Net;
+
+ my $folder = Email::Folder->new('imap://example.com'); # read INBOX
+
+ print $_->header('Subject') for $folder->messages;
+
+=head1 DESCRIPTION
+
+This software adds IMAP functionality to L<Email::Folder|Email::Folder>.
+Its interface is identical to the other
+L<Email::Folder::Reader|Email::Folder::Reader> subclasses.
+
+=head2 Parameters
+
+C<username> and C<password> parameters may be sent to C<new()>. If
+used, they override any user info passed in the connection URI.
+
+=head2 Folder Specification
+
+Folders are specified using a simplified form of the IMAP URL Scheme
+detailed in RFC 2192. Not all of that specification applies. Here
+are a few examples.
+
+Selecting the INBOX.
+
+ http://foo.com
+
+Selecting the INBOX using URI based authentication. Remember that the
+C<username> and C<password> parameters passed to C<new()> will override
+anything set in the URI.
+
+ http://user:[email protected]
+
+Selecting the p5p list.
+
+ http://foo.com/perl/perl5-porters
+
+=head1 SEE ALSO
+
+L<Email::Folder>,
+L<Email::Folder::Reader>,
+L<Email::FolderType::Net>,
+L<URI::imap>,
+L<Net::IMAP::Simple>.
+
+=head1 AUTHOR
+
+Casey West, <F<[email protected]>>.
+
+=head1 COPYRIGHT
+
+ Copyright (c) 2004 Casey West. All rights reserved.
+ This module is free software; you can redistribute it and/or modify it
+ under the same terms as Perl itself.
+
+=cut
diff --git a/t/test.t b/t/test.t
new file mode 100644
index 0000000..a40d337
--- /dev/null
+++ b/t/test.t
@@ -0,0 +1,7 @@
+use Test::More qw[no_plan];
+use strict;
+$^W = 1;
+
+use_ok 'Email::Folder::IMAP';
+
+can_ok 'Email::Folder::IMAP', qw[new next_message messages];
|
aasmith/plastic-pig
|
f510b0a83b1c077640fa4c19321c2d86d51679e8
|
Adding more strategies
|
diff --git a/bt.rb b/bt.rb
index b15628c..fd77cf3 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,98 +1,100 @@
$: << "lib"
require 'plastic_pig'
BASE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;"
DATA_QUERIES = [
"type=quote;range=%s/json/", # price-data
"type=macd;range=%s/json?period1=26&period2=12&signal=9", # divergence = macd - signal,
# macd = MACD(26,12),
# signal = MACD(9)
"type=rsi;range=%s/json?period=14", # rsi = RSI(14)
"type=sma;range=%s/json?period=200", # sma = SMA(200)
"type=stochasticslow;range=%s/json?period=15&dperiod=5", # signal = %D(5), stochastic = %K(15)
]
URLS = DATA_QUERIES.map{|d| BASE_URL + d }
def help
puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
puts "Fetching ..."
raw_series = URLS.map do |url|
series = PlasticPig::YahooFetcher.new(url % [symbol, range]).fetch
type = url.scan(/type=(\w+);/).to_s
unless type == "quote"
series.each do |row|
(row.keys - ["Date", type]).each do |key|
row["#{type}_#{key}"] = row.delete(key)
end
end
end
series
end
puts "Normalizing ..."
series = []
# Iterate though one data set, adding data when all series have data for that date.
raw_series.first.each do |row|
date = row["Date"]
# Slow.
all_data_for_date = raw_series.map{|rs| rs.detect{|r| r["Date"] == date } }
# skip if not all data available for date
unless all_data_for_date.compact.size == raw_series.size
puts "skipping incomplete date #{date}"
next
end
# merge array of hashes into one hash
all_data_for_date = all_data_for_date.inject({}) { |h,e| h.merge(e) }
series << all_data_for_date
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::Structures::DayFactory.build_list(series)
strategies = []
+strategies << PlasticPig::Strategies::SimpleMacd.new
+strategies << PlasticPig::Strategies::DoubleCross.new
strategies << PlasticPig::Strategies::RsiClassic.new(:rsi_70)
strategies << PlasticPig::Strategies::RsiAgita.new
puts "Backtesting ..."
bt = PlasticPig::BackTester.new(head, strategies)
entries = bt.run
entries.each { |e| puts "-"*80, e.summary, "" }
puts "="*80
puts "Used data ranging from #{head.date} to #{head.last.date}"
exits = entries.select { |e| e.exit }
puts "Found #{entries.size} entries, with #{exits.size} exits."
# Unique exits are important because it demonstrates how
# often a strategy is likely to work. If a strategy returns a
# high number of entries, but a low number of unique exits, then
# it may be a sign that the exit condition may have be fluke, and
# is unlikely to be reproducable.
uniqs = exits.map{|e|e.exit.day if e.exit}.compact.uniq
puts "There were #{uniqs.size} (#{(uniqs.size / exits.size.to_f * 100).places(2)}%) unique exit dates."
diff --git a/lib/plastic_pig/strategies.rb b/lib/plastic_pig/strategies.rb
index f819f43..ac6d463 100644
--- a/lib/plastic_pig/strategies.rb
+++ b/lib/plastic_pig/strategies.rb
@@ -1,2 +1,4 @@
+require 'plastic_pig/strategies/double_cross'
require 'plastic_pig/strategies/rsi_agita'
require 'plastic_pig/strategies/rsi_classic'
+require 'plastic_pig/strategies/simple_macd'
diff --git a/lib/plastic_pig/strategies/double_cross.rb b/lib/plastic_pig/strategies/double_cross.rb
new file mode 100644
index 0000000..729a4f0
--- /dev/null
+++ b/lib/plastic_pig/strategies/double_cross.rb
@@ -0,0 +1,39 @@
+# http://www.investopedia.com/articles/trading/08/macd-stochastic-double-cross.asp
+module PlasticPig
+ module Strategies
+ class DoubleCross
+ def enter?(day)
+ days = [day.previous, day]
+
+ return false unless days.all?
+
+ pd = day.previous.stochasticslow_signal
+ pk = day.previous.stochasticslow_stochastic
+
+ d = day.stochasticslow_signal
+ k = day.stochasticslow_stochastic
+
+ # does k cross over d ?
+ a = !(pk > d) && (k > d)
+
+ # k less than 50
+ b = k < 50
+
+ # macd div > 0 and macd > sig
+ #c = days.any?{|d| d.macd_divergence > 0 }
+ #d = days.any?{|d| d.macd > d.macd_signal }
+
+ # price above sma?
+ e = day.close > day.sma
+
+ if a and b and e
+ "double cross met"
+ end
+ end
+
+ def exit?(day, days_from_entry)
+ "getting old" if days_from_entry >= 5
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/strategies/simple_macd.rb b/lib/plastic_pig/strategies/simple_macd.rb
new file mode 100644
index 0000000..81d0a28
--- /dev/null
+++ b/lib/plastic_pig/strategies/simple_macd.rb
@@ -0,0 +1,13 @@
+module PlasticPig
+ module Strategies
+ class SimpleMacd
+ def enter?(day)
+ "div rose above 0" if (day.previous.macd_divergence..day.macd_divergence).crossed_above?(0)
+ end
+
+ def exit?(day, days_from_entry)
+ "bored" if days_from_entry >= 3
+ end
+ end
+ end
+end
|
aasmith/plastic-pig
|
6051a9f583c674784bb814cd303ee64d2ad5507a
|
Formatting.
|
diff --git a/lib/plastic_pig/strategies/rsi_agita.rb b/lib/plastic_pig/strategies/rsi_agita.rb
index 12ad0c4..e6963a6 100644
--- a/lib/plastic_pig/strategies/rsi_agita.rb
+++ b/lib/plastic_pig/strategies/rsi_agita.rb
@@ -1,23 +1,23 @@
module PlasticPig
module Strategies
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
- "RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ "RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
- "RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ "RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
end
diff --git a/lib/plastic_pig/structures/day.rb b/lib/plastic_pig/structures/day.rb
index f307c89..b3a48d1 100644
--- a/lib/plastic_pig/structures/day.rb
+++ b/lib/plastic_pig/structures/day.rb
@@ -1,26 +1,26 @@
module PlasticPig
module Structures
class Day
include LinkedList
VARS = %w(
date open high low close volume
rsi
sma
macd macd_divergence macd_signal
stochasticslow_signal stochasticslow_stochastic
)
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
- "<Day: #{pairs.join(",")}>"
+ "<Day: #{pairs.join(",")}>"
end
end
end
end
|
aasmith/plastic-pig
|
497429f921ff1983d8cf9f658ef4d4d425116dd0
|
Remove data-deleting bug.
|
diff --git a/bt.rb b/bt.rb
index 7d862c6..b15628c 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,101 +1,98 @@
$: << "lib"
require 'plastic_pig'
BASE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;"
DATA_QUERIES = [
"type=quote;range=%s/json/", # price-data
"type=macd;range=%s/json?period1=26&period2=12&signal=9", # divergence = macd - signal,
# macd = MACD(26,12),
# signal = MACD(9)
"type=rsi;range=%s/json?period=14", # rsi = RSI(14)
"type=sma;range=%s/json?period=200", # sma = SMA(200)
"type=stochasticslow;range=%s/json?period=15&dperiod=5", # signal = %D(5), stochastic = %K(15)
]
URLS = DATA_QUERIES.map{|d| BASE_URL + d }
def help
puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
puts "Fetching ..."
raw_series = URLS.map do |url|
series = PlasticPig::YahooFetcher.new(url % [symbol, range]).fetch
type = url.scan(/type=(\w+);/).to_s
unless type == "quote"
series.each do |row|
(row.keys - ["Date", type]).each do |key|
row["#{type}_#{key}"] = row.delete(key)
end
end
end
series
end
puts "Normalizing ..."
series = []
# Iterate though one data set, adding data when all series have data for that date.
raw_series.first.each do |row|
date = row["Date"]
- # Equiv of:
- # all_data_for_date = raw_series.map{|rs| rs.detect{|r| r["Date"] == date } }
- # but faster because source array is slowly deleted from, reducing search space.
- all_data_for_date = []
- raw_series.each{|rs| rs.delete_if{|r| r["Date"] == date && all_data_for_date << r } }
+ # Slow.
+ all_data_for_date = raw_series.map{|rs| rs.detect{|r| r["Date"] == date } }
# skip if not all data available for date
- unless all_data_for_date.size == raw_series.size
+ unless all_data_for_date.compact.size == raw_series.size
puts "skipping incomplete date #{date}"
next
end
# merge array of hashes into one hash
all_data_for_date = all_data_for_date.inject({}) { |h,e| h.merge(e) }
series << all_data_for_date
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::Structures::DayFactory.build_list(series)
strategies = []
strategies << PlasticPig::Strategies::RsiClassic.new(:rsi_70)
strategies << PlasticPig::Strategies::RsiAgita.new
puts "Backtesting ..."
bt = PlasticPig::BackTester.new(head, strategies)
entries = bt.run
entries.each { |e| puts "-"*80, e.summary, "" }
puts "="*80
puts "Used data ranging from #{head.date} to #{head.last.date}"
exits = entries.select { |e| e.exit }
puts "Found #{entries.size} entries, with #{exits.size} exits."
# Unique exits are important because it demonstrates how
# often a strategy is likely to work. If a strategy returns a
# high number of entries, but a low number of unique exits, then
# it may be a sign that the exit condition may have be fluke, and
# is unlikely to be reproducable.
uniqs = exits.map{|e|e.exit.day if e.exit}.compact.uniq
puts "There were #{uniqs.size} (#{(uniqs.size / exits.size.to_f * 100).places(2)}%) unique exit dates."
|
aasmith/plastic-pig
|
21c6ba1bf0b661936f3b3d4619726b9ab9a82aa8
|
Add more variables to Day.
|
diff --git a/lib/plastic_pig/structures/day.rb b/lib/plastic_pig/structures/day.rb
index 36e6812..f307c89 100644
--- a/lib/plastic_pig/structures/day.rb
+++ b/lib/plastic_pig/structures/day.rb
@@ -1,20 +1,26 @@
module PlasticPig
module Structures
class Day
include LinkedList
- VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
+ VARS = %w(
+ date open high low close volume
+ rsi
+ sma
+ macd macd_divergence macd_signal
+ stochasticslow_signal stochasticslow_stochastic
+ )
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
end
end
diff --git a/lib/plastic_pig/structures/day_factory.rb b/lib/plastic_pig/structures/day_factory.rb
index 308487b..1e09052 100644
--- a/lib/plastic_pig/structures/day_factory.rb
+++ b/lib/plastic_pig/structures/day_factory.rb
@@ -1,33 +1,33 @@
module PlasticPig
module Structures
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
- %w(open high low close volume rsi).each do |a|
+ (Day::VARS - %w(date)).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
end
end
|
aasmith/plastic-pig
|
21f9fafdcf0377d516e0170cf87dcc510b802226
|
Generify data loading, and prefix type keys to prevent collisions.
|
diff --git a/bt.rb b/bt.rb
index 455fdfc..7d862c6 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,68 +1,101 @@
$: << "lib"
require 'plastic_pig'
-RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
-PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
+BASE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;"
+
+DATA_QUERIES = [
+ "type=quote;range=%s/json/", # price-data
+ "type=macd;range=%s/json?period1=26&period2=12&signal=9", # divergence = macd - signal,
+ # macd = MACD(26,12),
+ # signal = MACD(9)
+ "type=rsi;range=%s/json?period=14", # rsi = RSI(14)
+ "type=sma;range=%s/json?period=200", # sma = SMA(200)
+ "type=stochasticslow;range=%s/json?period=15&dperiod=5", # signal = %D(5), stochastic = %K(15)
+]
+
+URLS = DATA_QUERIES.map{|d| BASE_URL + d }
def help
puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
-price_series = PlasticPig::YahooFetcher.new(PRICE_URL % [symbol, range]).fetch
-rsi_series = PlasticPig::YahooFetcher.new(RSI_URL % [symbol, range]).fetch
+puts "Fetching ..."
+
+raw_series = URLS.map do |url|
+ series = PlasticPig::YahooFetcher.new(url % [symbol, range]).fetch
+ type = url.scan(/type=(\w+);/).to_s
+
+ unless type == "quote"
+ series.each do |row|
+ (row.keys - ["Date", type]).each do |key|
+ row["#{type}_#{key}"] = row.delete(key)
+ end
+ end
+ end
+
+ series
+end
+
+puts "Normalizing ..."
series = []
-# Load data where data occurs only in both series for a given date.
-price_series.each do |price|
- rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
+# Iterate though one data set, adding data when all series have data for that date.
+raw_series.first.each do |row|
+ date = row["Date"]
+
+ # Equiv of:
+ # all_data_for_date = raw_series.map{|rs| rs.detect{|r| r["Date"] == date } }
+ # but faster because source array is slowly deleted from, reducing search space.
+ all_data_for_date = []
+ raw_series.each{|rs| rs.delete_if{|r| r["Date"] == date && all_data_for_date << r } }
+
+ # skip if not all data available for date
+ unless all_data_for_date.size == raw_series.size
+ puts "skipping incomplete date #{date}"
+ next
+ end
- series << price.merge(rsi) if rsi
+ # merge array of hashes into one hash
+ all_data_for_date = all_data_for_date.inject({}) { |h,e| h.merge(e) }
+
+ series << all_data_for_date
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::Structures::DayFactory.build_list(series)
strategies = []
strategies << PlasticPig::Strategies::RsiClassic.new(:rsi_70)
strategies << PlasticPig::Strategies::RsiAgita.new
+puts "Backtesting ..."
+
bt = PlasticPig::BackTester.new(head, strategies)
entries = bt.run
entries.each { |e| puts "-"*80, e.summary, "" }
puts "="*80
puts "Used data ranging from #{head.date} to #{head.last.date}"
exits = entries.select { |e| e.exit }
puts "Found #{entries.size} entries, with #{exits.size} exits."
# Unique exits are important because it demonstrates how
# often a strategy is likely to work. If a strategy returns a
# high number of entries, but a low number of unique exits, then
# it may be a sign that the exit condition may have be fluke, and
# is unlikely to be reproducable.
uniqs = exits.map{|e|e.exit.day if e.exit}.compact.uniq
puts "There were #{uniqs.size} (#{(uniqs.size / exits.size.to_f * 100).places(2)}%) unique exit dates."
-__END__
-interesting:
-C most active
-EEM 6 most active, ishares emerging
-EDC 3x emerging
-QQQQ nasdaq
-QLD 2x nasdaq
-TQQQ 3x nasdaq
-TNA 3x russ 2000
-F
-
diff --git a/lib/plastic_pig/structures/day_factory.rb b/lib/plastic_pig/structures/day_factory.rb
index 63d2705..308487b 100644
--- a/lib/plastic_pig/structures/day_factory.rb
+++ b/lib/plastic_pig/structures/day_factory.rb
@@ -1,33 +1,33 @@
module PlasticPig
module Structures
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
- %w(open high low close volume rsi).each do |a|
- d.send(:"#{a}=", hash[a])
- end
+ %w(open high low close volume rsi).each do |a|
+ d.send(:"#{a}=", hash[a])
+ end
- d
+ d
end
end
end
end
end
|
aasmith/plastic-pig
|
d0a2f8ec33da156735cebebbbeddb5eaddcbc165
|
Add trading summary.
|
diff --git a/bt.rb b/bt.rb
index fc9648a..455fdfc 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,54 +1,68 @@
$: << "lib"
require 'plastic_pig'
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
def help
puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::Structures::DayFactory.build_list(series)
strategies = []
strategies << PlasticPig::Strategies::RsiClassic.new(:rsi_70)
strategies << PlasticPig::Strategies::RsiAgita.new
bt = PlasticPig::BackTester.new(head, strategies)
entries = bt.run
-entries.each { |e| puts "="*80, e.summary, "" }
+entries.each { |e| puts "-"*80, e.summary, "" }
+
+puts "="*80
+puts "Used data ranging from #{head.date} to #{head.last.date}"
+
+exits = entries.select { |e| e.exit }
+puts "Found #{entries.size} entries, with #{exits.size} exits."
+
+# Unique exits are important because it demonstrates how
+# often a strategy is likely to work. If a strategy returns a
+# high number of entries, but a low number of unique exits, then
+# it may be a sign that the exit condition may have be fluke, and
+# is unlikely to be reproducable.
+uniqs = exits.map{|e|e.exit.day if e.exit}.compact.uniq
+puts "There were #{uniqs.size} (#{(uniqs.size / exits.size.to_f * 100).places(2)}%) unique exit dates."
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
QLD 2x nasdaq
TQQQ 3x nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
2e04113711764754758df622b2fb5ac1c7699401
|
Move classes into directory structure.
|
diff --git a/bt.rb b/bt.rb
index dfd016d..fc9648a 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,323 +1,54 @@
-require 'linked_list'
+$: << "lib"
+require 'plastic_pig'
-require 'pp'
-require 'open-uri'
-require 'rubygems'
-require 'json'
-
-class ::Range
- def crossed_below?(n)
- first > n and last < n
- end
-
- def crossed_above?(n)
- first < n and last > n
- end
-end
-
-class Float
- def places(n=2)
- n = 10 ** n.to_f
- (self * n).truncate / n
- end
-end
-
-module PlasticPig
- RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
- PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
-
- class YahooFetcher
- attr_reader :url
-
- def initialize(url)
- @url = url
- end
-
- def fetch
- read_json(url)
- end
-
- def read_json(url)
- JSON.parse(fix_json(open(url).read))['series']
- end
-
- def fix_json(str)
- str.
- # remove the javascript callback around the json.
- gsub(/.*\( (.*)\)/m, '\1').chomp.
-
- # Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
- gsub(/,\s*\n\s*\}/m, "}")
- end
- end
-
- class DayFactory
- class << self
- def build_list(hashes)
- head, days = nil
-
- hashes.each do |h|
- day = build(h)
-
- # build list by linking days
- head = day unless head
- days << day if days
- days = day
- end
-
- head
- end
-
- def build(hash)
- d = Day.new
- d.date = hash["Date"]
-
- %w(open high low close volume rsi).each do |a|
- d.send(:"#{a}=", hash[a])
- end
-
- d
- end
- end
- end
-
- class Day
- include LinkedList
-
- VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
- attr_accessor *VARS
-
- def parsed_date
- @parsed_date ||= Date.parse(date.to_s)
- end
-
- def inspect
- pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
-
- "<Day: #{pairs.join(",")}>"
- end
- end
-
- class Entry
- attr_accessor :day, :reason, :exit, :strategy
-
- def price
- day.open
- end
-
- def summary
- summaries = []
-
- if day
- summaries << "Entered at start of day #{day.date} @ $#{day.open}"
- else
- summaries << "ENTER NEXT TRADING DAY AT OPEN"
- end
-
- summaries << "Reason: #{reason}"
- summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
-
- if exit
- summaries << "Exit Summary:"
- summaries << exit.summary
- else
- summaries << "No exit was generated."
- end
-
- summaries.join("\n")
- end
- end
-
- class Exit
- attr_accessor :day, :reason, :entry, :strategy
-
- def price
- day.close
- end
-
- def profit
- price - entry.price
- end
-
- def profit_percent
- profit.to_f / entry.price
- end
-
- def summary
- summary = []
-
- if day
- summary << "Exit at start of day #{day.date} @ $#{day.open};"
- else
- summary << "EXIT NEXT TRADING DAY AT OPEN"
- end
-
- summary << "Reason: #{reason}"
- summary << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
-
- summary << "Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)" if day
-
- summary.map{|s| "\t#{s}"}.join("\n")
- end
- end
-
- # Strategies
-
- class RsiClassic
- attr_accessor :exit_type
-
- EXITS = {
- :exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
- :exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
- :exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
- :rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
- :rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
- }
-
- REASONS = {
- :exp_3 => "Expired after 3 days.",
- :exp_5 => "Expired after 5 days.",
- :exp_10 => "Expired after 10 days.",
- :rsi_70 => "RSI crossed above 70",
- :rsi_40 => "RSI dropped below 40."
- }
-
- def initialize(exit_type)
- raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
-
- @exit_type = exit_type
- end
-
- def enter?(day)
- if day.previous.rsi < 55 and day.rsi > 55
- "RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
- end
- end
-
- def exit?(day, days_from_entry)
- if EXITS[exit_type].call(day, days_from_entry)
- REASONS[exit_type] + " on #{day.date}"
- end
- end
-
- def name
- "RSI Classic: #{exit_type}"
- end
- end
-
- class RsiAgita
- ENTER_RSI = [5,10,15,20,25,30,35,40]
-
- def enter?(day)
- rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
-
- if rsi
- "RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
- end
- end
-
- def exit?(day, days_from_entry)
- x = (day.previous.rsi..day.rsi).crossed_above?(65)
-
- if x
- "RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
- end
- end
- end
-end
+RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
+PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
def help
puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
-price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
-rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
+price_series = PlasticPig::YahooFetcher.new(PRICE_URL % [symbol, range]).fetch
+rsi_series = PlasticPig::YahooFetcher.new(RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
-head = PlasticPig::DayFactory.build_list(series)
-
-def find_entries(head, strategies)
- entries = []
-
- head.each do |day|
- if day.previous
- strategies.each do |strategy|
- reason = strategy.enter?(day)
-
- if reason
- entry = PlasticPig::Entry.new
- entry.strategy = strategy
- entry.reason = reason
- entry.day = day.next
-
- entries << entry
- end
- end
- end
- end
-
- entries
-end
-
-def find_exits(entries, strategies)
- entries.each do |entry|
- next unless entry.day
-
- entry.day.each_with_index do |day, i|
- strategies.each do |strategy|
- reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
-
- if reason
- x = PlasticPig::Exit.new
- x.strategy = strategy
- x.reason = reason
- x.entry = entry
- x.day = day.next
-
- entry.exit = x
- end
- end
-
- break if entry.exit
- end
- end
-end
+head = PlasticPig::Structures::DayFactory.build_list(series)
strategies = []
-strategies << PlasticPig::RsiClassic.new(:rsi_70)
-strategies << PlasticPig::RsiAgita.new
+strategies << PlasticPig::Strategies::RsiClassic.new(:rsi_70)
+strategies << PlasticPig::Strategies::RsiAgita.new
-entries = find_entries(head, strategies)
-find_exits(entries, strategies)
+bt = PlasticPig::BackTester.new(head, strategies)
+entries = bt.run
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
QLD 2x nasdaq
TQQQ 3x nasdaq
TNA 3x russ 2000
F
diff --git a/lib/plastic_pig.rb b/lib/plastic_pig.rb
new file mode 100644
index 0000000..0f46940
--- /dev/null
+++ b/lib/plastic_pig.rb
@@ -0,0 +1,14 @@
+require 'pp'
+require 'open-uri'
+require 'rubygems'
+require 'json'
+
+require 'plastic_pig/back_tester'
+require 'plastic_pig/core_ext'
+require 'plastic_pig/linked_list'
+require 'plastic_pig/structures'
+require 'plastic_pig/strategies'
+require 'plastic_pig/yahoo_fetcher'
+
+module PlasticPig
+end
diff --git a/lib/plastic_pig/back_tester.rb b/lib/plastic_pig/back_tester.rb
new file mode 100644
index 0000000..830ff6f
--- /dev/null
+++ b/lib/plastic_pig/back_tester.rb
@@ -0,0 +1,63 @@
+module PlasticPig
+ class BackTester
+ attr_accessor :series, :strategies
+
+ def initialize(series, strategies)
+ @series = series
+ @strategies = strategies
+ end
+
+ def run
+ entries = find_entries
+ find_exits(entries) # Adds exits to entries.
+ entries
+ end
+
+ def find_entries
+ entries = []
+
+ series.each do |day|
+ if day.previous
+ strategies.each do |strategy|
+ reason = strategy.enter?(day)
+
+ if reason
+ entry = PlasticPig::Structures::Entry.new
+ entry.strategy = strategy
+ entry.reason = reason
+ entry.day = day.next
+
+ entries << entry
+ end
+ end
+ end
+ end
+
+ entries
+ end
+
+ def find_exits(entries)
+ entries.each do |entry|
+ next unless entry.day
+
+ entry.day.each_with_index do |day, i|
+ strategies.each do |strategy|
+ reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
+
+ if reason
+ x = PlasticPig::Structures::Exit.new
+ x.strategy = strategy
+ x.reason = reason
+ x.entry = entry
+ x.day = day.next
+
+ entry.exit = x
+ end
+ end
+
+ break if entry.exit
+ end
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/core_ext.rb b/lib/plastic_pig/core_ext.rb
new file mode 100644
index 0000000..2b1e8d9
--- /dev/null
+++ b/lib/plastic_pig/core_ext.rb
@@ -0,0 +1,17 @@
+class ::Range
+ def crossed_below?(n)
+ first > n and last < n
+ end
+
+ def crossed_above?(n)
+ first < n and last > n
+ end
+end
+
+class Float
+ def places(n=2)
+ n = 10 ** n.to_f
+ (self * n).truncate / n
+ end
+end
+
diff --git a/linked_list.rb b/lib/plastic_pig/linked_list.rb
similarity index 100%
rename from linked_list.rb
rename to lib/plastic_pig/linked_list.rb
diff --git a/lib/plastic_pig/strategies.rb b/lib/plastic_pig/strategies.rb
new file mode 100644
index 0000000..f819f43
--- /dev/null
+++ b/lib/plastic_pig/strategies.rb
@@ -0,0 +1,2 @@
+require 'plastic_pig/strategies/rsi_agita'
+require 'plastic_pig/strategies/rsi_classic'
diff --git a/lib/plastic_pig/strategies/rsi_agita.rb b/lib/plastic_pig/strategies/rsi_agita.rb
new file mode 100644
index 0000000..12ad0c4
--- /dev/null
+++ b/lib/plastic_pig/strategies/rsi_agita.rb
@@ -0,0 +1,23 @@
+module PlasticPig
+ module Strategies
+ class RsiAgita
+ ENTER_RSI = [5,10,15,20,25,30,35,40]
+
+ def enter?(day)
+ rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
+
+ if rsi
+ "RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+
+ def exit?(day, days_from_entry)
+ x = (day.previous.rsi..day.rsi).crossed_above?(65)
+
+ if x
+ "RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/strategies/rsi_classic.rb b/lib/plastic_pig/strategies/rsi_classic.rb
new file mode 100644
index 0000000..68cc81b
--- /dev/null
+++ b/lib/plastic_pig/strategies/rsi_classic.rb
@@ -0,0 +1,45 @@
+module PlasticPig
+ module Strategies
+ class RsiClassic
+ attr_accessor :exit_type
+
+ EXITS = {
+ :exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
+ :exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
+ :exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
+ :rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
+ :rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
+ }
+
+ REASONS = {
+ :exp_3 => "Expired after 3 days.",
+ :exp_5 => "Expired after 5 days.",
+ :exp_10 => "Expired after 10 days.",
+ :rsi_70 => "RSI crossed above 70",
+ :rsi_40 => "RSI dropped below 40."
+ }
+
+ def initialize(exit_type)
+ raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
+
+ @exit_type = exit_type
+ end
+
+ def enter?(day)
+ if day.previous.rsi < 55 and day.rsi > 55
+ "RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+
+ def exit?(day, days_from_entry)
+ if EXITS[exit_type].call(day, days_from_entry)
+ REASONS[exit_type] + " on #{day.date}"
+ end
+ end
+
+ def name
+ "RSI Classic: #{exit_type}"
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/structures.rb b/lib/plastic_pig/structures.rb
new file mode 100644
index 0000000..016a88c
--- /dev/null
+++ b/lib/plastic_pig/structures.rb
@@ -0,0 +1,4 @@
+require 'plastic_pig/structures/day'
+require 'plastic_pig/structures/day_factory'
+require 'plastic_pig/structures/entry'
+require 'plastic_pig/structures/exit'
diff --git a/lib/plastic_pig/structures/day.rb b/lib/plastic_pig/structures/day.rb
new file mode 100644
index 0000000..36e6812
--- /dev/null
+++ b/lib/plastic_pig/structures/day.rb
@@ -0,0 +1,20 @@
+module PlasticPig
+ module Structures
+ class Day
+ include LinkedList
+
+ VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
+ attr_accessor *VARS
+
+ def parsed_date
+ @parsed_date ||= Date.parse(date.to_s)
+ end
+
+ def inspect
+ pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
+
+ "<Day: #{pairs.join(",")}>"
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/structures/day_factory.rb b/lib/plastic_pig/structures/day_factory.rb
new file mode 100644
index 0000000..63d2705
--- /dev/null
+++ b/lib/plastic_pig/structures/day_factory.rb
@@ -0,0 +1,33 @@
+module PlasticPig
+ module Structures
+ class DayFactory
+ class << self
+ def build_list(hashes)
+ head, days = nil
+
+ hashes.each do |h|
+ day = build(h)
+
+ # build list by linking days
+ head = day unless head
+ days << day if days
+ days = day
+ end
+
+ head
+ end
+
+ def build(hash)
+ d = Day.new
+ d.date = hash["Date"]
+
+ %w(open high low close volume rsi).each do |a|
+ d.send(:"#{a}=", hash[a])
+ end
+
+ d
+ end
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/structures/entry.rb b/lib/plastic_pig/structures/entry.rb
new file mode 100644
index 0000000..3c3ab2c
--- /dev/null
+++ b/lib/plastic_pig/structures/entry.rb
@@ -0,0 +1,33 @@
+module PlasticPig
+ module Structures
+ class Entry
+ attr_accessor :day, :reason, :exit, :strategy
+
+ def price
+ day.open
+ end
+
+ def summary
+ summaries = []
+
+ if day
+ summaries << "Entered at start of day #{day.date} @ $#{day.open}"
+ else
+ summaries << "ENTER NEXT TRADING DAY AT OPEN"
+ end
+
+ summaries << "Reason: #{reason}"
+ summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
+
+ if exit
+ summaries << "Exit Summary:"
+ summaries << exit.summary
+ else
+ summaries << "No exit was generated."
+ end
+
+ summaries.join("\n")
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/structures/exit.rb b/lib/plastic_pig/structures/exit.rb
new file mode 100644
index 0000000..b14139d
--- /dev/null
+++ b/lib/plastic_pig/structures/exit.rb
@@ -0,0 +1,36 @@
+module PlasticPig
+ module Structures
+ class Exit
+ attr_accessor :day, :reason, :entry, :strategy
+
+ def price
+ day.close
+ end
+
+ def profit
+ price - entry.price
+ end
+
+ def profit_percent
+ profit.to_f / entry.price
+ end
+
+ def summary
+ summary = []
+
+ if day
+ summary << "Exit at start of day #{day.date} @ $#{day.open};"
+ else
+ summary << "EXIT NEXT TRADING DAY AT OPEN"
+ end
+
+ summary << "Reason: #{reason}"
+ summary << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
+
+ summary << "Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)" if day
+
+ summary.map{|s| "\t#{s}"}.join("\n")
+ end
+ end
+ end
+end
diff --git a/lib/plastic_pig/yahoo_fetcher.rb b/lib/plastic_pig/yahoo_fetcher.rb
new file mode 100644
index 0000000..f7001f5
--- /dev/null
+++ b/lib/plastic_pig/yahoo_fetcher.rb
@@ -0,0 +1,26 @@
+module PlasticPig
+ class YahooFetcher
+ attr_reader :url
+
+ def initialize(url)
+ @url = url
+ end
+
+ def fetch
+ read_json(url)
+ end
+
+ def read_json(url)
+ JSON.parse(fix_json(open(url).read))['series']
+ end
+
+ def fix_json(str)
+ str.
+ # remove the javascript callback around the json.
+ gsub(/.*\( (.*)\)/m, '\1').chomp.
+
+ # Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
+ gsub(/,\s*\n\s*\}/m, "}")
+ end
+ end
+end
|
aasmith/plastic-pig
|
5fa24e3b702a49d14985fcd62f0d678ee97b83cf
|
Add README.
|
diff --git a/README b/README
new file mode 100644
index 0000000..5402cb7
--- /dev/null
+++ b/README
@@ -0,0 +1,15 @@
+Backtester, Copyright Andrew A. Smith, 2010.
+
+SYNOPSIS
+ ruby bt.rb symbol [-h] [-r range] [-m max_date]
+
+DESCRIPTION
+ Backtests a stock symbol against a predefined set of trading
+ strategies.
+
+OPTIONS
+ -h Display this message.
+ -m Process series up to and including specified max_date.
+ -r Load series data using the specified range. Valid
+ values are 5d 3m 6m 1y 2y 5y. Default is 1y.
+
diff --git a/bt.rb b/bt.rb
index 9ce1480..dfd016d 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,339 +1,323 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
summary = []
if day
summary << "Exit at start of day #{day.date} @ $#{day.open};"
else
summary << "EXIT NEXT TRADING DAY AT OPEN"
end
summary << "Reason: #{reason}"
summary << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
summary << "Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)" if day
summary.map{|s| "\t#{s}"}.join("\n")
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
if EXITS[exit_type].call(day, days_from_entry)
REASONS[exit_type] + " on #{day.date}"
end
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
def help
- puts <<-HELP
-Backtester, Copyright Andrew A. Smith, 2010.
-
-SYNOPSIS
- ruby bt.rb symbol [-h] [-r range] [-m max_date]
-
-DESCRIPTION
- Backtests a stock symbol against a predefined set of trading
- strategies.
-
-OPTIONS
- -h\tDisplay this message.
- -m\tProcess series up to and including specified max_date.
- -r\tLoad series data using the specified range. Valid
- \tvalues are 5d 3m 6m 1y 2y 5y. Default is 1y.
-
- HELP
+ puts File.read("README")
abort
end
help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
args = ARGV.join(" ")
max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::DayFactory.build_list(series)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day.next
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
QLD 2x nasdaq
TQQQ 3x nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
00938cfa7a52e1daa0c114ed7dff441274d769c9
|
Cleaning up args.
|
diff --git a/bt.rb b/bt.rb
index c2143f0..9ce1480 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,315 +1,339 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
summary = []
if day
summary << "Exit at start of day #{day.date} @ $#{day.open};"
else
summary << "EXIT NEXT TRADING DAY AT OPEN"
end
summary << "Reason: #{reason}"
summary << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
summary << "Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)" if day
summary.map{|s| "\t#{s}"}.join("\n")
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
if EXITS[exit_type].call(day, days_from_entry)
REASONS[exit_type] + " on #{day.date}"
end
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
+def help
+ puts <<-HELP
+Backtester, Copyright Andrew A. Smith, 2010.
+
+SYNOPSIS
+ ruby bt.rb symbol [-h] [-r range] [-m max_date]
+
+DESCRIPTION
+ Backtests a stock symbol against a predefined set of trading
+ strategies.
+
+OPTIONS
+ -h\tDisplay this message.
+ -m\tProcess series up to and including specified max_date.
+ -r\tLoad series data using the specified range. Valid
+ \tvalues are 5d 3m 6m 1y 2y 5y. Default is 1y.
+
+ HELP
+ abort
+end
+
+help if ARGV.any?{|e|e =~ /^-h$/ }
symbol = ARGV[0] or raise "need symbol"
-max_date = ARGV.select{|e|e =~ /-m(\d+)/} && $1
-range = ARGV.select{|e|e =~ /-r(\d+\w)/} && $1 || "1y"
+
+args = ARGV.join(" ")
+max_date = args.select{ |e| e =~ /-m (\d+)/} && $1
+range = args.select{ |e| e =~ /-r (\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::DayFactory.build_list(series)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day.next
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
QLD 2x nasdaq
TQQQ 3x nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
2549d6c087bec1d6e6836c25a7a8da9eb75a9abf
|
Handles cases where the exit trigger occurs on the last day of the series.
|
diff --git a/bt.rb b/bt.rb
index 2207660..c2143f0 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,305 +1,315 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
- <<-SUMMARY
- Exit at end of day #{day.date} @ $#{day.close};
- Reason: #{reason}
- Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
- Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
- SUMMARY
+ summary = []
+
+ if day
+ summary << "Exit at start of day #{day.date} @ $#{day.open};"
+ else
+ summary << "EXIT NEXT TRADING DAY AT OPEN"
+ end
+
+ summary << "Reason: #{reason}"
+ summary << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
+
+ summary << "Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)" if day
+
+ summary.map{|s| "\t#{s}"}.join("\n")
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
- REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
+ if EXITS[exit_type].call(day, days_from_entry)
+ REASONS[exit_type] + " on #{day.date}"
+ end
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
max_date = ARGV.select{|e|e =~ /-m(\d+)/} && $1
range = ARGV.select{|e|e =~ /-r(\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::DayFactory.build_list(series)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
- x.day = day
+ x.day = day.next
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
QLD 2x nasdaq
TQQQ 3x nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
519ce311a8b7c4260b3b209b0feeac5c80d42a22
|
Add comments.
|
diff --git a/bt.rb b/bt.rb
index 78ab660..2207660 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,303 +1,305 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
max_date = ARGV.select{|e|e =~ /-m(\d+)/} && $1
range = ARGV.select{|e|e =~ /-r(\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
series = []
# Load data where data occurs only in both series for a given date.
price_series.each do |price|
rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
series << price.merge(rsi) if rsi
end
series.reject!{|s| s["Date"] > max_date.to_i } if max_date
head = PlasticPig::DayFactory.build_list(series)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
+QLD 2x nasdaq
+TQQQ 3x nasdaq
TNA 3x russ 2000
F
diff --git a/linked_list.rb b/linked_list.rb
index dc5566f..141eb50 100644
--- a/linked_list.rb
+++ b/linked_list.rb
@@ -1,94 +1,96 @@
+# Linked list implementation Copyright 2008 Aaron Patterson and Andrew Smith.
+
module PlasticPig
module LinkedList
include Enumerable
attr_writer :previous
attr_writer :next
def next n = nil
@next ||= nil
return @next unless n
list = []
current_node = self
n.times {
current_node = current_node.next
list << current_node
}
list
end
def previous n = nil
@previous ||= nil
return @previous unless n
list = []
current_node = self
n.times {
current_node = current_node.previous
list << current_node
}
list.reverse
end
def ago n
node = self
n.times {
node = node.previous
return nil unless node
}
node
end
def ahead n
node = self
n.times {
node = node.next
return nil unless node
}
node
end
def << next_node
next_node.previous = self
self.next = next_node
next_node
end
def slice!(start, length)
head = ahead(start)
head.previous = nil
tail = head
(length - 1).times { tail = tail.next }
tail.next = nil
head
end
def first
current_node = self
loop {
return current_node unless current_node.previous
current_node = current_node.previous
}
end
def last
current_node = self
loop {
return current_node unless current_node.next
current_node = current_node.next
}
end
def each &block
current = self
begin
block.call(current)
end while(current = current.next)
end
def length
i = 0
first.each { |n| i += 1 }
i
end
end
end
|
aasmith/plastic-pig
|
8375ac2bbf785e000a54fbc17d2dfed2ad8c5355
|
Simplify data loading and always force series alignment.
|
diff --git a/bt.rb b/bt.rb
index 5a71003..78ab660 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,308 +1,303 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
max_date = ARGV.select{|e|e =~ /-m(\d+)/} && $1
range = ARGV.select{|e|e =~ /-r(\d+\w)/} && $1 || "1y"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
-if max_date
- [rsi_series, price_series].each{ |a| a.reject!{|s| s["Date"] > max_date.to_i } }
-end
+series = []
-prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
- if max_date
- next if !price || !rsi
- else
- unless price["Date"] == rsi["Date"]
- raise "Loading error, series do not align on dates. #{price["Date"]} v #{rsi["Date"]}"
- end
- end
+# Load data where data occurs only in both series for a given date.
+price_series.each do |price|
+ rsi = rsi_series.detect { |rsi| price["Date"] == rsi["Date"] }
+
+ series << price.merge(rsi) if rsi
+end
- price.merge(rsi)
-end.compact
+series.reject!{|s| s["Date"] > max_date.to_i } if max_date
-head = PlasticPig::DayFactory.build_list(prices_and_rsi)
+head = PlasticPig::DayFactory.build_list(series)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
c35e2860d065b7ad24aa95f5e457bcfec5b8d25e
|
Allow a custom range to be specified.
|
diff --git a/bt.rb b/bt.rb
index e66d774..5a71003 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,307 +1,308 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
- RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
- PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
+ RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=%s/json?period=14"
+ PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=%s/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
if day
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
else
summaries << "ENTER NEXT TRADING DAY AT OPEN"
end
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
-max_date = ARGV[1]
+max_date = ARGV.select{|e|e =~ /-m(\d+)/} && $1
+range = ARGV.select{|e|e =~ /-r(\d+\w)/} && $1 || "1y"
-price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
-rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
+price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % [symbol, range]).fetch
+rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % [symbol, range]).fetch
if max_date
[rsi_series, price_series].each{ |a| a.reject!{|s| s["Date"] > max_date.to_i } }
end
prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
if max_date
next if !price || !rsi
else
unless price["Date"] == rsi["Date"]
raise "Loading error, series do not align on dates. #{price["Date"]} v #{rsi["Date"]}"
end
end
price.merge(rsi)
end.compact
head = PlasticPig::DayFactory.build_list(prices_and_rsi)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
next unless entry.day
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
1b508a82c3c4d3597099cdc6d851ecbb1a171d25
|
Handle cases where the next day is not available.
|
diff --git a/bt.rb b/bt.rb
index 263aec9..e66d774 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,300 +1,307 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
class Float
def places(n=2)
n = 10 ** n.to_f
(self * n).truncate / n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
- summaries << "Entered at start of day #{day.date} @ $#{day.open}"
+ if day
+ summaries << "Entered at start of day #{day.date} @ $#{day.open}"
+ else
+ summaries << "ENTER NEXT TRADING DAY AT OPEN"
+ end
+
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def profit_percent
profit.to_f / entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
max_date = ARGV[1]
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
if max_date
[rsi_series, price_series].each{ |a| a.reject!{|s| s["Date"] > max_date.to_i } }
end
prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
if max_date
next if !price || !rsi
else
unless price["Date"] == rsi["Date"]
raise "Loading error, series do not align on dates. #{price["Date"]} v #{rsi["Date"]}"
end
end
price.merge(rsi)
end.compact
head = PlasticPig::DayFactory.build_list(prices_and_rsi)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
+ next unless entry.day
+
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
2da75ff9bdcf286469885d9ebd71bfcfcda90375
|
Add percentage and cleaner formatting.
|
diff --git a/bt.rb b/bt.rb
index c833f40..263aec9 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,289 +1,300 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
+class Float
+ def places(n=2)
+ n = 10 ** n.to_f
+ (self * n).truncate / n
+ end
+end
+
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
+ def profit_percent
+ profit.to_f / entry.price
+ end
+
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
- Profit: $#{profit}
+ Profit: $#{profit.places(2)} (#{(profit_percent * 100).places(2)}%)
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
max_date = ARGV[1]
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
if max_date
[rsi_series, price_series].each{ |a| a.reject!{|s| s["Date"] > max_date.to_i } }
end
prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
if max_date
next if !price || !rsi
else
unless price["Date"] == rsi["Date"]
raise "Loading error, series do not align on dates. #{price["Date"]} v #{rsi["Date"]}"
end
end
price.merge(rsi)
end.compact
head = PlasticPig::DayFactory.build_list(prices_and_rsi)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
21bce9b6de035f03dc3790926e25c05d90801398
|
Add max date trimming
|
diff --git a/bt.rb b/bt.rb
index 405c612..c833f40 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,280 +1,289 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
class ::Range
def crossed_below?(n)
first > n and last < n
end
def crossed_above?(n)
first < n and last > n
end
end
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
summaries << "Reason: #{reason}"
summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
if exit
summaries << "Exit Summary:"
summaries << exit.summary
else
summaries << "No exit was generated."
end
summaries.join("\n")
end
end
class Exit
attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit}
SUMMARY
end
end
# Strategies
class RsiClassic
attr_accessor :exit_type
EXITS = {
:exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
:exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
:exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
:rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
:rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
}
REASONS = {
:exp_3 => "Expired after 3 days.",
:exp_5 => "Expired after 5 days.",
:exp_10 => "Expired after 10 days.",
:rsi_70 => "RSI crossed above 70",
:rsi_40 => "RSI dropped below 40."
}
def initialize(exit_type)
raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
@exit_type = exit_type
end
def enter?(day)
if day.previous.rsi < 55 and day.rsi > 55
"RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
end
def name
"RSI Classic: #{exit_type}"
end
end
class RsiAgita
ENTER_RSI = [5,10,15,20,25,30,35,40]
def enter?(day)
rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
if rsi
"RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
def exit?(day, days_from_entry)
x = (day.previous.rsi..day.rsi).crossed_above?(65)
if x
"RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
end
end
end
end
symbol = ARGV[0] or raise "need symbol"
+max_date = ARGV[1]
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
+if max_date
+ [rsi_series, price_series].each{ |a| a.reject!{|s| s["Date"] > max_date.to_i } }
+end
+
prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
- unless price["Date"] == rsi["Date"]
- raise "Loading error, series do not align on dates."
+ if max_date
+ next if !price || !rsi
+ else
+ unless price["Date"] == rsi["Date"]
+ raise "Loading error, series do not align on dates. #{price["Date"]} v #{rsi["Date"]}"
+ end
end
price.merge(rsi)
-end
+end.compact
head = PlasticPig::DayFactory.build_list(prices_and_rsi)
def find_entries(head, strategies)
entries = []
head.each do |day|
if day.previous
strategies.each do |strategy|
reason = strategy.enter?(day)
if reason
entry = PlasticPig::Entry.new
entry.strategy = strategy
entry.reason = reason
entry.day = day.next
entries << entry
end
end
end
end
entries
end
def find_exits(entries, strategies)
entries.each do |entry|
entry.day.each_with_index do |day, i|
strategies.each do |strategy|
reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
if reason
x = PlasticPig::Exit.new
x.strategy = strategy
x.reason = reason
x.entry = entry
x.day = day
entry.exit = x
end
end
break if entry.exit
end
end
end
strategies = []
strategies << PlasticPig::RsiClassic.new(:rsi_70)
strategies << PlasticPig::RsiAgita.new
entries = find_entries(head, strategies)
find_exits(entries, strategies)
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
82ffba45b54146f11c494b5a45020697a4030f50
|
Add more strategies, allow only one exit per strategy.
|
diff --git a/bt.rb b/bt.rb
index 0b983e4..405c612 100644
--- a/bt.rb
+++ b/bt.rb
@@ -1,208 +1,280 @@
require 'linked_list'
require 'pp'
require 'open-uri'
require 'rubygems'
require 'json'
+class ::Range
+ def crossed_below?(n)
+ first > n and last < n
+ end
+
+ def crossed_above?(n)
+ first < n and last > n
+ end
+end
+
module PlasticPig
RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
class YahooFetcher
attr_reader :url
def initialize(url)
@url = url
end
def fetch
read_json(url)
end
def read_json(url)
JSON.parse(fix_json(open(url).read))['series']
end
def fix_json(str)
str.
# remove the javascript callback around the json.
gsub(/.*\( (.*)\)/m, '\1').chomp.
# Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
gsub(/,\s*\n\s*\}/m, "}")
end
end
class DayFactory
class << self
def build_list(hashes)
head, days = nil
hashes.each do |h|
day = build(h)
# build list by linking days
head = day unless head
days << day if days
days = day
end
head
end
def build(hash)
d = Day.new
d.date = hash["Date"]
%w(open high low close volume rsi).each do |a|
d.send(:"#{a}=", hash[a])
end
d
end
end
end
class Day
include LinkedList
VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
attr_accessor *VARS
def parsed_date
@parsed_date ||= Date.parse(date.to_s)
end
def inspect
pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
"<Day: #{pairs.join(",")}>"
end
end
class Entry
- attr_accessor :day, :reason, :exits
-
- def initialize
- @exits = []
- end
+ attr_accessor :day, :reason, :exit, :strategy
def price
day.open
end
def summary
summaries = []
summaries << "Entered at start of day #{day.date} @ $#{day.open}"
summaries << "Reason: #{reason}"
- summaries << "Entry generated #{exits.size} exits:"
- exits.each { |x| summaries << x.summary }
+ summaries << "Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}"
+
+ if exit
+ summaries << "Exit Summary:"
+ summaries << exit.summary
+ else
+ summaries << "No exit was generated."
+ end
summaries.join("\n")
end
end
class Exit
- attr_accessor :day, :reason, :entry
+ attr_accessor :day, :reason, :entry, :strategy
def price
day.close
end
def profit
price - entry.price
end
def summary
<<-SUMMARY
Exit at end of day #{day.date} @ $#{day.close};
Reason: #{reason}
+ Strategy: #{strategy.respond_to?(:name) ? strategy.name : strategy.class.name}
Profit: $#{profit}
SUMMARY
end
end
+
+ # Strategies
+
+ class RsiClassic
+ attr_accessor :exit_type
+
+ EXITS = {
+ :exp_3 => lambda { |day, days_from_entry| days_from_entry == 3 },
+ :exp_5 => lambda { |day, days_from_entry| days_from_entry == 5 },
+ :exp_10 => lambda { |day, days_from_entry| days_from_entry == 10 },
+ :rsi_70 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_above?(70) },
+ :rsi_40 => lambda { |day, days_from_entry| (day.previous.rsi..day.rsi).crossed_below?(40) }
+ }
+
+ REASONS = {
+ :exp_3 => "Expired after 3 days.",
+ :exp_5 => "Expired after 5 days.",
+ :exp_10 => "Expired after 10 days.",
+ :rsi_70 => "RSI crossed above 70",
+ :rsi_40 => "RSI dropped below 40."
+ }
+
+ def initialize(exit_type)
+ raise "invalid exit_type #{exit_type.inspect}" unless EXITS.include?(exit_type)
+
+ @exit_type = exit_type
+ end
+
+ def enter?(day)
+ if day.previous.rsi < 55 and day.rsi > 55
+ "RSI crossed above 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+
+ def exit?(day, days_from_entry)
+ REASONS[exit_type] if EXITS[exit_type].call(day, days_from_entry)
+ end
+
+ def name
+ "RSI Classic: #{exit_type}"
+ end
+ end
+
+ class RsiAgita
+ ENTER_RSI = [5,10,15,20,25,30,35,40]
+
+ def enter?(day)
+ rsi = ENTER_RSI.detect { |n| (day.previous.rsi..day.rsi).crossed_below?(n) }
+
+ if rsi
+ "RSI crossed below #{rsi} from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+
+ def exit?(day, days_from_entry)
+ x = (day.previous.rsi..day.rsi).crossed_above?(65)
+
+ if x
+ "RSI crossed above 65 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ end
+ end
+ end
end
symbol = ARGV[0] or raise "need symbol"
price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
unless price["Date"] == rsi["Date"]
raise "Loading error, series do not align on dates."
end
price.merge(rsi)
end
head = PlasticPig::DayFactory.build_list(prices_and_rsi)
-#head.each { |d| puts d.inspect }
+def find_entries(head, strategies)
+ entries = []
-entries = []
+ head.each do |day|
+ if day.previous
+ strategies.each do |strategy|
+ reason = strategy.enter?(day)
-head.each do |day|
- if day.previous
- if day.previous.rsi < 55 and day.rsi > 55
- entry = PlasticPig::Entry.new
- entry.reason = "RSI crossed 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
- entry.day = day.next
+ if reason
+ entry = PlasticPig::Entry.new
+ entry.strategy = strategy
+ entry.reason = reason
+ entry.day = day.next
- entries << entry
+ entries << entry
+ end
+ end
end
end
-end
-
-entries.each do |entry|
- low_rsi, high_rsi = false
- entry.day.each_with_index do |day,i|
-
- # pick off the 3rd, 5th and 10th days
- if [2,4,9].include?(i)
- x = PlasticPig::Exit.new
- x.day = day
- x.reason = "Expired after #{i+1} days"
- x.entry = entry
-
- entry.exits << x
- end
+ entries
+end
- # find days when the rsi moved > 70 or < 40.
- if day.rsi < 40 && !low_rsi
- x = PlasticPig::Exit.new
- x.day = day
- x.reason = "RSI dropped to below 40"
- x.entry = entry
+def find_exits(entries, strategies)
+ entries.each do |entry|
+ entry.day.each_with_index do |day, i|
+ strategies.each do |strategy|
+ reason = entry.strategy == strategy && strategy.exit?(day, i + 1)
- entry.exits << x
- low_rsi = true
+ if reason
+ x = PlasticPig::Exit.new
+ x.strategy = strategy
+ x.reason = reason
+ x.entry = entry
+ x.day = day
- elsif day.rsi > 70 && !high_rsi
- x = PlasticPig::Exit.new
- x.day = day
- x.reason = "RSI rose above 70"
- x.entry = entry
+ entry.exit = x
+ end
+ end
- entry.exits << x
- high_rsi = true
+ break if entry.exit
end
-
- break if i >= 9 && high_rsi && low_rsi
end
end
+strategies = []
+strategies << PlasticPig::RsiClassic.new(:rsi_70)
+strategies << PlasticPig::RsiAgita.new
+
+entries = find_entries(head, strategies)
+find_exits(entries, strategies)
+
entries.each { |e| puts "="*80, e.summary, "" }
__END__
interesting:
C most active
EEM 6 most active, ishares emerging
EDC 3x emerging
QQQQ nasdaq
TNA 3x russ 2000
F
|
aasmith/plastic-pig
|
74d6fff978c3ae15bd95651a1583f87ff53768b5
|
Basic back tester with initial strategy
|
diff --git a/bt.rb b/bt.rb
new file mode 100644
index 0000000..0b983e4
--- /dev/null
+++ b/bt.rb
@@ -0,0 +1,208 @@
+require 'linked_list'
+
+require 'pp'
+require 'open-uri'
+require 'rubygems'
+require 'json'
+
+module PlasticPig
+ RSI_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=rsi;range=1y/json?period=14"
+ PRICE_URL = "http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;range=1y/json/"
+
+ class YahooFetcher
+ attr_reader :url
+
+ def initialize(url)
+ @url = url
+ end
+
+ def fetch
+ read_json(url)
+ end
+
+ def read_json(url)
+ JSON.parse(fix_json(open(url).read))['series']
+ end
+
+ def fix_json(str)
+ str.
+ # remove the javascript callback around the json.
+ gsub(/.*\( (.*)\)/m, '\1').chomp.
+
+ # Yahoo!'s json has an extra (invalid) comma before the closing bracket in the meta entry.
+ gsub(/,\s*\n\s*\}/m, "}")
+ end
+ end
+
+ class DayFactory
+ class << self
+ def build_list(hashes)
+ head, days = nil
+
+ hashes.each do |h|
+ day = build(h)
+
+ # build list by linking days
+ head = day unless head
+ days << day if days
+ days = day
+ end
+
+ head
+ end
+
+ def build(hash)
+ d = Day.new
+ d.date = hash["Date"]
+
+ %w(open high low close volume rsi).each do |a|
+ d.send(:"#{a}=", hash[a])
+ end
+
+ d
+ end
+ end
+ end
+
+ class Day
+ include LinkedList
+
+ VARS = [:date, :open, :high, :low, :close, :volume, :rsi]
+ attr_accessor *VARS
+
+ def parsed_date
+ @parsed_date ||= Date.parse(date.to_s)
+ end
+
+ def inspect
+ pairs = VARS.map{|v| "#{v}=#{send(v.to_sym).inspect}" }
+
+ "<Day: #{pairs.join(",")}>"
+ end
+ end
+
+ class Entry
+ attr_accessor :day, :reason, :exits
+
+ def initialize
+ @exits = []
+ end
+
+ def price
+ day.open
+ end
+
+ def summary
+ summaries = []
+
+ summaries << "Entered at start of day #{day.date} @ $#{day.open}"
+ summaries << "Reason: #{reason}"
+ summaries << "Entry generated #{exits.size} exits:"
+ exits.each { |x| summaries << x.summary }
+
+ summaries.join("\n")
+ end
+ end
+
+ class Exit
+ attr_accessor :day, :reason, :entry
+
+ def price
+ day.close
+ end
+
+ def profit
+ price - entry.price
+ end
+
+ def summary
+ <<-SUMMARY
+ Exit at end of day #{day.date} @ $#{day.close};
+ Reason: #{reason}
+ Profit: $#{profit}
+ SUMMARY
+ end
+ end
+end
+
+symbol = ARGV[0] or raise "need symbol"
+
+price_series = PlasticPig::YahooFetcher.new(PlasticPig::PRICE_URL % symbol).fetch
+rsi_series = PlasticPig::YahooFetcher.new(PlasticPig::RSI_URL % symbol).fetch
+
+prices_and_rsi = price_series.zip(rsi_series).map do |price, rsi|
+ unless price["Date"] == rsi["Date"]
+ raise "Loading error, series do not align on dates."
+ end
+
+ price.merge(rsi)
+end
+
+head = PlasticPig::DayFactory.build_list(prices_and_rsi)
+
+#head.each { |d| puts d.inspect }
+
+entries = []
+
+head.each do |day|
+ if day.previous
+ if day.previous.rsi < 55 and day.rsi > 55
+ entry = PlasticPig::Entry.new
+ entry.reason = "RSI crossed 55 from #{day.previous.rsi} to #{day.rsi} on #{day.date}"
+ entry.day = day.next
+
+ entries << entry
+ end
+ end
+end
+
+entries.each do |entry|
+ low_rsi, high_rsi = false
+
+ entry.day.each_with_index do |day,i|
+
+ # pick off the 3rd, 5th and 10th days
+ if [2,4,9].include?(i)
+ x = PlasticPig::Exit.new
+ x.day = day
+ x.reason = "Expired after #{i+1} days"
+ x.entry = entry
+
+ entry.exits << x
+ end
+
+ # find days when the rsi moved > 70 or < 40.
+ if day.rsi < 40 && !low_rsi
+ x = PlasticPig::Exit.new
+ x.day = day
+ x.reason = "RSI dropped to below 40"
+ x.entry = entry
+
+ entry.exits << x
+ low_rsi = true
+
+ elsif day.rsi > 70 && !high_rsi
+ x = PlasticPig::Exit.new
+ x.day = day
+ x.reason = "RSI rose above 70"
+ x.entry = entry
+
+ entry.exits << x
+ high_rsi = true
+ end
+
+ break if i >= 9 && high_rsi && low_rsi
+ end
+end
+
+entries.each { |e| puts "="*80, e.summary, "" }
+
+__END__
+interesting:
+C most active
+EEM 6 most active, ishares emerging
+EDC 3x emerging
+QQQQ nasdaq
+TNA 3x russ 2000
+F
+
diff --git a/linked_list.rb b/linked_list.rb
new file mode 100644
index 0000000..dc5566f
--- /dev/null
+++ b/linked_list.rb
@@ -0,0 +1,94 @@
+module PlasticPig
+ module LinkedList
+ include Enumerable
+
+ attr_writer :previous
+ attr_writer :next
+
+ def next n = nil
+ @next ||= nil
+ return @next unless n
+ list = []
+ current_node = self
+ n.times {
+ current_node = current_node.next
+ list << current_node
+ }
+ list
+ end
+
+ def previous n = nil
+ @previous ||= nil
+ return @previous unless n
+ list = []
+ current_node = self
+ n.times {
+ current_node = current_node.previous
+ list << current_node
+ }
+ list.reverse
+ end
+
+ def ago n
+ node = self
+ n.times {
+ node = node.previous
+ return nil unless node
+ }
+ node
+ end
+
+ def ahead n
+ node = self
+ n.times {
+ node = node.next
+ return nil unless node
+ }
+ node
+ end
+
+ def << next_node
+ next_node.previous = self
+ self.next = next_node
+ next_node
+ end
+
+ def slice!(start, length)
+ head = ahead(start)
+ head.previous = nil
+ tail = head
+ (length - 1).times { tail = tail.next }
+ tail.next = nil
+ head
+ end
+
+ def first
+ current_node = self
+ loop {
+ return current_node unless current_node.previous
+ current_node = current_node.previous
+ }
+ end
+
+ def last
+ current_node = self
+ loop {
+ return current_node unless current_node.next
+ current_node = current_node.next
+ }
+ end
+
+ def each &block
+ current = self
+ begin
+ block.call(current)
+ end while(current = current.next)
+ end
+
+ def length
+ i = 0
+ first.each { |n| i += 1 }
+ i
+ end
+ end
+end
|
xdissent/monowave-eagle
|
2299ae4f3ae5c78942fa44721c8fda36b3395871
|
Saving state before reinstall
|
diff --git a/Libraries/Charge Pump Voltage Convertors.lbr b/Libraries/Charge Pump Voltage Convertors.lbr
new file mode 100644
index 0000000..fc79a1c
Binary files /dev/null and b/Libraries/Charge Pump Voltage Convertors.lbr differ
diff --git a/Libraries/Supply.lbr b/Libraries/Supply.lbr
index 25dff70..99feee7 100644
Binary files a/Libraries/Supply.lbr and b/Libraries/Supply.lbr differ
diff --git a/Libraries/Tubes.lbr b/Libraries/Tubes.lbr
new file mode 100644
index 0000000..2f22105
Binary files /dev/null and b/Libraries/Tubes.lbr differ
diff --git a/Projects/Bell 5630/Bell 5630.sch b/Projects/Bell 5630/Bell 5630.sch
new file mode 100644
index 0000000..cfcf0ff
Binary files /dev/null and b/Projects/Bell 5630/Bell 5630.sch differ
diff --git a/Projects/Bell 5630/Phase Inverter.cir b/Projects/Bell 5630/Phase Inverter.cir
new file mode 100644
index 0000000..544fa84
--- /dev/null
+++ b/Projects/Bell 5630/Phase Inverter.cir
@@ -0,0 +1,40 @@
+Phase Inverter
+.CONTROL
+run
+.ENDC
+.SUBCKT 12AX7 A G K
+Bca ca 0 V=45+V(A,K)+95.43*V(G,K)
+Bre re 0 V=URAMP(V(A,K)/5)-URAMP(V(A,K)/5-1)
+Baa A K I=V(re)*1.147E-6*(URAMP(V(ca))^1.5)
+Bgg G K I=5E-6*(URAMP(V(G,K)+0.2)^1.5)
+Cgk G K 1.6P
+Cgp G A 1.7P
+Cpk A K 0.46P
+.ENDS
+CC1 AFAMPIN VR1AG 50nF
+CC2 VR1AA VR1BG 50nF
+CC3 N$7 0 50uF
+CC4 VR1BA PHASEINVOUT1 50nF
+CC5 N$9 PHASEINVOUT2 50nF
+.TRAN 1us 100ms
+.CONTROL
+plot AFAMPIN VR1BG PHASEINVOUT1 PHASEINVOUT2
+.ENDC
+.TRAN 1uS 100mS
+.CONTROL
+plot VR1BA VR1BK
+.ENDC
+RR1 VR1AA VCC 1Meg
+RR2 VR1BA VCC 270k
+RR3 0 VR1AK 5.6k
+RR4 N$9 VR1BK 5.1k
+RR5 0 VR1AG 1Meg
+RR6 N$9 VR1BG 1.2Meg
+RR7 0 N$9 270k
+RR8 N$7 VR1AK 270
+RR9 0 PHASEINVOUT2 220k
+RR10 0 PHASEINVOUT1 220k
+XVR1A VR1AA VR1AG VR1AK 12AX7
+XVR1B VR1AA VR1AG VR1AK 12AX7
+VVSIN1 AFAMPIN 0 AC 1 SIN(0 0.00001V 1kHz)
+VCC VCC 0 DC 340V
diff --git a/Projects/Bell 5630/Phase Inverter.sch b/Projects/Bell 5630/Phase Inverter.sch
new file mode 100644
index 0000000..bda9684
Binary files /dev/null and b/Projects/Bell 5630/Phase Inverter.sch differ
diff --git a/Projects/Bell 5630/eagle.epf b/Projects/Bell 5630/eagle.epf
new file mode 100644
index 0000000..514eb25
--- /dev/null
+++ b/Projects/Bell 5630/eagle.epf
@@ -0,0 +1,25 @@
+[Eagle]
+Version="05 10 00"
+Platform="Windows"
+Serial="7D07E7847B-LSR-WLM-NCP"
+Globals="Globals"
+Desktop="Desktop"
+
+[Globals]
+AutoSaveProject=1
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Frames.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Supply.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Tubes.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
+
+[Win_1]
+Type="Control Panel"
+Loc="44 192 643 628"
+State=2
+Number=0
+
+[Desktop]
+Screen="1920 1174"
+Window="Win_1"
diff --git a/Projects/JCM800/Lead MV.cir b/Projects/JCM800/Lead MV.cir
new file mode 100644
index 0000000..1755c84
--- /dev/null
+++ b/Projects/JCM800/Lead MV.cir
@@ -0,0 +1,55 @@
+Lead MV
+.CONTROL
+run
+.ENDC
+.SUBCKT 12AX7 A G K
+Bca ca 0 V=45+V(A,K)+95.43*V(G,K)
+Bre re 0 V=URAMP(V(A,K)/5)-URAMP(V(A,K)/5-1)
+Baa A K I=V(re)*1.147E-6*(URAMP(V(ca))^1.5)
+Bgg G K I=5E-6*(URAMP(V(G,K)+0.2)^1.5)
+Cgk G K 1.6P
+Cgp G A 1.7P
+Cpk A K 0.46P
+.ENDS
+.SUBCKT 12AX7 A G K
+Bca ca 0 V=45+V(A,K)+95.43*V(G,K)
+Bre re 0 V=URAMP(V(A,K)/5)-URAMP(V(A,K)/5-1)
+Baa A K I=V(re)*1.147E-6*(URAMP(V(ca))^1.5)
+Bgg G K I=5E-6*(URAMP(V(G,K)+0.2)^1.5)
+Cgk G K 1.6P
+Cgp G A 1.7P
+Cpk A K 0.46P
+.ENDS
+CC1 N$3 0 680nF
+CC2 N$4 N$11 22nF
+CC3 N$11 N$5 470pF
+CC4 N$5 IN2 1nF
+CC5 N$8 N$10 22nf
+CC6 N$10 IN3 470pF
+CC7 OUT ROUT 22nF
+.TRAN 1us 100ms
+.CONTROL
+plot IN IN2 IN3 ROUT
+.ENDC
+RR1 0 IN 1Meg
+RR2 IN N$1 68k
+RR3 0 N$3 2.7k
+RR4 N$4 VCC 100k
+RR5 N$5 N$11 470k
+RR6CW N$5 IN2 31065.001000
+RR6CCW IN2 0 968935.001000
+RR7 0 N$7 10k
+RR8 N$8 VCC 100k
+RR9 IN3 N$10 470k
+RR10 0 IN3 470k
+RR11 0 N$13 820
+RR12 N$12 VDD 100k
+RR13 0 OUT 100k
+RR14 0 ROUT 1Meg
+XVR1A N$8 IN2 N$7 12AX7
+XVR1B N$4 N$1 N$3 12AX7
+XVR2A N$12 IN3 N$13 12AX7
+XVR2B VDD N$12 OUT 12AX7
+VVSIN1 IN 0 AC 1 SIN(0 1V 666Hz)
+VCC VCC 0 DC 250V
+VDD VDD 0 DC 260V
diff --git a/Projects/JCM800/Lead MV.sch b/Projects/JCM800/Lead MV.sch
new file mode 100644
index 0000000..ff8abda
Binary files /dev/null and b/Projects/JCM800/Lead MV.sch differ
diff --git a/Projects/JCM800/eagle.epf b/Projects/JCM800/eagle.epf
new file mode 100644
index 0000000..e2a06b7
--- /dev/null
+++ b/Projects/JCM800/eagle.epf
@@ -0,0 +1,26 @@
+[Eagle]
+Version="05 10 00"
+Platform="Windows"
+Serial="7D07E7847B-LSR-WLM-NCP"
+Globals="Globals"
+Desktop="Desktop"
+
+[Globals]
+AutoSaveProject=1
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Frames.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Supply.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Tubes.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Potentiometers.lbr"
+
+[Win_1]
+Type="Control Panel"
+Loc="977 230 1576 666"
+State=2
+Number=0
+
+[Desktop]
+Screen="1920 1174"
+Window="Win_1"
diff --git a/Projects/SPICE Examples/Cascaded Tube Stages.cir b/Projects/SPICE Examples/Cascaded Tube Stages.cir
new file mode 100644
index 0000000..8a74e71
--- /dev/null
+++ b/Projects/SPICE Examples/Cascaded Tube Stages.cir
@@ -0,0 +1,21 @@
+Cascaded Tube Stages
+.CONTROL
+run
+.ENDC
+CC1 N$1 G2 20nF
+CC2 N$5 OUT 100nF
+.TRAN 1uS 100mS
+.CONTROL
+plot G1 G2 OUT
+.ENDC
+RR1 N$1 VCC 100k
+RR2 IN G1 68k
+RR3 0 G1 1Meg
+RR4 0 N$3 1.5k
+RR5 0 G2 1Meg
+RR6 N$5 VCC 100k
+RR7 0 N$6 1.5k
+RR8 0 OUT 1Meg
+TEST
+VVSIN1 IN 0 AC 1 SIN(0 1V 1kHz)
+VCC VCC 0 DC 300V
diff --git a/Projects/SPICE Examples/Cascaded Tube Stages.sch b/Projects/SPICE Examples/Cascaded Tube Stages.sch
new file mode 100644
index 0000000..7c6703a
Binary files /dev/null and b/Projects/SPICE Examples/Cascaded Tube Stages.sch differ
diff --git a/Projects/SPICE Examples/eagle.epf b/Projects/SPICE Examples/eagle.epf
index 475a995..6acec3a 100644
--- a/Projects/SPICE Examples/eagle.epf
+++ b/Projects/SPICE Examples/eagle.epf
@@ -1,28 +1,29 @@
[Eagle]
-Version="05 06 00"
+Version="05 10 00"
Platform="Windows"
-Serial="20F4CAA25D-LSR-DOWL-NCP"
+Serial="7D07E7847B-LSR-WLM-NCP"
Globals="Globals"
Desktop="Desktop"
[Globals]
AutoSaveProject=1
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Frames.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Op Amps.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Supply.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Switches.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Transistors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Tubes.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Potentiometers.lbr"
[Win_1]
Type="Control Panel"
-Loc="770 394 1369 793"
+Loc="44 229 643 628"
State=2
Number=0
[Desktop]
-Screen="1920 1178"
+Screen="1920 1174"
Window="Win_1"
|
xdissent/monowave-eagle
|
c01b8cbc4c631a40fa86c1c66184a1ab40b3788e
|
Added LED device with SPICE data (temporary package). Added larger oscilloscopes to SPICE Tools. Added pulse SPICE signal generator. Added PNP transistors.
|
diff --git a/Libraries/Diodes.lbr b/Libraries/Diodes.lbr
index d44d947..5a06382 100644
Binary files a/Libraries/Diodes.lbr and b/Libraries/Diodes.lbr differ
diff --git a/Libraries/SPICE Tools.lbr b/Libraries/SPICE Tools.lbr
index 90270cb..a14107a 100644
Binary files a/Libraries/SPICE Tools.lbr and b/Libraries/SPICE Tools.lbr differ
diff --git a/Libraries/Transistors.lbr b/Libraries/Transistors.lbr
index 9debeb5..af5cb58 100644
Binary files a/Libraries/Transistors.lbr and b/Libraries/Transistors.lbr differ
diff --git a/Projects/SPICE Examples/eagle.epf b/Projects/SPICE Examples/eagle.epf
index abbb97b..475a995 100644
--- a/Projects/SPICE Examples/eagle.epf
+++ b/Projects/SPICE Examples/eagle.epf
@@ -1,28 +1,28 @@
[Eagle]
Version="05 06 00"
Platform="Windows"
Serial="20F4CAA25D-LSR-DOWL-NCP"
Globals="Globals"
Desktop="Desktop"
[Globals]
AutoSaveProject=1
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Frames.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Op Amps.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Supply.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Switches.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Transistors.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
-UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Potentiometers.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Frames.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Op Amps.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Supply.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Switches.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Transistors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
+UsedLibrary="C:/Users/xdissent/Documents/monowave-eagle/Libraries/Passives/Potentiometers.lbr"
[Win_1]
Type="Control Panel"
Loc="770 394 1369 793"
State=2
Number=0
[Desktop]
Screen="1920 1178"
Window="Win_1"
|
xdissent/monowave-eagle
|
059fd1ef0ce473c1d8459b324fe43854dc37d841
|
Typo in readme.
|
diff --git a/README.rst b/README.rst
index 9c2077c..47ffc33 100644
--- a/README.rst
+++ b/README.rst
@@ -1,272 +1,272 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`. Note that Eagle does some funky file name handling
and different path separators might be required for different platforms. It
looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME/monowave-eagle/Libraries`
**Design Rules** `$HOME/monowave-eagle/Design Rules`
**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
**Scripts** `$EAGLEDIR/scr`
**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the (forthcoming)
BOM manager.
Library Browser
---------------
The Library Browser User Language Program will generate a pretty slick HTML
site containing all the devices, packages, and symbols in the currently used
Eagle libraries. It renders XHTML 1.0 Strict compliant markup, and uses JQuery
and JQuery UI to spruce things up. A current version displaying all of the
Monowave libraries is always available at
http://xdissent.github.com/monowave-eagle/libraries/
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are available in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `3` indicating
"clockwise" and `2` is "counterclockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
* Run the DRC with `Monowave.dru` to check trace widths and clearances.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
-is was set to imperial. And with more and more manufacturers converting to
+was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
d0a2339b0c527077e2fca2b9ffc1d8a41a200f1b
|
Fixed link for library browser in readme.
|
diff --git a/README.rst b/README.rst
index 917e506..9c2077c 100644
--- a/README.rst
+++ b/README.rst
@@ -1,272 +1,272 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`. Note that Eagle does some funky file name handling
and different path separators might be required for different platforms. It
looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME/monowave-eagle/Libraries`
**Design Rules** `$HOME/monowave-eagle/Design Rules`
**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
**Scripts** `$EAGLEDIR/scr`
**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the (forthcoming)
BOM manager.
Library Browser
---------------
The Library Browser User Language Program will generate a pretty slick HTML
site containing all the devices, packages, and symbols in the currently used
Eagle libraries. It renders XHTML 1.0 Strict compliant markup, and uses JQuery
and JQuery UI to spruce things up. A current version displaying all of the
Monowave libraries is always available at
-http://github.com/xdissent/monowave-eagle/libraries/
+http://xdissent.github.com/monowave-eagle/libraries/
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are available in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `3` indicating
"clockwise" and `2` is "counterclockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
* Run the DRC with `Monowave.dru` to check trace widths and clearances.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
c1fa994c1632ac94333df4ed56696be5ab8cf9fe
|
Removed id attribute from library template to avoid spaces in the id. Now xhtml 1.0 strict compatible again.
|
diff --git a/User Language Programs/Library Browser/templates/library.html b/User Language Programs/Library Browser/templates/library.html
index 73e96c5..15f61b1 100644
--- a/User Language Programs/Library Browser/templates/library.html
+++ b/User Language Programs/Library Browser/templates/library.html
@@ -1,34 +1,34 @@
-<div class="library" id="{L.NAME}">
+<div class="library">
<h1>{L.NAME}</h1>
<p>{L.DESC}</p>
<div id="tabs">
<ul>
<li><a href="#devices">Devices</a></li>
<li><a href="#packages">Packages</a></li>
<li><a href="#symbols">Symbols</a></li>
</ul>
<div id="devices">
{DEVICES}
</div><!-- end devices -->
<div id="packages">
{PACKAGES}
</div><!-- end packages -->
<div id="symbols">
{SYMBOLS}
</div><!-- end symbols -->
</div><!-- end tabs -->
</div><!-- end library -->
\ No newline at end of file
|
xdissent/monowave-eagle
|
6a7291b5037046d34b536d8b970d275bdd7cf460
|
Finished up the library browser styles and templates.
|
diff --git a/User Language Programs/Library Browser/Combine Templates.ulp b/User Language Programs/Library Browser/Combine Templates.ulp
index 45cdb06..b616621 100644
--- a/User Language Programs/Library Browser/Combine Templates.ulp
+++ b/User Language Programs/Library Browser/Combine Templates.ulp
@@ -1,69 +1,71 @@
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* main
*
* Combine all the generated library templates.
*/
int main() {
// Set up toc.
string toc;
int i;
// Find all used libraries and add a link to the toc.
for (i = 0; used_libraries[i] != ""; i++) {
string lib_name = filesetext(filename(used_libraries[i]), "");
string toc_template;
fileread(toc_template, filedir(argv[0]) + "templates/toc.html");
toc_template = str_replace("{L.NAME}", lib_name, toc_template);
toc = toc + toc_template;
}
// Find all used libraries and wrap their html output with the index template.
for (i = 0; used_libraries[i] != ""; i++) {
string lib_name = filesetext(filename(used_libraries[i]), "");
- string index_template;
+ string wrapper_template;
string lib_template;
- fileread(index_template, filedir(argv[0]) + "templates/index.html");
+ fileread(wrapper_template, filedir(argv[0]) + "templates/wrapper.html");
fileread(lib_template, filedir(argv[0]) + "html/" + lib_name + ".html");
- index_template = str_replace("{TOC}", toc, index_template);
- index_template = str_replace("{LIBRARY}", lib_template, index_template);
+ wrapper_template = str_replace("{TOC}", toc, wrapper_template);
+ wrapper_template = str_replace("{CONTENT}", lib_template, wrapper_template);
output(filedir(argv[0]) + "html/" + lib_name + ".html") {
- printf(index_template);
+ printf(wrapper_template);
}
}
// Handle main index file.
+ string wrapper_template;
string index_template;
+ fileread(wrapper_template, filedir(argv[0]) + "templates/wrapper.html");
fileread(index_template, filedir(argv[0]) + "templates/index.html");
- index_template = str_replace("{TOC}", toc, index_template);
- index_template = str_replace("{LIBRARY}", "", index_template);
+ wrapper_template = str_replace("{TOC}", toc, wrapper_template);
+ wrapper_template = str_replace("{CONTENT}", index_template, wrapper_template);
output(filedir(argv[0]) + "html/index.html") {
- printf(index_template);
+ printf(wrapper_template);
}
return(0);
}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/Process Library.ulp b/User Language Programs/Library Browser/Process Library.ulp
index 07c6ef9..8312ba6 100644
--- a/User Language Programs/Library Browser/Process Library.ulp
+++ b/User Language Programs/Library Browser/Process Library.ulp
@@ -1,225 +1,238 @@
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* main
*
* Processes a library for the Library Browser ULP.
*/
int main() {
// Only valid in the library editor.
library(L) {
status("Processing: " + L.name);
// Template path.
string template_root = filedir(argv[0]) + "templates";
// HTML output path.
string html_root = filedir(argv[0]) + "html";
// Library short name.
string lib_name = filesetext(filename(L.name), "");
// Temporary image script file name.
string image_script = filedir(argv[0]) + "images.scr";
// Image output root path.
string image_root = filedir(argv[0]) + "images";
// Temporary image script output lines.
string img_out[];
// Image script line index.
int img_n = 0;
// Library template substitutions.
string devices;
string packages;
string symbols;
// Process devicesets.
L.devicesets(DS) {
status("Processing deviceset: " + DS.name);
// Read in device.html
string device_template;
fileread(device_template, template_root + "/device.html");
// Set up variants.
string variants;
// Process device variants.
DS.devices(D) {
// Set up attributes.
- string attrs;
+ string attrs = "";
// Crappy loop to handle attrs for technologies.
string t[];
int n = strsplit(t, D.technologies, ' ');
for (int i = 0; i < n; i++) {
D.attributes(A, t[i]) {
// Read in attribute.html
string attr_template;
fileread(attr_template, template_root + "/attribute.html");
// Substitute {A.NAME} in attribute template.
attr_template = str_replace("{A.NAME}", A.name, attr_template);
// Escape substitutions in attributes.
string val = str_replace("{", "{", A.value);
val = str_replace("}", "}", val);
// Substitute {A.VALUE} in attribute template.
attr_template = str_replace("{A.VALUE}", val, attr_template);
attrs = attrs + attr_template;
}
}
+
+ if (attrs == "") {
+ attrs = "<dt>None</dt>";
+ }
// Read in variant.html
string variant_template;
fileread(variant_template, template_root + "/variant.html");
// Substitute {ATTRIBUTES} in variant template.
variant_template = str_replace("{ATTRIBUTES}", attrs, variant_template);
+
+ // Change default variant name to "Default".
+ string variant_name;
+ if (D.name == "''") {
+ variant_name = "Default";
+ } else {
+ variant_name = D.name;
+ }
// Substitute {D.NAME} in variant template.
- variant_template = str_replace("{D.NAME}", D.name, variant_template);
+ variant_template = str_replace("{D.NAME}", variant_name, variant_template);
+
// Substitute {D.P.NAME} in variant template if it exists.
if (D.package) {
variant_template = str_replace("{D.P.NAME}", D.package.name, variant_template);
} else {
variant_template = str_replace("{D.P.NAME}", "None", variant_template);
}
// Add variant_template to variants string.
variants = variants + variant_template;
}
// Set up gates.
string gates;
// Process device gates.
DS.gates(G) {
// Read in gate.html
string gate_template;
fileread(gate_template, template_root + "/gate.html");
// Substitute {G.S.NAME} in gate template.
gate_template = str_replace("{G.S.NAME}", G.symbol.name, gate_template);
// Substitute {G.NAME} in gate template.
gate_template = str_replace("{G.NAME}", G.name, gate_template);
// Add gate_template to gates string.
gates = gates + gate_template;
}
// Substitute variant template for {VARIANTS} in device template.
device_template = str_replace("{VARIANTS}", variants, device_template);
// Substitute gate template for {GATES} in device template.
device_template = str_replace("{GATES}", gates, device_template);
// Substitute {DS.NAME} and {DS.DESC}
device_template = str_replace("{DS.NAME}", DS.name, device_template);
device_template = str_replace("{DS.DESC}", DS.description, device_template);
// Substitute device symbol name for {DS.S.NAME}.
// device_template = str_replace("{DS.S.NAME}", DS.symbol.name, device_template)
// Add device template to devices string.
devices = devices + device_template;
// Add image export command to image script.
sprintf(img_out[img_n++], "EDIT %s.dev", DS.name);
sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-device-%s.png' 300", image_root, lib_name, DS.name);
}
// Process packages.
L.packages(P) {
status("Processing package: " + P.name);
// Read in package.html template.
string package_template;
fileread(package_template, template_root + "/package.html");
// Substitute {P.NAME} and {P.DESC}
package_template = str_replace("{P.NAME}", P.name, package_template);
package_template = str_replace("{P.DESC}", P.description, package_template);
// Add package template to packages string.
packages = packages + package_template;
// Add image export command to image script.
sprintf(img_out[img_n++], "EDIT %s.pac", P.name);
sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-package-%s.png' 300", image_root, lib_name, P.name);
}
// Process symbols.
L.symbols(S) {
status("Processing symbol: " + S.name);
// Read in symbol.html template.
string symbol_template;
fileread(symbol_template, template_root + "/symbol.html");
// Substitute {S.NAME}
symbol_template = str_replace("{S.NAME}", S.name, symbol_template);
// Add symbol template to symbols string.
symbols = symbols + symbol_template;
// Add image export command to image script.
sprintf(img_out[img_n++], "EDIT %s.sym", S.name);
sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-symbol-%s.png' 300", image_root, lib_name, S.name);
}
// Read in library.html template.
string library_template;
fileread(library_template, template_root + "/library.html");
// Substitute devices string for {DEVICES}.
library_template = str_replace("{DEVICES}", devices, library_template);
// Substitute packages string for {PACKAGES}.
library_template = str_replace("{PACKAGES}", packages, library_template);
// Substitute symbols string for {SYMBOLS}.
library_template = str_replace("{SYMBOLS}", symbols, library_template);
// Subtitute {L.NAME} and {L.DESC} in library template.
library_template = str_replace("{L.NAME}", lib_name, library_template);
library_template = str_replace("{L.DESC}", L.description, library_template);
// Output rendered library template.
output(html_root + "/" + lib_name + ".html") {
printf(library_template);
}
// Output image script.
output(image_script) {
printf(strjoin(img_out, '\n'));
}
// Run image export script for all devices, packages, and symbols.
exit("SCRIPT '" + image_script + "'");
}
return(0);
}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/css/grid.less b/User Language Programs/Library Browser/css/grid.less
new file mode 100644
index 0000000..f958f28
--- /dev/null
+++ b/User Language Programs/Library Browser/css/grid.less
@@ -0,0 +1,97 @@
+/**
+ * Grid LESS
+ *
+ * Horizontal Grid
+ *
+ * Copyright 2009 Greg Thornton <[email protected]>
+ * License: http://creativecommons.org/licenses/by-sa/3.0/us/
+ */
+
+@import url(reset.less);
+@import url(text.less);
+
+/**
+ * Create a grid container.
+ */
+.grid-container(@columns:16, @width: 960px, @margin: 10px) {
+ width: @width;
+ margin-right: auto;
+ margin-left: auto;
+
+ /**
+ * Variable passed to child grids.
+ */
+ @column-width: @width / @columns;
+
+ /**
+ * Create a grid.
+ */
+ .grid(@grid-columns: 0) {
+
+ /**
+ * Styles
+ */
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: @margin;
+ margin-right: @margin;
+ width: @grid-columns * @column-width - 2 * @margin;
+ }
+
+ /**
+ * Add empty columns to the left.
+ */
+ .prefix(@prefix: 0) {
+ padding-left: @column-width * @prefix;
+ }
+
+ /**
+ * Add empty columns to the right.
+ */
+ .suffix(@suffix: 0) {
+ padding-right: @column-width * @suffix;
+ }
+
+ /**
+ * Pull grid to the left.
+ */
+ .pull(@pull: 0) {
+ left: 0 - @column-width * @pull;
+ }
+
+ /**
+ * Push grid to the right.
+ */
+ .push(@push: 0) {
+ left: @column-width * @push;
+ }
+}
+
+/**
+ * The following 2 mixins would ideally be defined inside the .grid-container
+ * mixin since it isn't relevant in any other scope. There is a bug in LESS
+ * that makes it impossible to nest mixins that don't take arguments so they
+ * are defined globally for now.
+ */
+
+/**
+ * The first grid inside another grid.
+ */
+.alpha {
+ margin-left: 0;
+}
+
+/**
+ * The last grid inside another grid.
+ */
+.omega {
+ margin-right: 0;
+}
+
+/**
+ * Make an element clear all floats.
+ */
+.clear {
+ clear: both;
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_0_aaaaaa_40x100.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_0_aaaaaa_40x100.png
new file mode 100644
index 0000000..5b5dab2
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_0_aaaaaa_40x100.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_cccccc_40x100.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_cccccc_40x100.png
new file mode 100644
index 0000000..5473aff
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_cccccc_40x100.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_ffffff_40x100.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_ffffff_40x100.png
new file mode 100644
index 0000000..ac8b229
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_flat_75_ffffff_40x100.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_55_fbf9ee_1x400.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_55_fbf9ee_1x400.png
new file mode 100644
index 0000000..ad3d634
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_55_fbf9ee_1x400.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_65_ffffff_1x400.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_65_ffffff_1x400.png
new file mode 100644
index 0000000..42ccba2
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_65_ffffff_1x400.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_dadada_1x400.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_dadada_1x400.png
new file mode 100644
index 0000000..5a46b47
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_dadada_1x400.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_e6e6e6_1x400.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_e6e6e6_1x400.png
new file mode 100644
index 0000000..86c2baa
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_75_e6e6e6_1x400.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_95_fef1ec_1x400.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_95_fef1ec_1x400.png
new file mode 100644
index 0000000..4443fdc
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-bg_glass_95_fef1ec_1x400.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_222222_256x240.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_222222_256x240.png
new file mode 100644
index 0000000..ee039dc
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_222222_256x240.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_2e83ff_256x240.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_2e83ff_256x240.png
new file mode 100644
index 0000000..45e8928
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_2e83ff_256x240.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_454545_256x240.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_454545_256x240.png
new file mode 100644
index 0000000..7ec70d1
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_454545_256x240.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_888888_256x240.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_888888_256x240.png
new file mode 100644
index 0000000..5ba708c
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_888888_256x240.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_cd0a0a_256x240.png b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_cd0a0a_256x240.png
new file mode 100644
index 0000000..7930a55
Binary files /dev/null and b/User Language Programs/Library Browser/css/jqueryui-theme/images/ui-icons_cd0a0a_256x240.png differ
diff --git a/User Language Programs/Library Browser/css/jqueryui-theme/theme.css b/User Language Programs/Library Browser/css/jqueryui-theme/theme.css
new file mode 100644
index 0000000..c9658f3
--- /dev/null
+++ b/User Language Programs/Library Browser/css/jqueryui-theme/theme.css
@@ -0,0 +1,406 @@
+/*
+* jQuery UI CSS Framework
+* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
+*/
+
+/* Layout helpers
+----------------------------------*/
+.ui-helper-hidden { display: none; }
+.ui-helper-hidden-accessible { position: absolute; left: -99999999px; }
+.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
+.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
+.ui-helper-clearfix { display: inline-block; }
+/* required comment for clearfix to work in Opera \*/
+* html .ui-helper-clearfix { height:1%; }
+.ui-helper-clearfix { display:block; }
+/* end clearfix */
+.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
+
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-disabled { cursor: default !important; }
+
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Overlays */
+.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+
+
+
+/*
+* jQuery UI CSS Framework
+* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
+* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Georgia,%20serif&fwDefault=normal&fsDefault=12px&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=01_flat.png&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=02_glass.png&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=02_glass.png&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=02_glass.png&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
+*/
+
+
+/* Component containers
+----------------------------------*/
+.ui-widget { font-family: Georgia, serif; font-size: 12px; }
+.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Georgia, serif; font-size: 1em; }
+.ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #222222; }
+.ui-widget-content a { color: #222222; }
+.ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url(images/ui-bg_flat_75_cccccc_40x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
+.ui-widget-header a { color: #222222; }
+
+/* Interaction states
+----------------------------------*/
+.ui-state-default, .ui-widget-content .ui-state-default { border: 1px solid #d3d3d3; background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #555555; outline: none; }
+.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; outline: none; }
+.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus { border: 1px solid #999999; background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; outline: none; }
+.ui-state-hover a, .ui-state-hover a:hover { color: #212121; text-decoration: none; outline: none; }
+.ui-state-active, .ui-widget-content .ui-state-active { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; outline: none; }
+.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121; outline: none; text-decoration: none; }
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-highlight, .ui-widget-content .ui-state-highlight {border: 1px solid #fcefa1; background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; color: #363636; }
+.ui-state-highlight a, .ui-widget-content .ui-state-highlight a { color: #363636; }
+.ui-state-error, .ui-widget-content .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
+.ui-state-error a, .ui-widget-content .ui-state-error a { color: #cd0a0a; }
+.ui-state-error-text, .ui-widget-content .ui-state-error-text { color: #cd0a0a; }
+.ui-state-disabled, .ui-widget-content .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
+.ui-priority-primary, .ui-widget-content .ui-priority-primary { font-weight: bold; }
+.ui-priority-secondary, .ui-widget-content .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png); }
+.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
+.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
+.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); }
+.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png); }
+
+/* positioning */
+.ui-icon-carat-1-n { background-position: 0 0; }
+.ui-icon-carat-1-ne { background-position: -16px 0; }
+.ui-icon-carat-1-e { background-position: -32px 0; }
+.ui-icon-carat-1-se { background-position: -48px 0; }
+.ui-icon-carat-1-s { background-position: -64px 0; }
+.ui-icon-carat-1-sw { background-position: -80px 0; }
+.ui-icon-carat-1-w { background-position: -96px 0; }
+.ui-icon-carat-1-nw { background-position: -112px 0; }
+.ui-icon-carat-2-n-s { background-position: -128px 0; }
+.ui-icon-carat-2-e-w { background-position: -144px 0; }
+.ui-icon-triangle-1-n { background-position: 0 -16px; }
+.ui-icon-triangle-1-ne { background-position: -16px -16px; }
+.ui-icon-triangle-1-e { background-position: -32px -16px; }
+.ui-icon-triangle-1-se { background-position: -48px -16px; }
+.ui-icon-triangle-1-s { background-position: -64px -16px; }
+.ui-icon-triangle-1-sw { background-position: -80px -16px; }
+.ui-icon-triangle-1-w { background-position: -96px -16px; }
+.ui-icon-triangle-1-nw { background-position: -112px -16px; }
+.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
+.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
+.ui-icon-arrow-1-n { background-position: 0 -32px; }
+.ui-icon-arrow-1-ne { background-position: -16px -32px; }
+.ui-icon-arrow-1-e { background-position: -32px -32px; }
+.ui-icon-arrow-1-se { background-position: -48px -32px; }
+.ui-icon-arrow-1-s { background-position: -64px -32px; }
+.ui-icon-arrow-1-sw { background-position: -80px -32px; }
+.ui-icon-arrow-1-w { background-position: -96px -32px; }
+.ui-icon-arrow-1-nw { background-position: -112px -32px; }
+.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
+.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
+.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
+.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
+.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
+.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
+.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
+.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
+.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
+.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
+.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
+.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
+.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
+.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
+.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
+.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
+.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
+.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
+.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
+.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
+.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
+.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
+.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
+.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
+.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
+.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
+.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
+.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
+.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
+.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
+.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
+.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
+.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
+.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
+.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
+.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
+.ui-icon-arrow-4 { background-position: 0 -80px; }
+.ui-icon-arrow-4-diag { background-position: -16px -80px; }
+.ui-icon-extlink { background-position: -32px -80px; }
+.ui-icon-newwin { background-position: -48px -80px; }
+.ui-icon-refresh { background-position: -64px -80px; }
+.ui-icon-shuffle { background-position: -80px -80px; }
+.ui-icon-transfer-e-w { background-position: -96px -80px; }
+.ui-icon-transferthick-e-w { background-position: -112px -80px; }
+.ui-icon-folder-collapsed { background-position: 0 -96px; }
+.ui-icon-folder-open { background-position: -16px -96px; }
+.ui-icon-document { background-position: -32px -96px; }
+.ui-icon-document-b { background-position: -48px -96px; }
+.ui-icon-note { background-position: -64px -96px; }
+.ui-icon-mail-closed { background-position: -80px -96px; }
+.ui-icon-mail-open { background-position: -96px -96px; }
+.ui-icon-suitcase { background-position: -112px -96px; }
+.ui-icon-comment { background-position: -128px -96px; }
+.ui-icon-person { background-position: -144px -96px; }
+.ui-icon-print { background-position: -160px -96px; }
+.ui-icon-trash { background-position: -176px -96px; }
+.ui-icon-locked { background-position: -192px -96px; }
+.ui-icon-unlocked { background-position: -208px -96px; }
+.ui-icon-bookmark { background-position: -224px -96px; }
+.ui-icon-tag { background-position: -240px -96px; }
+.ui-icon-home { background-position: 0 -112px; }
+.ui-icon-flag { background-position: -16px -112px; }
+.ui-icon-calendar { background-position: -32px -112px; }
+.ui-icon-cart { background-position: -48px -112px; }
+.ui-icon-pencil { background-position: -64px -112px; }
+.ui-icon-clock { background-position: -80px -112px; }
+.ui-icon-disk { background-position: -96px -112px; }
+.ui-icon-calculator { background-position: -112px -112px; }
+.ui-icon-zoomin { background-position: -128px -112px; }
+.ui-icon-zoomout { background-position: -144px -112px; }
+.ui-icon-search { background-position: -160px -112px; }
+.ui-icon-wrench { background-position: -176px -112px; }
+.ui-icon-gear { background-position: -192px -112px; }
+.ui-icon-heart { background-position: -208px -112px; }
+.ui-icon-star { background-position: -224px -112px; }
+.ui-icon-link { background-position: -240px -112px; }
+.ui-icon-cancel { background-position: 0 -128px; }
+.ui-icon-plus { background-position: -16px -128px; }
+.ui-icon-plusthick { background-position: -32px -128px; }
+.ui-icon-minus { background-position: -48px -128px; }
+.ui-icon-minusthick { background-position: -64px -128px; }
+.ui-icon-close { background-position: -80px -128px; }
+.ui-icon-closethick { background-position: -96px -128px; }
+.ui-icon-key { background-position: -112px -128px; }
+.ui-icon-lightbulb { background-position: -128px -128px; }
+.ui-icon-scissors { background-position: -144px -128px; }
+.ui-icon-clipboard { background-position: -160px -128px; }
+.ui-icon-copy { background-position: -176px -128px; }
+.ui-icon-contact { background-position: -192px -128px; }
+.ui-icon-image { background-position: -208px -128px; }
+.ui-icon-video { background-position: -224px -128px; }
+.ui-icon-script { background-position: -240px -128px; }
+.ui-icon-alert { background-position: 0 -144px; }
+.ui-icon-info { background-position: -16px -144px; }
+.ui-icon-notice { background-position: -32px -144px; }
+.ui-icon-help { background-position: -48px -144px; }
+.ui-icon-check { background-position: -64px -144px; }
+.ui-icon-bullet { background-position: -80px -144px; }
+.ui-icon-radio-off { background-position: -96px -144px; }
+.ui-icon-radio-on { background-position: -112px -144px; }
+.ui-icon-pin-w { background-position: -128px -144px; }
+.ui-icon-pin-s { background-position: -144px -144px; }
+.ui-icon-play { background-position: 0 -160px; }
+.ui-icon-pause { background-position: -16px -160px; }
+.ui-icon-seek-next { background-position: -32px -160px; }
+.ui-icon-seek-prev { background-position: -48px -160px; }
+.ui-icon-seek-end { background-position: -64px -160px; }
+.ui-icon-seek-first { background-position: -80px -160px; }
+.ui-icon-stop { background-position: -96px -160px; }
+.ui-icon-eject { background-position: -112px -160px; }
+.ui-icon-volume-off { background-position: -128px -160px; }
+.ui-icon-volume-on { background-position: -144px -160px; }
+.ui-icon-power { background-position: 0 -176px; }
+.ui-icon-signal-diag { background-position: -16px -176px; }
+.ui-icon-signal { background-position: -32px -176px; }
+.ui-icon-battery-0 { background-position: -48px -176px; }
+.ui-icon-battery-1 { background-position: -64px -176px; }
+.ui-icon-battery-2 { background-position: -80px -176px; }
+.ui-icon-battery-3 { background-position: -96px -176px; }
+.ui-icon-circle-plus { background-position: 0 -192px; }
+.ui-icon-circle-minus { background-position: -16px -192px; }
+.ui-icon-circle-close { background-position: -32px -192px; }
+.ui-icon-circle-triangle-e { background-position: -48px -192px; }
+.ui-icon-circle-triangle-s { background-position: -64px -192px; }
+.ui-icon-circle-triangle-w { background-position: -80px -192px; }
+.ui-icon-circle-triangle-n { background-position: -96px -192px; }
+.ui-icon-circle-arrow-e { background-position: -112px -192px; }
+.ui-icon-circle-arrow-s { background-position: -128px -192px; }
+.ui-icon-circle-arrow-w { background-position: -144px -192px; }
+.ui-icon-circle-arrow-n { background-position: -160px -192px; }
+.ui-icon-circle-zoomin { background-position: -176px -192px; }
+.ui-icon-circle-zoomout { background-position: -192px -192px; }
+.ui-icon-circle-check { background-position: -208px -192px; }
+.ui-icon-circlesmall-plus { background-position: 0 -208px; }
+.ui-icon-circlesmall-minus { background-position: -16px -208px; }
+.ui-icon-circlesmall-close { background-position: -32px -208px; }
+.ui-icon-squaresmall-plus { background-position: -48px -208px; }
+.ui-icon-squaresmall-minus { background-position: -64px -208px; }
+.ui-icon-squaresmall-close { background-position: -80px -208px; }
+.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
+.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
+.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
+.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
+.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
+.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Corner radius */
+.ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; }
+.ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
+.ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
+.ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }
+.ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }
+.ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }
+.ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; }
+
+/* Overlays */
+.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
+.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -webkit-border-radius: 8px; }/* Accordion
+----------------------------------*/
+.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
+.ui-accordion .ui-accordion-li-fix { display: inline; }
+.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
+.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em 2.2em; }
+.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
+.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; }
+.ui-accordion .ui-accordion-content-active { display: block; }/* Datepicker
+----------------------------------*/
+.ui-datepicker { width: 17em; padding: .2em .2em 0; }
+.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
+.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
+.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
+.ui-datepicker .ui-datepicker-prev { left:2px; }
+.ui-datepicker .ui-datepicker-next { right:2px; }
+.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
+.ui-datepicker .ui-datepicker-next-hover { right:1px; }
+.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; }
+.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
+.ui-datepicker .ui-datepicker-title select { float:left; font-size:1em; margin:1px 0; }
+.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
+.ui-datepicker select.ui-datepicker-month,
+.ui-datepicker select.ui-datepicker-year { width: 49%;}
+.ui-datepicker .ui-datepicker-title select.ui-datepicker-year { float: right; }
+.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
+.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; }
+.ui-datepicker td { border: 0; padding: 1px; }
+.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
+.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
+.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
+.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
+
+/* with multiple calendars */
+.ui-datepicker.ui-datepicker-multi { width:auto; }
+.ui-datepicker-multi .ui-datepicker-group { float:left; }
+.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
+.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
+.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
+.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
+.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
+.ui-datepicker-row-break { clear:both; width:100%; }
+
+/* RTL support */
+.ui-datepicker-rtl { direction: rtl; }
+.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+
+/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
+.ui-datepicker-cover {
+ display: none; /*sorry for IE5*/
+ display/**/: block; /*sorry for IE5*/
+ position: absolute; /*must have*/
+ z-index: -1; /*must have*/
+ filter: mask(); /*must have*/
+ top: -4px; /*must have*/
+ left: -4px; /*must have*/
+ width: 200px; /*must have*/
+ height: 200px; /*must have*/
+}/* Dialog
+----------------------------------*/
+.ui-dialog { position: relative; padding: .2em; width: 300px; }
+.ui-dialog .ui-dialog-titlebar { padding: .5em .3em .3em 1em; position: relative; }
+.ui-dialog .ui-dialog-title { float: left; margin: .1em 0 .2em; }
+.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
+.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
+.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
+.ui-dialog .ui-dialog-content { border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
+.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
+.ui-dialog .ui-dialog-buttonpane button { float: right; margin: .5em .4em .5em 0; cursor: pointer; padding: .2em .6em .3em .6em; line-height: 1.4em; width:auto; overflow:visible; }
+.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
+.ui-draggable .ui-dialog-titlebar { cursor: move; }
+/* Progressbar
+----------------------------------*/
+.ui-progressbar { height:2em; text-align: left; }
+.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }/* Resizable
+----------------------------------*/
+.ui-resizable { position: relative;}
+.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;}
+.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
+.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0px; }
+.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0px; }
+.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0px; height: 100%; }
+.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0px; height: 100%; }
+.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
+.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
+.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
+.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/* Slider
+----------------------------------*/
+.ui-slider { position: relative; text-align: left; }
+.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
+.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; }
+
+.ui-slider-horizontal { height: .8em; }
+.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
+.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
+.ui-slider-horizontal .ui-slider-range-min { left: 0; }
+.ui-slider-horizontal .ui-slider-range-max { right: 0; }
+
+.ui-slider-vertical { width: .8em; height: 100px; }
+.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
+.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
+.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
+.ui-slider-vertical .ui-slider-range-max { top: 0; }/* Tabs
+----------------------------------*/
+.ui-tabs { padding: .2em; zoom: 1; }
+.ui-tabs .ui-tabs-nav { list-style: none; position: relative; padding: .2em .2em 0; }
+.ui-tabs .ui-tabs-nav li { position: relative; float: left; border-bottom-width: 0 !important; margin: 0 .2em -1px 0; padding: 0; }
+.ui-tabs .ui-tabs-nav li a { float: left; text-decoration: none; padding: .5em 1em; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 1px; border-bottom-width: 0; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
+.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
+.ui-tabs .ui-tabs-panel { padding: 1em 1.4em; display: block; border-width: 0; background: none; }
+.ui-tabs .ui-tabs-hide { display: none !important; }
diff --git a/User Language Programs/Library Browser/css/library.css b/User Language Programs/Library Browser/css/library.css
new file mode 100644
index 0000000..829eb2e
--- /dev/null
+++ b/User Language Programs/Library Browser/css/library.css
@@ -0,0 +1,216 @@
+html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ vertical-align: baseline;
+ background: transparent;
+}
+body { line-height: 1; }
+ol, ul { list-style: none; }
+blockquote, q { quotes: none; }
+blockquote:before {
+ content: '';
+ content: none;
+}
+blockquote:after {
+ content: '';
+ content: none;
+}
+q:before {
+ content: '';
+ content: none;
+}
+q:after {
+ content: '';
+ content: none;
+}
+:focus { outline: 0; }
+ins { text-decoration: none; }
+del { text-decoration: line-through; }
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+}
+body {
+ font-family: Helvetica, Arial, 'Liberation Sans', FreeSans, sans-serif;
+ font-size: 12px;
+ line-height: 18px;
+}
+a:focus { outline: 1px dotted; }
+hr {
+ border: 0 #cccccc solid;
+ border-top-width: 1px;
+ clear: both;
+ height: 0;
+ margin-top: -1px;
+}
+.gargantuan {
+ font-weight: bold;
+ font-size: 6em;
+ line-height: 1em;
+}
+.enormous {
+ font-weight: bold;
+ font-size: 5em;
+ line-height: 1.2em;
+}
+.giant {
+ font-weight: bold;
+ font-size: 4em;
+ line-height: 1.125em;
+}
+.huge {
+ font-weight: bold;
+ font-size: 3em;
+ line-height: 1.5em;
+}
+.h1 {
+ font-weight: bold;
+ font-size: 2.5em;
+ line-height: 1.2em;
+}
+.h2 {
+ font-weight: bold;
+ font-size: 2em;
+ line-height: 1.5em;
+}
+.h3 {
+ font-weight: bold;
+ font-size: 1.5em;
+ line-height: 18px;
+}
+.h4 {
+ font-weight: bold;
+ font-size: 1.25em;
+ line-height: 18px;
+}
+.h5 {
+ font-weight: bold;
+ font-size: 1em;
+ line-height: 18px;
+}
+.h6 {
+ font-weight: normal;
+ font-size: 1em;
+ line-height: 18px;
+}
+h1 {
+ font-weight: bold;
+ font-size: 2.5em;
+ line-height: 1.2em;
+}
+h2 {
+ font-weight: bold;
+ font-size: 2em;
+ line-height: 1.5em;
+}
+h3 {
+ font-weight: bold;
+ font-size: 1.5em;
+ line-height: 18px;
+}
+h4 {
+ font-weight: bold;
+ font-size: 1.25em;
+ line-height: 18px;
+}
+h5 {
+ font-weight: bold;
+ font-size: 1em;
+ line-height: 18px;
+}
+h6 {
+ font-weight: normal;
+ font-size: 1em;
+ line-height: 18px;
+}
+ol { list-style: decimal; }
+ul { list-style: none; }
+li { margin-left: 30px; }
+p, dl, hr, h1, h2, h3, h4, h5, h6, ol, ul, pre, table, address, fieldset { margin-bottom: 18px; }
+.alpha { margin-left: 0; }
+.omega { margin-right: 0; }
+.clear { clear: both; }
+#wrapper {
+ width: 960px;
+ margin-right: auto;
+ margin-left: auto;
+ font-family: Georgia;
+}
+#wrapper #header {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 940px;
+}
+#wrapper #header > p {
+ font-weight: bold;
+ font-size: 3em;
+ line-height: 1.5em;
+}
+#wrapper #sidebar {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 160px;
+}
+#wrapper #sidebar > p {
+ font-weight: bold;
+ font-size: 1.5em;
+ line-height: 18px;
+}
+#wrapper #sidebar > ul > li { margin-left: 0; }
+#wrapper #content {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 760px;
+}
+#wrapper #content .device .gates > .gate {
+ width: 25%;
+ float: left;
+}
+#wrapper #content .device > h3 { clear: both; }
+#wrapper #content .device .variants { margin-bottom: 18px; }
+#wrapper #content .device .variants dl { border: 1px solid #aaaaaa; }
+#wrapper #content .device .variants dl dt { background-color: #cccccc; }
+#wrapper #content .device .variants dl dd {
+ padding: 18px;
+ font-family: Monaco;
+}
+#wrapper #content img { max-width: 720px; }
+#wrapper #footer {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 940px;
+}
+#wrapper #footer p:first-child {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 460px;
+ margin-left: 0;
+}
+#wrapper #footer p:last-child {
+ display: inline;
+ float: left;
+ position: relative;
+ margin-left: 10px;
+ margin-right: 10px;
+ width: 460px;
+ margin-right: 0;
+ text-align: right;
+}
diff --git a/User Language Programs/Library Browser/css/library.less b/User Language Programs/Library Browser/css/library.less
new file mode 100644
index 0000000..c581de7
--- /dev/null
+++ b/User Language Programs/Library Browser/css/library.less
@@ -0,0 +1,84 @@
+@import url(grid.less);
+
+#wrapper {
+ .grid-container;
+
+ font-family: Georgia;
+
+ #header {
+ .grid(16);
+
+ > p {
+ .huge;
+ }
+ }
+
+ #sidebar {
+ .grid(3);
+
+ > p {
+ .h3;
+ }
+
+ > ul > li {
+ margin-left: 0;
+ }
+ }
+
+ #content {
+ .grid(13);
+
+ .device {
+
+ .gates {
+
+ > .gate {
+ width: 25%;
+ float: left;
+ }
+ }
+
+ > h3 {
+ clear: both;
+ }
+
+ .variants {
+
+ margin-bottom: 18px;
+
+ dl {
+ border: 1px solid #aaaaaa;
+
+ dt {
+ background-color: #cccccc;
+ }
+
+ dd {
+ padding: 18px;
+ font-family: Monaco;
+ }
+ }
+ }
+ }
+
+ img {
+ max-width: 720px;
+ }
+ }
+
+ #footer {
+ .grid(16);
+
+ p:first-child {
+ .grid(8);
+ .alpha;
+ }
+
+ p:last-child {
+ .grid(8);
+ .omega;
+
+ text-align: right;
+ }
+ }
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/css/reset.less b/User Language Programs/Library Browser/css/reset.less
new file mode 100644
index 0000000..823ee76
--- /dev/null
+++ b/User Language Programs/Library Browser/css/reset.less
@@ -0,0 +1,53 @@
+/* http://meyerweb.com/eric/tools/css/reset/ */
+/* v1.0 | 20080212 */
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, font, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ vertical-align: baseline;
+ background: transparent;
+}
+body {
+ line-height: 1;
+}
+ol, ul {
+ list-style: none;
+}
+blockquote, q {
+ quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
+
+/* remember to define focus styles! */
+:focus {
+ outline: 0;
+}
+
+/* remember to highlight inserts somehow! */
+ins {
+ text-decoration: none;
+}
+del {
+ text-decoration: line-through;
+}
+
+/* tables still need 'cellspacing="0"' in the markup */
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/css/text.less b/User Language Programs/Library Browser/css/text.less
new file mode 100644
index 0000000..48e50c7
--- /dev/null
+++ b/User Language Programs/Library Browser/css/text.less
@@ -0,0 +1,126 @@
+/**
+ * Grid LESS
+ *
+ * Vertical Grid and Text
+ *
+ * Copyright 2009 Greg Thornton <[email protected]>
+ * License: http://creativecommons.org/licenses/by-sa/3.0/us/
+ */
+
+@font-size: 12px;
+@line-height: 18px;
+
+body {
+ font-family: Helvetica, Arial, 'Liberation Sans', FreeSans, sans-serif;
+ font-size: @font-size;
+ line-height: @line-height;
+}
+
+a:focus {
+ outline: 1px dotted;
+}
+
+hr {
+ border: 0 #ccc solid;
+ border-top-width: 1px;
+ clear: both;
+ height: 0;
+ margin-top: -1px;
+}
+
+.gargantuan {
+ font-weight: bold;
+ font-size: 6em;
+ line-height: 1em;
+}
+
+.enormous {
+ font-weight: bold;
+ font-size: 5em;
+ line-height: 1.2em;
+}
+
+.giant {
+ font-weight: bold;
+ font-size: 4em;
+ line-height: 1.125em;
+}
+
+.huge {
+ font-weight: bold;
+ font-size: 3em;
+ line-height: 1.5em;
+}
+
+.h1 {
+ font-weight: bold;
+ font-size: 2.5em;
+ line-height: 1.2em;
+}
+
+.h2 {
+ font-weight: bold;
+ font-size: 2em;
+ line-height: 1.5em;
+}
+
+.h3 {
+ font-weight: bold;
+ font-size: 1.5em;
+ line-height: @line-height;
+}
+
+.h4 {
+ font-weight: bold;
+ font-size: 1.25em;
+ line-height: @line-height;
+}
+
+.h5 {
+ font-weight: bold;
+ font-size: 1em;
+ line-height: @line-height;
+}
+
+.h6 {
+ font-weight: normal;
+ font-size: 1em;
+ line-height: @line-height;
+}
+
+h1 { .h1; }
+h2 { .h2; }
+h3 { .h3; }
+h4 { .h4; }
+h5 { .h5; }
+h6 { .h6; }
+
+ol {
+ list-style: decimal;
+}
+
+ul {
+ list-style: none;
+}
+
+li {
+ margin-left: 30px;
+}
+
+p,
+dl,
+hr,
+h1,
+h2,
+h3,
+h4,
+h5,
+h6,
+ol,
+ul,
+pre,
+table,
+address,
+fieldset {
+ margin-bottom: @line-height;
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/js/library.js b/User Language Programs/Library Browser/js/library.js
new file mode 100644
index 0000000..ea5f2c0
--- /dev/null
+++ b/User Language Programs/Library Browser/js/library.js
@@ -0,0 +1,23 @@
+google.load('jquery', '1.3.2');
+google.load('jqueryui', '1.7.2');
+
+google.setOnLoadCallback(function() {
+ $(function() {
+ $('#tabs').tabs();
+
+ $('#tabs a[href^=#package-]').click(function() {
+ $('#tabs').tabs('select', '#packages');
+ });
+
+ $('#tabs a[href^=#device-]').click(function() {
+ $('#tabs').tabs('select', '#devices');
+ });
+
+ $('#tabs a[href^=#symbol-]').click(function() {
+ $('#tabs').tabs('select', '#symbols');
+ });
+
+ $('.variants > h4').wrapInner('<a href="#"></a>');
+ $('.variants').accordion({collapsible: true, active: false});
+ });
+});
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/device.html b/User Language Programs/Library Browser/templates/device.html
index 7b9c82c..5f580d7 100644
--- a/User Language Programs/Library Browser/templates/device.html
+++ b/User Language Programs/Library Browser/templates/device.html
@@ -1,23 +1,21 @@
-<div class="device" id="{L.NAME}-devices-{DS.NAME}">
+<div class="device" id="device-{DS.NAME}">
- <h4>{DS.NAME}</h4>
- <img src="../images/{L.NAME}-device-{DS.NAME}.png" />
+ <h2>{DS.NAME}</h2>
+ <img src="../images/{L.NAME}-device-{DS.NAME}.png" alt="{DS.NAME} device" />
<p>{DS.DESC}</p>
- <div class="gates" id="{L.NAME}-devices-{DS.NAME}-gates">
-
- <h5>Gates</h5>
+ <h3>Gates</h3>
+ <div class="gates" id="device-{DS.NAME}-gates">
{GATES}
</div><!-- end gates -->
- <div class="variants" id="{L.NAME}-devices-{DS.NAME}-variants">
-
- <h5>Variants</h5>
+ <h3>Variants</h3>
+ <div class="variants" id="device-{DS.NAME}-variants">
{VARIANTS}
</div><!-- end variants -->
</div><!-- end device -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/gate.html b/User Language Programs/Library Browser/templates/gate.html
index 10362c2..1768188 100644
--- a/User Language Programs/Library Browser/templates/gate.html
+++ b/User Language Programs/Library Browser/templates/gate.html
@@ -1,7 +1,7 @@
-<div class="gate" id="{L.NAME}-devices-{DS.NAME}-gates-{G.NAME}">
+<div class="gate" id="device-{DS.NAME}-gates-{G.NAME}">
- <h6>{G.NAME}</h6>
+ <h4>{G.NAME}</h4>
- <p>Symbol: <a href="#{L.NAME}-symbols-{G.S.NAME}">{G.S.NAME}</a></p>
+ <p>Symbol: <a href="#symbol-{G.S.NAME}">{G.S.NAME}</a></p>
</div><!-- end gate -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/index.html b/User Language Programs/Library Browser/templates/index.html
index 3bbaec6..ac57ef8 100644
--- a/User Language Programs/Library Browser/templates/index.html
+++ b/User Language Programs/Library Browser/templates/index.html
@@ -1,32 +1,2 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
- <title>Monowave Eagle Libraries</title>
-
-</head>
-
-<body>
-<div id="wrapper">
- <ul id="toc">
- {TOC}
- </ul>
-
- <div id="content">
- <h1>Monowave Eagle Libraries</h1>
+ <h1>Introduction</h1>
<p>These libraries are part of the <a href="http://xdissent.github.com/monowave-eagle">Monowave Eagle</a> package. This page was generated with the Library Browser User Language Program, which is also included as part of the package. To use these devices in Eagle, follow the instructions in the <a href="http://github.com/xdissent/monowave-eagle/">README</a>.</p>
-
- {LIBRARY}
-
- </div><!-- end content -->
-
- <div id="footer">
- © 2009 Monowave Labs
- </div>
-
-</div>
-</body>
-</html>
diff --git a/User Language Programs/Library Browser/templates/library.html b/User Language Programs/Library Browser/templates/library.html
index 7023a73..73e96c5 100644
--- a/User Language Programs/Library Browser/templates/library.html
+++ b/User Language Programs/Library Browser/templates/library.html
@@ -1,30 +1,34 @@
<div class="library" id="{L.NAME}">
- <h2>{L.NAME}</h2>
+ <h1>{L.NAME}</h1>
<p>{L.DESC}</p>
- <div class="devices" id="{L.NAME}-devices">
-
- <h3>Devices</h3>
+ <div id="tabs">
+
+ <ul>
+ <li><a href="#devices">Devices</a></li>
+ <li><a href="#packages">Packages</a></li>
+ <li><a href="#symbols">Symbols</a></li>
+ </ul>
+
+ <div id="devices">
- {DEVICES}
+ {DEVICES}
- </div><!-- end devices -->
+ </div><!-- end devices -->
- <div class="packages" id="{L.NAME}-packages">
-
- <h3>Packages</h3>
+ <div id="packages">
- {PACKAGES}
+ {PACKAGES}
- </div><!-- end packages -->
+ </div><!-- end packages -->
- <div class="symbols" id="{L.NAME}-symbols">
+ <div id="symbols">
- <h3>Symbols</h3>
+ {SYMBOLS}
- {SYMBOLS}
-
- </div><!-- end symbols -->
+ </div><!-- end symbols -->
+ </div><!-- end tabs -->
+
</div><!-- end library -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/package.html b/User Language Programs/Library Browser/templates/package.html
index 82a82ff..5cb1c72 100644
--- a/User Language Programs/Library Browser/templates/package.html
+++ b/User Language Programs/Library Browser/templates/package.html
@@ -1,7 +1,7 @@
-<div class="package" id="{L.NAME}-packages-{P.NAME}">
+<div class="package" id="package-{P.NAME}">
- <h4>{P.NAME}</h4>
- <img src="../images/{L.NAME}-package-{P.NAME}.png" />
+ <h2>{P.NAME}</h2>
+ <img src="../images/{L.NAME}-package-{P.NAME}.png" alt="{P.NAME} package" />
<p>{P.DESC}</p>
</div><!-- end package -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/symbol.html b/User Language Programs/Library Browser/templates/symbol.html
index 1b17c15..86f62b1 100644
--- a/User Language Programs/Library Browser/templates/symbol.html
+++ b/User Language Programs/Library Browser/templates/symbol.html
@@ -1,7 +1,7 @@
-<div class="symbol" id="{L.NAME}-symbols-{S.NAME}">
+<div class="symbol" id="symbol-{S.NAME}">
- <h4>{S.NAME}</h4>
+ <h2>{S.NAME}</h2>
- <img src="../images/{L.NAME}-symbol-{S.NAME}.png" />
+ <img src="../images/{L.NAME}-symbol-{S.NAME}.png" alt="{S.NAME} symbol" />
</div><!-- end symbol -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/variant.html b/User Language Programs/Library Browser/templates/variant.html
index e2df44b..996ba1b 100644
--- a/User Language Programs/Library Browser/templates/variant.html
+++ b/User Language Programs/Library Browser/templates/variant.html
@@ -1,11 +1,11 @@
-<div class="variant" id="{L.NAME}-devices-{DS.NAME}-variants-{D.NAME}">
+<h4>{D.NAME}</h4>
+
+<div class="variant" id="devices-{DS.NAME}-variants-{D.NAME}">
- <h6>{D.NAME}</h6>
-
- <p>Package: <a href="#{L.NAME}-packages-{D.P.NAME}">{D.P.NAME}</a></p>
+ <p>Package: <a href="#package-{D.P.NAME}">{D.P.NAME}</a></p>
<p>Attributes:</p>
<dl>
{ATTRIBUTES}
</dl>
</div><!-- end variant -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/wrapper.html b/User Language Programs/Library Browser/templates/wrapper.html
new file mode 100644
index 0000000..53637aa
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/wrapper.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+
+ <link rel="stylesheet" href="../css/library.css" type="text/css" media="screen, projection" />
+ <link rel="stylesheet" href="../css/jqueryui-theme/theme.css" type="text/css" media="screen, projection" />
+ <script type="text/javascript" src="http://www.google.com/jsapi"></script>
+ <script type="text/javascript" src="../js/library.js"></script>
+ <title>Monowave Eagle Libraries</title>
+
+</head>
+
+<body>
+<div id="wrapper">
+ <div id="header">
+ <p>Monowave Eagle Libraries</p>
+ </div>
+
+ <div id="sidebar">
+ <p><a href="index.html">Introduction</a></p>
+ <p>Libraries</p>
+ <ul id="toc">
+ {TOC}
+ </ul>
+ </div>
+
+ <div id="content">
+
+ {CONTENT}
+
+ </div><!-- end content -->
+
+ <div id="footer">
+ <p>
+ <a href="http://validator.w3.org/check?uri=referer">
+ <img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Strict" />
+ </a>
+ </p>
+ <p>© 2009 Monowave Labs</p>
+ </div>
+
+</div>
+</body>
+</html>
|
xdissent/monowave-eagle
|
67fcc6f91db86434d6b4fc95feba99dcc20b759b
|
Added library browser ULP.
|
diff --git a/User Language Programs/Library Browser/Combine Templates.ulp b/User Language Programs/Library Browser/Combine Templates.ulp
new file mode 100644
index 0000000..45cdb06
--- /dev/null
+++ b/User Language Programs/Library Browser/Combine Templates.ulp
@@ -0,0 +1,69 @@
+/**
+ * str_replace
+ *
+ * Replaces all occurrences of a substring found within a string.
+ */
+string str_replace(string search, string replace, string subject) {
+ int lastpos = 0;
+ while(strstr(subject, search, lastpos) >= 0) {
+ int pos = strstr(subject, search, lastpos);
+ string before = strsub(subject, 0, pos);
+ string after = strsub(subject, pos + strlen(search));
+ subject = before + replace + after;
+ lastpos = pos + strlen(replace);
+ }
+ return subject;
+}
+
+/**
+ * main
+ *
+ * Combine all the generated library templates.
+ */
+int main() {
+
+ // Set up toc.
+ string toc;
+
+ int i;
+
+ // Find all used libraries and add a link to the toc.
+ for (i = 0; used_libraries[i] != ""; i++) {
+ string lib_name = filesetext(filename(used_libraries[i]), "");
+ string toc_template;
+ fileread(toc_template, filedir(argv[0]) + "templates/toc.html");
+
+ toc_template = str_replace("{L.NAME}", lib_name, toc_template);
+
+ toc = toc + toc_template;
+ }
+
+ // Find all used libraries and wrap their html output with the index template.
+ for (i = 0; used_libraries[i] != ""; i++) {
+ string lib_name = filesetext(filename(used_libraries[i]), "");
+ string index_template;
+ string lib_template;
+
+ fileread(index_template, filedir(argv[0]) + "templates/index.html");
+ fileread(lib_template, filedir(argv[0]) + "html/" + lib_name + ".html");
+
+ index_template = str_replace("{TOC}", toc, index_template);
+ index_template = str_replace("{LIBRARY}", lib_template, index_template);
+
+ output(filedir(argv[0]) + "html/" + lib_name + ".html") {
+ printf(index_template);
+ }
+ }
+
+ // Handle main index file.
+ string index_template;
+ fileread(index_template, filedir(argv[0]) + "templates/index.html");
+ index_template = str_replace("{TOC}", toc, index_template);
+ index_template = str_replace("{LIBRARY}", "", index_template);
+
+ output(filedir(argv[0]) + "html/index.html") {
+ printf(index_template);
+ }
+
+ return(0);
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/Library Browser.ulp b/User Language Programs/Library Browser/Library Browser.ulp
new file mode 100644
index 0000000..9035236
--- /dev/null
+++ b/User Language Programs/Library Browser/Library Browser.ulp
@@ -0,0 +1,54 @@
+/**
+ * Library Browser
+ *
+ * This User Language Program will render an HTML index of an Eagle Library.
+ */
+
+#usage "en: Library Browser\n"
+ "This User Language Program will render an HTML index of an Eagle Library."
+
+/**
+ * main
+ *
+ * Renders the HTML library browser.
+ */
+int main() {
+ // The render script output.
+ string out[];
+
+ // Index for render script output lines.
+ int n = 0;
+
+ // HTML output path. No path separator at the end.
+ string html_root = filedir(argv[0]) + "html";
+
+ // Create temporary render script.
+ string render_script = filedir(argv[0]) + "render.scr";
+
+ // Find all used libraries.
+ for (int i = 0; used_libraries[i] != ""; i++) {
+
+ // Add line to render script, to open this library.
+ out[n++] = "OPEN '" + used_libraries[i] + "'";
+
+ // Add line to render script, to run render ULP for this library.
+ out[n++] = "RUN '" + filedir(argv[0]) + "Process Library.ulp'";
+ }
+
+ // Combine all the templates and finish up.
+ out[n++] = "RUN '" + filedir(argv[0]) + "Combine Templates.ulp'";
+
+ // Close the library editor.
+ out[n++] = "CLOSE";
+
+ // Open output file
+ output(render_script) {
+ printf(strjoin(out, '\n'));
+ }
+
+ // Exit this ULP and run the temporary render script.
+ exit("SCRIPT '" + render_script + "'");
+
+ // We'll never return because `exit()` is used to call a script.
+ return(0);
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/Process Library.ulp b/User Language Programs/Library Browser/Process Library.ulp
new file mode 100644
index 0000000..a64128c
--- /dev/null
+++ b/User Language Programs/Library Browser/Process Library.ulp
@@ -0,0 +1,221 @@
+/**
+ * str_replace
+ *
+ * Replaces all occurrences of a substring found within a string.
+ */
+string str_replace(string search, string replace, string subject) {
+ int lastpos = 0;
+ while(strstr(subject, search, lastpos) >= 0) {
+ int pos = strstr(subject, search, lastpos);
+ string before = strsub(subject, 0, pos);
+ string after = strsub(subject, pos + strlen(search));
+ subject = before + replace + after;
+ lastpos = pos + strlen(replace);
+ }
+ return subject;
+}
+
+/**
+ * main
+ *
+ * Processes a library for the Library Browser ULP.
+ */
+int main() {
+
+ // Only valid in the library editor.
+ library(L) {
+ status("Processing: " + L.name);
+
+ // Template path.
+ string template_root = filedir(argv[0]) + "templates";
+
+ // HTML output path.
+ string html_root = filedir(argv[0]) + "html";
+
+ // Library short name.
+ string lib_name = filesetext(filename(L.name), "");
+
+ // Temporary image script file name.
+ string image_script = filedir(argv[0]) + "images.scr";
+
+ // Image output root path.
+ string image_root = filedir(argv[0]) + "images";
+
+ // Temporary image script output lines.
+ string img_out[];
+
+ // Image script line index.
+ int img_n = 0;
+
+ // Library template substitutions.
+ string devices;
+ string packages;
+ string symbols;
+
+ // Process devicesets.
+ L.devicesets(DS) {
+ status("Processing deviceset: " + DS.name);
+
+ // Read in device.html
+ string device_template;
+ fileread(device_template, template_root + "/device.html");
+
+ // Set up variants.
+ string variants;
+
+ // Process device variants.
+ DS.devices(D) {
+
+ // Set up attributes.
+ string attrs;
+
+ // Crappy loop to handle attrs for technologies.
+ string t[];
+ int n = strsplit(t, D.technologies, ' ');
+ for (int i = 0; i < n; i++) {
+ D.attributes(A, t[i]) {
+ // Read in attribute.html
+ string attr_template;
+ fileread(attr_template, template_root + "/attribute.html");
+
+ // Substitute {A.NAME} in attribute template.
+ attr_template = str_replace("{A.NAME}", A.name, attr_template);
+
+ // Escape substitutions in attributes.
+ string val = str_replace("{", "{", A.value);
+ val = str_replace("}", "}", val);
+
+ // Substitute {A.VALUE} in attribute template.
+ attr_template = str_replace("{A.VALUE}", val, attr_template);
+
+ attrs = attrs + attr_template;
+ }
+ }
+
+ // Read in variant.html
+ string variant_template;
+ fileread(variant_template, template_root + "/variant.html");
+
+ // Substitute {ATTRIBUTES} in variant template.
+ variant_template = str_replace("{ATTRIBUTES}", attrs, variant_template);
+
+ // Substitute {D.NAME} in variant template.
+ variant_template = str_replace("{D.NAME}", D.name, variant_template);
+ // Substitute {D.P.NAME} in variant template.
+ variant_template = str_replace("{D.P.NAME}", D.package.name, variant_template);
+
+ // Add variant_template to variants string.
+ variants = variants + variant_template;
+ }
+
+ // Set up gates.
+ string gates;
+
+ // Process device gates.
+ DS.gates(G) {
+
+ // Read in gate.html
+ string gate_template;
+ fileread(gate_template, template_root + "/gate.html");
+
+ // Substitute {G.S.NAME} in gate template.
+ gate_template = str_replace("{G.S.NAME}", G.symbol.name, gate_template);
+
+ // Substitute {G.NAME} in gate template.
+ gate_template = str_replace("{G.NAME}", G.name, gate_template);
+
+ // Add gate_template to gates string.
+ gates = gates + gate_template;
+ }
+
+ // Substitute variant template for {VARIANTS} in device template.
+ device_template = str_replace("{VARIANTS}", variants, device_template);
+
+ // Substitute gate template for {GATES} in device template.
+ device_template = str_replace("{GATES}", gates, device_template);
+
+ // Substitute {DS.NAME} and {DS.DESC}
+ device_template = str_replace("{DS.NAME}", DS.name, device_template);
+ device_template = str_replace("{DS.DESC}", DS.description, device_template);
+
+ // Substitute device symbol name for {DS.S.NAME}.
+ // device_template = str_replace("{DS.S.NAME}", DS.symbol.name, device_template)
+
+ // Add device template to devices string.
+ devices = devices + device_template;
+
+ // Add image export command to image script.
+ sprintf(img_out[img_n++], "EDIT %s.dev", DS.name);
+ sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-device-%s.png' 300", image_root, lib_name, DS.name);
+ }
+
+ // Process packages.
+ L.packages(P) {
+ status("Processing package: " + P.name);
+
+ // Read in package.html template.
+ string package_template;
+ fileread(package_template, template_root + "/package.html");
+
+ // Substitute {P.NAME} and {P.DESC}
+ package_template = str_replace("{P.NAME}", P.name, package_template);
+ package_template = str_replace("{P.DESC}", P.description, package_template);
+
+ // Add package template to packages string.
+ packages = packages + package_template;
+
+ // Add image export command to image script.
+ sprintf(img_out[img_n++], "EDIT %s.pac", P.name);
+ sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-package-%s.png' 300", image_root, lib_name, P.name);
+ }
+
+ // Process symbols.
+ L.symbols(S) {
+ status("Processing symbol: " + S.name);
+
+ // Read in symbol.html template.
+ string symbol_template;
+ fileread(symbol_template, template_root + "/symbol.html");
+
+ // Substitute {S.NAME}
+ symbol_template = str_replace("{S.NAME}", S.name, symbol_template);
+
+ // Add symbol template to symbols string.
+ symbols = symbols + symbol_template;
+
+ // Add image export command to image script.
+ sprintf(img_out[img_n++], "EDIT %s.sym", S.name);
+ sprintf(img_out[img_n++], "EXPORT IMAGE '%s/%s-symbol-%s.png' 300", image_root, lib_name, S.name);
+ }
+
+ // Read in library.html template.
+ string library_template;
+ fileread(library_template, template_root + "/library.html");
+
+ // Substitute devices string for {DEVICES}.
+ library_template = str_replace("{DEVICES}", devices, library_template);
+ // Substitute packages string for {PACKAGES}.
+ library_template = str_replace("{PACKAGES}", packages, library_template);
+ // Substitute symbols string for {SYMBOLS}.
+ library_template = str_replace("{SYMBOLS}", symbols, library_template);
+
+ // Subtitute {L.NAME} and {L.DESC} in library template.
+ library_template = str_replace("{L.NAME}", lib_name, library_template);
+ library_template = str_replace("{L.DESC}", L.description, library_template);
+
+ // Output rendered library template.
+ output(html_root + "/" + lib_name + ".html") {
+ printf(library_template);
+ }
+
+ // Output image script.
+ output(image_script) {
+ printf(strjoin(img_out, '\n'));
+ }
+
+ // Run image export script for all devices, packages, and symbols.
+ exit("SCRIPT '" + image_script + "'");
+ }
+
+ return(0);
+}
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/attribute.html b/User Language Programs/Library Browser/templates/attribute.html
new file mode 100644
index 0000000..34fff3a
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/attribute.html
@@ -0,0 +1,2 @@
+<dt>{A.NAME}</dt>
+<dd>{A.VALUE}</dd>
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/device.html b/User Language Programs/Library Browser/templates/device.html
new file mode 100644
index 0000000..7b9c82c
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/device.html
@@ -0,0 +1,23 @@
+<div class="device" id="{L.NAME}-devices-{DS.NAME}">
+
+ <h4>{DS.NAME}</h4>
+ <img src="../images/{L.NAME}-device-{DS.NAME}.png" />
+ <p>{DS.DESC}</p>
+
+ <div class="gates" id="{L.NAME}-devices-{DS.NAME}-gates">
+
+ <h5>Gates</h5>
+
+ {GATES}
+
+ </div><!-- end gates -->
+
+ <div class="variants" id="{L.NAME}-devices-{DS.NAME}-variants">
+
+ <h5>Variants</h5>
+
+ {VARIANTS}
+
+ </div><!-- end variants -->
+
+</div><!-- end device -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/gate.html b/User Language Programs/Library Browser/templates/gate.html
new file mode 100644
index 0000000..10362c2
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/gate.html
@@ -0,0 +1,7 @@
+<div class="gate" id="{L.NAME}-devices-{DS.NAME}-gates-{G.NAME}">
+
+ <h6>{G.NAME}</h6>
+
+ <p>Symbol: <a href="#{L.NAME}-symbols-{G.S.NAME}">{G.S.NAME}</a></p>
+
+</div><!-- end gate -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/index.html b/User Language Programs/Library Browser/templates/index.html
new file mode 100644
index 0000000..3bbaec6
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/index.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+
+ <title>Monowave Eagle Libraries</title>
+
+</head>
+
+<body>
+<div id="wrapper">
+ <ul id="toc">
+ {TOC}
+ </ul>
+
+ <div id="content">
+ <h1>Monowave Eagle Libraries</h1>
+ <p>These libraries are part of the <a href="http://xdissent.github.com/monowave-eagle">Monowave Eagle</a> package. This page was generated with the Library Browser User Language Program, which is also included as part of the package. To use these devices in Eagle, follow the instructions in the <a href="http://github.com/xdissent/monowave-eagle/">README</a>.</p>
+
+ {LIBRARY}
+
+ </div><!-- end content -->
+
+ <div id="footer">
+ © 2009 Monowave Labs
+ </div>
+
+</div>
+</body>
+</html>
diff --git a/User Language Programs/Library Browser/templates/library.html b/User Language Programs/Library Browser/templates/library.html
new file mode 100644
index 0000000..7023a73
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/library.html
@@ -0,0 +1,30 @@
+<div class="library" id="{L.NAME}">
+
+ <h2>{L.NAME}</h2>
+ <p>{L.DESC}</p>
+
+ <div class="devices" id="{L.NAME}-devices">
+
+ <h3>Devices</h3>
+
+ {DEVICES}
+
+ </div><!-- end devices -->
+
+ <div class="packages" id="{L.NAME}-packages">
+
+ <h3>Packages</h3>
+
+ {PACKAGES}
+
+ </div><!-- end packages -->
+
+ <div class="symbols" id="{L.NAME}-symbols">
+
+ <h3>Symbols</h3>
+
+ {SYMBOLS}
+
+ </div><!-- end symbols -->
+
+</div><!-- end library -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/package.html b/User Language Programs/Library Browser/templates/package.html
new file mode 100644
index 0000000..82a82ff
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/package.html
@@ -0,0 +1,7 @@
+<div class="package" id="{L.NAME}-packages-{P.NAME}">
+
+ <h4>{P.NAME}</h4>
+ <img src="../images/{L.NAME}-package-{P.NAME}.png" />
+ <p>{P.DESC}</p>
+
+</div><!-- end package -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/symbol.html b/User Language Programs/Library Browser/templates/symbol.html
new file mode 100644
index 0000000..1b17c15
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/symbol.html
@@ -0,0 +1,7 @@
+<div class="symbol" id="{L.NAME}-symbols-{S.NAME}">
+
+ <h4>{S.NAME}</h4>
+
+ <img src="../images/{L.NAME}-symbol-{S.NAME}.png" />
+
+</div><!-- end symbol -->
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/toc.html b/User Language Programs/Library Browser/templates/toc.html
new file mode 100644
index 0000000..2cc8fe0
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/toc.html
@@ -0,0 +1,3 @@
+<li>
+ <a href="{L.NAME}.html">{L.NAME}</a>
+</li>
\ No newline at end of file
diff --git a/User Language Programs/Library Browser/templates/variant.html b/User Language Programs/Library Browser/templates/variant.html
new file mode 100644
index 0000000..e2df44b
--- /dev/null
+++ b/User Language Programs/Library Browser/templates/variant.html
@@ -0,0 +1,11 @@
+<div class="variant" id="{L.NAME}-devices-{DS.NAME}-variants-{D.NAME}">
+
+ <h6>{D.NAME}</h6>
+
+ <p>Package: <a href="#{L.NAME}-packages-{D.P.NAME}">{D.P.NAME}</a></p>
+ <p>Attributes:</p>
+ <dl>
+ {ATTRIBUTES}
+ </dl>
+
+</div><!-- end variant -->
\ No newline at end of file
|
xdissent/monowave-eagle
|
53ac104b74962a1e458b4b9d6c038d2ac48b2406
|
Added note to readme about design rules.
|
diff --git a/README.rst b/README.rst
index 1217fef..d445c80 100644
--- a/README.rst
+++ b/README.rst
@@ -1,260 +1,262 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`. Note that Eagle does some funky file name handling
and different path separators might be required for different platforms. It
looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME/monowave-eagle/Libraries`
**Design Rules** `$HOME/monowave-eagle/Design Rules`
**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
**Scripts** `$EAGLEDIR/scr`
**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the (forthcoming)
BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
-are provided in the `Projects/SPICE Examples` directory. Check the comments in
+are available in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `3` indicating
"clockwise" and `2` is "counterclockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
+* Run the DRC with `Monowave.dru` to check trace widths and clearances.
+
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
5a92f4347536bd6df3390172f35c759bc307d83a
|
Noted that the BOM manager doesn't exist yet.
|
diff --git a/README.rst b/README.rst
index 341640e..1217fef 100644
--- a/README.rst
+++ b/README.rst
@@ -1,259 +1,260 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`. Note that Eagle does some funky file name handling
and different path separators might be required for different platforms. It
looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME/monowave-eagle/Libraries`
**Design Rules** `$HOME/monowave-eagle/Design Rules`
**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
**Scripts** `$EAGLEDIR/scr`
**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
-other parts of this package, like SPICE simulation and the BOM manager.
+other parts of this package, like SPICE simulation and the (forthcoming)
+BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `3` indicating
"clockwise" and `2` is "counterclockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
24f8728306c446442d9a522f50021473dde6f22a
|
Corrected potentiometer notes.
|
diff --git a/README.rst b/README.rst
index 52707b5..341640e 100644
--- a/README.rst
+++ b/README.rst
@@ -1,259 +1,259 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`. Note that Eagle does some funky file name handling
and different path separators might be required for different platforms. It
looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME/monowave-eagle/Libraries`
**Design Rules** `$HOME/monowave-eagle/Design Rules`
**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
**Scripts** `$EAGLEDIR/scr`
**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
-* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
- "clockwise".
+* Pins for potentiometers are named `1`, `2` and `3` with `3` indicating
+ "clockwise" and `2` is "counterclockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
4e4182840645b956e5b76b0c31eb72fa2f250e63
|
Converted backslashes in paths to forward slashes.
|
diff --git a/README.rst b/README.rst
index 3049b73..52707b5 100644
--- a/README.rst
+++ b/README.rst
@@ -1,257 +1,259 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
-`C:\Documents and Settings\Administrator\My Documents\monowave-eagle`. Mac
+`/C:/Documents and Settings/Administrator/My Documents/monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
-have to update `eagle.epf`.
+have to update `eagle.epf`. Note that Eagle does some funky file name handling
+and different path separators might be required for different platforms. It
+looks like the forward slash is pretty much universally compatible though.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
-**Libraries** `$HOME\monowave-eagle\Libraries`
-**Design Rules** `$HOME\monowave-eagle\Design Rules`
-**User Language Programs** `$HOME\monowave-eagle\User Language Programs`
-**Scripts** `$EAGLEDIR\scr`
-**CAM Jobs** `$HOME\monowave-eagle\CAM Jobs`
-**Projects** `$HOME\monowave-eagle\Projects`
+**Libraries** `$HOME/monowave-eagle/Libraries`
+**Design Rules** `$HOME/monowave-eagle/Design Rules`
+**User Language Programs** `$HOME/monowave-eagle/User Language Programs`
+**Scripts** `$EAGLEDIR/scr`
+**CAM Jobs** `$HOME/monowave-eagle/CAM Jobs`
+**Projects** `$HOME/monowave-eagle/Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
"clockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
================= ==============================================
**VAA** Large, unregulated/unfiltered positive supply.
**VBB** Large, regulated/filtered positive supply.
**VCC** General regulated/filtered positive supply.
**VDD** Misc supply.
**VEE** General regulated/filtered negative supply.
**VFF** Large regulated/filtered negative supply.
**VGG** Large unregulated/unfiltered positive supply.
**VHH** - **VZZ** Misc supply.
================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
7b61ca87e633bf5f7abd5562e7076051c98e2800
|
Last table.
|
diff --git a/README.rst b/README.rst
index 4235c53..3049b73 100644
--- a/README.rst
+++ b/README.rst
@@ -1,262 +1,257 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`C:\Documents and Settings\Administrator\My Documents\monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
========================== =============================================
**Libraries** `$HOME\monowave-eagle\Libraries`
**Design Rules** `$HOME\monowave-eagle\Design Rules`
**User Language Programs** `$HOME\monowave-eagle\User Language Programs`
**Scripts** `$EAGLEDIR\scr`
**CAM Jobs** `$HOME\monowave-eagle\CAM Jobs`
**Projects** `$HOME\monowave-eagle\Projects`
========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
"clockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
========= =========
**Layer** `tNames`
**Size** 0.006 in.
**Font** Vector
**Ratio** 8%
**Value** `>NAME`
========= =========
* Each package has a visible value with the following properties:
========= =========
**Layer** `tValues`
**Size** 0.004 in.
**Font** Vector
**Ratio** 8%
**Value** `>VALUE`
========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
- + **VAA**: Large, unregulated/unfiltered positive supply.
-
- + **VBB**: Large, regulated/filtered positive supply.
-
- + **VCC**: General regulated/filtered positive supply.
-
- + **VDD**: Misc supply.
-
- + **VEE**: General regulated/filtered negative supply.
-
- + **VFF**: Large regulated/filtered negative supply.
-
- + **VGG**: Large unregulated/unfiltered positive supply.
-
- + **VHH** - **VZZ**: Misc supply.
+ ================= ==============================================
+ **VAA** Large, unregulated/unfiltered positive supply.
+ **VBB** Large, regulated/filtered positive supply.
+ **VCC** General regulated/filtered positive supply.
+ **VDD** Misc supply.
+ **VEE** General regulated/filtered negative supply.
+ **VFF** Large regulated/filtered negative supply.
+ **VGG** Large unregulated/unfiltered positive supply.
+ **VHH** - **VZZ** Misc supply.
+ ================= ==============================================
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
cac3c242a27416c083bb8bb1a3ac2a9e1a923331
|
Tabulated readme.
|
diff --git a/README.rst b/README.rst
index 6ab7606..4235c53 100644
--- a/README.rst
+++ b/README.rst
@@ -1,265 +1,262 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Get the Source
--------------
Using your preferred Git application, clone
`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
SPICE examples, you may need to update the paths in
`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
is located at
`C:\Documents and Settings\Administrator\My Documents\monowave-eagle`. Mac
users (of which I am one) are out of luck here and will almost definitely
have to update `eagle.epf`.
Eagle Setup
-----------
To use this package, simply add the appropriate paths to your Eagle directory
options (*Options* -> *Directories*). Most of the time your options will look
like the following:
-====================== =============================================
-Libraries `$HOME\monowave-eagle\Libraries`
-Design Rules `$HOME\monowave-eagle\Design Rules`
-User Language Programs `$HOME\monowave-eagle\User Language Programs`
-Scripts `$EAGLEDIR\scr`
-CAM Jobs `$HOME\monowave-eagle\CAM Jobs`
-Projects `$HOME\monowave-eagle\Projects`
-====================== =============================================
+========================== =============================================
+**Libraries** `$HOME\monowave-eagle\Libraries`
+**Design Rules** `$HOME\monowave-eagle\Design Rules`
+**User Language Programs** `$HOME\monowave-eagle\User Language Programs`
+**Scripts** `$EAGLEDIR\scr`
+**CAM Jobs** `$HOME\monowave-eagle\CAM Jobs`
+**Projects** `$HOME\monowave-eagle\Projects`
+========================== =============================================
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
"clockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
- + **Layer**: `tNames`
+ ========= =========
+ **Layer** `tNames`
+ **Size** 0.006 in.
+ **Font** Vector
+ **Ratio** 8%
+ **Value** `>NAME`
+ ========= =========
- + **Size**: 0.006 in.
-
- + **Font**: Vector
-
- + **Ratio**: 8%
-
- + **Value**: `>NAME`
* Each package has a visible value with the following properties:
- + **Layer**: `tValues`
-
- + **Size**: 0.004 in.
-
- + **Font**: Vector
-
- + **Ratio**: 8%
-
- + **Value**: `>VALUE`
+ ========= =========
+ **Layer** `tValues`
+ **Size** 0.004 in.
+ **Font** Vector
+ **Ratio** 8%
+ **Value** `>VALUE`
+ ========= =========
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
+ **VAA**: Large, unregulated/unfiltered positive supply.
+ **VBB**: Large, regulated/filtered positive supply.
+ **VCC**: General regulated/filtered positive supply.
+ **VDD**: Misc supply.
+ **VEE**: General regulated/filtered negative supply.
+ **VFF**: Large regulated/filtered negative supply.
+ **VGG**: Large unregulated/unfiltered positive supply.
+ **VHH** - **VZZ**: Misc supply.
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
5022b6bb477f13fcb7e5bcbbbb91b997189c5562
|
Added setup notes to readme.
|
diff --git a/README.rst b/README.rst
index ffee178..6ab7606 100644
--- a/README.rst
+++ b/README.rst
@@ -1,237 +1,265 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
+Get the Source
+--------------
+
+Using your preferred Git application, clone
+`git://github.com/xdissent/monowave-eagle.git`. If you plan on running the
+SPICE examples, you may need to update the paths in
+`Projects/SPICE Examples/eagle.epf` or make sure your clone of the repository
+is located at
+`C:\Documents and Settings\Administrator\My Documents\monowave-eagle`. Mac
+users (of which I am one) are out of luck here and will almost definitely
+have to update `eagle.epf`.
+
+Eagle Setup
+-----------
+
+To use this package, simply add the appropriate paths to your Eagle directory
+options (*Options* -> *Directories*). Most of the time your options will look
+like the following:
+
+====================== =============================================
+Libraries `$HOME\monowave-eagle\Libraries`
+Design Rules `$HOME\monowave-eagle\Design Rules`
+User Language Programs `$HOME\monowave-eagle\User Language Programs`
+Scripts `$EAGLEDIR\scr`
+CAM Jobs `$HOME\monowave-eagle\CAM Jobs`
+Projects `$HOME\monowave-eagle\Projects`
+====================== =============================================
+
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. A few circuit examples
are provided in the `Projects/SPICE Examples` directory. Check the comments in
the `Eagle to Spice.ulp` file for more information on creating your own SPICE
compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
"clockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
+ **Layer**: `tNames`
+ **Size**: 0.006 in.
+ **Font**: Vector
+ **Ratio**: 8%
+ **Value**: `>NAME`
* Each package has a visible value with the following properties:
+ **Layer**: `tValues`
+ **Size**: 0.004 in.
+ **Font**: Vector
+ **Ratio**: 8%
+ **Value**: `>VALUE`
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
+ **VAA**: Large, unregulated/unfiltered positive supply.
+ **VBB**: Large, regulated/filtered positive supply.
+ **VCC**: General regulated/filtered positive supply.
+ **VDD**: Misc supply.
+ **VEE**: General regulated/filtered negative supply.
+ **VFF**: Large regulated/filtered negative supply.
+ **VGG**: Large unregulated/unfiltered positive supply.
+ **VHH** - **VZZ**: Misc supply.
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
440900b132875762601af87cb6798cb1bf618932
|
Added note about SPICE Examples to readme.
|
diff --git a/README.rst b/README.rst
index 703aa4c..ffee178 100644
--- a/README.rst
+++ b/README.rst
@@ -1,235 +1,237 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
-that aid in manipulating and plotting simulation data. Check the comments in
-the `Eagle to Spice.ulp` file for more information.
+that aid in manipulating and plotting simulation data. A few circuit examples
+are provided in the `Projects/SPICE Examples` directory. Check the comments in
+the `Eagle to Spice.ulp` file for more information on creating your own SPICE
+compatible Eagle parts.
Standard Practices
------------------
If at all possible, you should follow the following guidelines when working
with the libraries and tools in this package:
Symbols
~~~~~~~
* Symbols use a 0.1 inch grid.
* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
* Pins for polarized 2 terminal devices are named `+` and `-`.
* Pins for bipolar transistors are named `C`, `B` and `E`.
* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
"clockwise".
* Pins for operational amplifiers are named `IN-`, `IN+`, `OUT`, `VCC`, and `VDD`
* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
`X` is the gate name. Example: `A2`.
* Pins for supply symbols are named for the common supply net they represent.
For example, the `VCC` symbol will always represent the `VCC` supply.
Packages
~~~~~~~~
* Package pads fall on a 0.1 inch grid where possible.
* Package holes use metric units. Preferred hole sizes:
+ 0.7 mm
+ 0.9 mm
+ 1.1 mm
+ 1.3 mm
* Packages are centered about the origin except when pads won't fall on
the 0.1 inch grid.
* Each package has a visible name with the following properties:
+ **Layer**: `tNames`
+ **Size**: 0.006 in.
+ **Font**: Vector
+ **Ratio**: 8%
+ **Value**: `>NAME`
* Each package has a visible value with the following properties:
+ **Layer**: `tValues`
+ **Size**: 0.004 in.
+ **Font**: Vector
+ **Ratio**: 8%
+ **Value**: `>VALUE`
* The package name appears above the component, left justified.
* The package value appears inside the component where possible, or at
the bottom, left justified.
* All package outlines are 8 mil wide.
Devices
~~~~~~~
* Gates are named `A` and `B` (`C`, `D` etc).
* Single gate devices are named `A`.
* Supply gates are named `SUP`.
* Supply devices may include only supply symbols with a single supply pin
named for the device itself.
* SPICE data is defined on a device if possible.
Schematics
~~~~~~~~~~
* Schematics use a 0.1 inch grid.
* Multiple sheets should be used to separate logical blocks.
* Each sheet should contain a `LETTER` frame with all information filled out.
Changing the value will control the sheet's title.
* The `0` device represents *true* ground. Any other ground symbol must be
connected to an instance of this device to be considered ground. For
example, a `DGND` device may represent all digital ground points in a
circuit, and could be tied to true ground through some kind of filtering
network.
* Each supply voltage should use a different symbol, as follows:
+ **VAA**: Large, unregulated/unfiltered positive supply.
+ **VBB**: Large, regulated/filtered positive supply.
+ **VCC**: General regulated/filtered positive supply.
+ **VDD**: Misc supply.
+ **VEE**: General regulated/filtered negative supply.
+ **VFF**: Large regulated/filtered negative supply.
+ **VGG**: Large unregulated/unfiltered positive supply.
+ **VHH** - **VZZ**: Misc supply.
Boards
~~~~~~
* Boards use a 0.1 inch grid.
* Traces use a 45 degree bend. Avoid 90 degree bends where possible.
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
The Future
----------
The Monowave Labs support files will eventually (and hopefully) include:
* SPICE enabled test point devices which can simulate ammeters,
voltmeters and power meters in SPICE. Each test point will create
a pad on the board layout for easy testing of the actual circuit.
* Keyboard shortcuts for Eagle commands. MOVE, GRID mm, GRID inch and GROUP
are common and should have easy to use shortcuts.
* Better design rules that check for silk screen and pad overlap.
* A BOM manager.
* A Bitscope program to run automated tests to verify a circuit works similarly
to the simulations.
* A User Language Program to generate a SPICE subcircuit for a group of
parts, and automatically create a new Library part which uses that subcircuit
as it's SPICE model. Each explicitly named net in the group would become a pin
and a template symbol could be created for the device. Better yet, a dialog
could let you connect the nets to pins. Pin ordering and placement could also
be configurable. The resulting device could be saved to a library chosen at
runtime also through the dialog.
\ No newline at end of file
|
xdissent/monowave-eagle
|
291556e8de8ec7196d3cfeaa1007c54c12879b5e
|
Added SPICE Examples.
|
diff --git a/Projects/SPICE Examples/BJT Differential Amplifier.cir b/Projects/SPICE Examples/BJT Differential Amplifier.cir
new file mode 100644
index 0000000..7c46ac6
--- /dev/null
+++ b/Projects/SPICE Examples/BJT Differential Amplifier.cir
@@ -0,0 +1,26 @@
+BJT Differential Amplifier
+.CONTROL
+run
+.ENDC
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.TRAN 1uS 10mS
+.CONTROL
+plot INVOUT OUT
+.ENDC
+Q1 INVOUT IN N$3 2N3904
+Q2 OUT 0 N$2 2N3904
+R1 INVOUT VCC 75k
+R2 OUT VCC 75k
+R3 N$1 N$3 1k
+R4 N$1 N$2 1k
+R5 VEE N$1 75k
+VVSIN1 IN 0 AC 1 SIN(0 100mV 1kHz)
+VCC VCC 0 DC 15V
+VEE VEE 0 DC -15V
diff --git a/Projects/SPICE Examples/BJT Differential Amplifier.sch b/Projects/SPICE Examples/BJT Differential Amplifier.sch
new file mode 100644
index 0000000..d1a2902
Binary files /dev/null and b/Projects/SPICE Examples/BJT Differential Amplifier.sch differ
diff --git a/Projects/SPICE Examples/Double Balanced Multiplier.cir b/Projects/SPICE Examples/Double Balanced Multiplier.cir
new file mode 100644
index 0000000..f3035a9
--- /dev/null
+++ b/Projects/SPICE Examples/Double Balanced Multiplier.cir
@@ -0,0 +1,82 @@
+Double Balanced Multiplier
+.CONTROL
+run
+.ENDC
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.SUBCKT OPAMP 1 2 101 102 81
+.model NPN NPN(BF=50000)
+Q1 5 1 7 NPN
+Q2 6 2 8 NPN
+RC1 101 5 95.49
+RC2 101 6 95.49
+RE1 7 4 43.79
+RE2 8 4 43.79
+I1 4 102 0.001
+G1 100 10 6 5 0.0104719
+RP1 10 100 9.549MEG
+CP1 10 100 0.0016667UF
+EOUT 80 100 10 100 1
+RO 80 81 100
+RREF1 101 103 100K
+RREF2 103 102 100K
+EREF 100 0 103 0 1
+R100 100 0 1MEG
+.ENDS
+CC1 MOD N$13 10uF
+CC2 N$14 INVMOD 10uF
+.TRAN 1uS 100mS
+.CONTROL
+plot OUT
+.ENDC
+Q1 COL1 N$3 N$1 2N3904
+Q2 COL2 N$4 N$1 2N3904
+Q3 COL1 N$5 N$2 2N3904
+Q4 COL2 N$6 N$2 2N3904
+Q5 N$1 N$13 N$8 2N3904
+Q6 N$2 N$14 N$9 2N3904
+RR1 COL2 VCC 750
+RR2 COL1 VCC 750
+RR3 IN N$3 47
+RR4 N$4 0 47
+RR5 0 N$5 47
+RR6 N$6 IN 47
+RR7 VEE N$8 680
+RR8 VEE N$9 680
+RR9 N$13 VCC 3k
+RR10 VEE N$13 1k
+RR11 N$14 VCC 3k
+RR12 VEE N$14 1k
+RR13 0 MOD 100k
+RR14 0 INVMOD 100k
+RR15 COL2 N$7 20k
+RR16 N$7 OUT 20k
+RR17 COL1 N$10 15k
+RR18 0 N$10 15k
+XU1 N$10 N$7 VCC VEE OUT OPAMP
+VVSIN1 IN 0 AC 1 SIN(0 1V 440Hz)
+VVSIN2 MOD INVMOD SIN(0 100mV 10Hz)
+VCC VCC 0 DC 15V
+VEE VEE 0 DC -15V
diff --git a/Projects/SPICE Examples/Double Balanced Multiplier.sch b/Projects/SPICE Examples/Double Balanced Multiplier.sch
new file mode 100644
index 0000000..1db0c74
Binary files /dev/null and b/Projects/SPICE Examples/Double Balanced Multiplier.sch differ
diff --git a/Projects/SPICE Examples/Op Amp Buffers.cir b/Projects/SPICE Examples/Op Amp Buffers.cir
new file mode 100644
index 0000000..94b6cfb
--- /dev/null
+++ b/Projects/SPICE Examples/Op Amp Buffers.cir
@@ -0,0 +1,34 @@
+Op Amp Buffers
+.CONTROL
+run
+.ENDC
+.SUBCKT OPAMP 1 2 101 102 81
+.model NPN NPN(BF=50000)
+Q1 5 1 7 NPN
+Q2 6 2 8 NPN
+RC1 101 5 95.49
+RC2 101 6 95.49
+RE1 7 4 43.79
+RE2 8 4 43.79
+I1 4 102 0.001
+G1 100 10 6 5 0.0104719
+RP1 10 100 9.549MEG
+CP1 10 100 0.0016667UF
+EOUT 80 100 10 100 1
+RO 80 81 100
+RREF1 101 103 100K
+RREF2 103 102 100K
+EREF 100 0 103 0 1
+R100 100 0 1MEG
+.ENDS
+.TRAN 1uS 10mS
+.CONTROL
+plot OUT INVOUT
+.ENDC
+R1 IN N$1 100k
+R2 N$1 INVOUT 100k
+XU1A IN OUT VCC VEE OUT OPAMP
+XU1B 0 N$1 VCC VEE INVOUT OPAMP
+VVSIN1 IN 0 AC 1 SIN(0 1V 1kHz)
+VCC VCC 0 DC 10V
+VEE VEE 0 DC -10V
diff --git a/Projects/SPICE Examples/Op Amp Buffers.sch b/Projects/SPICE Examples/Op Amp Buffers.sch
new file mode 100644
index 0000000..1dd611f
Binary files /dev/null and b/Projects/SPICE Examples/Op Amp Buffers.sch differ
diff --git a/Projects/SPICE Examples/Potentiometer Tapers.cir b/Projects/SPICE Examples/Potentiometer Tapers.cir
new file mode 100644
index 0000000..1556275
--- /dev/null
+++ b/Projects/SPICE Examples/Potentiometer Tapers.cir
@@ -0,0 +1,15 @@
+Potentiometer Tapers
+.CONTROL
+run
+.ENDC
+.TRAN 1uS 10mS
+.CONTROL
+plot LINOUT LOGOUT REVLOGOUT
+.ENDC
+RR1CW IN LINOUT 50000.001000
+RR1CCW LINOUT 0 50000.001000
+RR2CW IN LOGOUT 88656.001000
+RR2CCW LOGOUT 0 11344.001000
+RR3CW IN REVLOGOUT 11344.001000
+RR3CCW REVLOGOUT 0 88656.001000
+VVSIN1 IN 0 AC 1 SIN(0 1V 1kHz)
diff --git a/Projects/SPICE Examples/Potentiometer Tapers.sch b/Projects/SPICE Examples/Potentiometer Tapers.sch
new file mode 100644
index 0000000..c315faf
Binary files /dev/null and b/Projects/SPICE Examples/Potentiometer Tapers.sch differ
diff --git a/Projects/SPICE Examples/Voltage Controlled Oscillator.cir b/Projects/SPICE Examples/Voltage Controlled Oscillator.cir
new file mode 100644
index 0000000..a8f1d82
--- /dev/null
+++ b/Projects/SPICE Examples/Voltage Controlled Oscillator.cir
@@ -0,0 +1,49 @@
+Voltage Controlled Oscillator
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.model 2N3904 NPN(Is=6.734f Xti=3 Eg=1.11 Vaf=74.03 Bf=416.4 Ne=1.259
++ Ise=6.734f Ikf=66.78m Xtb=1.5 Br=.7371 Nc=2 Isc=0 Ikr=0 Rc=1
++ Cjc=3.638p Mjc=.3085 Vjc=.75 Fc=.5 Cje=4.493p Mje=.2593 Vje=.75
++ Tr=239.5n Tf=301.2p Itf=.4 Vtf=4 Xtf=2 Rb=10)
+.SUBCKT OPAMP 1 2 101 102 81
+.model NPN NPN(BF=50000)
+Q1 5 1 7 NPN
+Q2 6 2 8 NPN
+RC1 101 5 95.49
+RC2 101 6 95.49
+RE1 7 4 43.79
+RE2 8 4 43.79
+I1 4 102 0.001
+G1 100 10 6 5 0.0104719
+RP1 10 100 9.549MEG
+CP1 10 100 0.0016667UF
+EOUT 80 100 10 100 1
+RO 80 81 100
+RREF1 101 103 100K
+RREF2 103 102 100K
+EREF 100 0 103 0 1
+R100 100 0 1MEG
+.ENDS
+CC1 TRIANGLE N$1 0.01uF
+.CONTROL
+tran 1000uS 10S
+setplot tran1
+plot TRIANGLE SQUARE
+.ENDC
+Q1 N$9 N$8 0 2N3904
+Q2 VCC SQUARE N$7 2N3904
+RR1 IN N$1 100k
+RR2 IN N$2 49.9k
+RR3 0 N$2 49.9k
+RR4 N$9 N$1 49.9k
+RR5 0 N$5 100k
+RR6 N$5 VCC 100k
+RR7 N$5 SQUARE 100k
+RR8 N$8 N$7 10k
+RR9 0 N$7 47k
+XU1A N$2 N$1 VCC 0 TRIANGLE OPAMP
+XU1B N$5 TRIANGLE VCC 0 SQUARE OPAMP
+VCC VCC 0 10V
+VIN IN 0 9V
diff --git a/Projects/SPICE Examples/Voltage Controlled Oscillator.sch b/Projects/SPICE Examples/Voltage Controlled Oscillator.sch
new file mode 100644
index 0000000..1b24c52
Binary files /dev/null and b/Projects/SPICE Examples/Voltage Controlled Oscillator.sch differ
diff --git a/Projects/SPICE Examples/eagle.epf b/Projects/SPICE Examples/eagle.epf
new file mode 100644
index 0000000..abbb97b
--- /dev/null
+++ b/Projects/SPICE Examples/eagle.epf
@@ -0,0 +1,28 @@
+[Eagle]
+Version="05 06 00"
+Platform="Windows"
+Serial="20F4CAA25D-LSR-DOWL-NCP"
+Globals="Globals"
+Desktop="Desktop"
+
+[Globals]
+AutoSaveProject=1
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Frames.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Op Amps.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/SPICE Tools.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Supply.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Switches.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Transistors.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Resistors.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Capacitors.lbr"
+UsedLibrary="C:/Documents and Settings/Administrator/My Documents/monowave-eagle/Libraries/Passives/Potentiometers.lbr"
+
+[Win_1]
+Type="Control Panel"
+Loc="770 394 1369 793"
+State=2
+Number=0
+
+[Desktop]
+Screen="1920 1178"
+Window="Win_1"
|
xdissent/monowave-eagle
|
73af8317a8fc5300f7043e78dee3ecfed7191c12
|
Added run command to SPICE circuits automatically in Eagle to Spice ULP. Updated SPICE tools to use .TRAN instead of MacSpice specific commands.
|
diff --git a/Libraries/SPICE Tools.lbr b/Libraries/SPICE Tools.lbr
index a7d91a9..90270cb 100644
Binary files a/Libraries/SPICE Tools.lbr and b/Libraries/SPICE Tools.lbr differ
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index a0e34c1..ac57cc6 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,437 +1,439 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
* Global SPICE data for a schematic can be added to the "SPICE" global
* attribute. It is recommended that you define things like VCC the supply
* voltage globally. Note that Global SPICE data may only contain attribute
* substitutions, newlines, operations.
*
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
* Placeholder Replacement
* ----------- -----------
* {NAME} The name of the part in the schematic.
* {VALUE} The value of the part in the schematic.
* {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is
* attached.
* {ATTR.<ATTR>} The value of the attribute named <ATTR>.
* \n A newline character. This is required for multiline SPICE data
* because Eagle does not allow multiline attributes for parts.
*
* Example:
* ATTRIBUTE C1 'SPICE' 'C{NAME} {A.NET} {C.NET} {VALUE}'
*
* Operations
* ==========
*
* "SPICE" attributes may contain simple operations to calculate complex values
* at runtime. Operations may be nested and always return a real value without
* units. Either term in the operation may contain a scale factor and/or units,
* and conversion to a real number will be done before the operation is evaluated.
*
* Available operations:
*
* Operator Operation
* -------- ---------
* LN <RIGHT> Natural logarithm of value.
* LOG <RIGHT> Base 10 logarithm of value.
* <LEFT> / <RIGHT> Division.
* <LEFT> * <RIGHT> Multiplication.
* <LEFT> + <RIGHT> Addition.
* <LEFT> - <RIGHT> Subtraction.
*
* Example:
* ATTRIBUTE R1 'SPICE' 'R{NAME} {1.NET} {2.NET} {{{VALUE} * {{ATTR.POSITION} / 100}} + 0.001}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_rreplace
*
* Replaces all occurrences of a regex pattern found within a string.
*
* Care has been taken to ensure that the replacement text is never
* tested against the regex to prevent infinite loops.
*/
string str_rreplace(string search, string replace, string subject) {
int lastpos = 0;
while (strxstr(subject, search, lastpos) >= 0) {
int len = 0;
int pos = strxstr(subject, search, lastpos, len);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_trim
*
* Removes whitespace from the beginning and end of a string.
* If the scale factor isn't one of the predefined SPICE values,
* 1 will be returned.
*
*/
string str_trim(string subject) {
int pos = 0;
int len = 0;
pos = strxstr(subject, "\\S+", pos, len);
return strsub(subject, pos, len);
}
/**
* scale_to_multiplier
*
* Returns the multiplier for the given scale.
*
* The scale will be trimmed of whitespace before processing.
*
* Example: "K" => 1000
*
*/
real scale_to_multiplier(string scale) {
scale = strupr(str_trim(scale));
if (scale == "T") {
return pow(10, 12);
} else if (scale == "G") {
return pow(10, 9);
} else if (scale == "MEG") {
return pow(10, 6);
} else if (scale == "K") {
return pow(10, 3);
} else if (scale == "MIL") {
return 2.54 * pow(10, -6);
} else if (scale == "M") {
return pow(10, -3);
} else if (scale == "U") {
return pow(10, -6);
} else if (scale == "N") {
return pow(10, -9);
} else if (scale == "P") {
return pow(10, -12);
} else if (scale == "F") {
return pow(10, -15);
}
return 1;
}
/**
* str_to_units
*
* Converts a string to a real value taking into account the units supplied.
*
* If the subject supplied has non-numeric characters at the beginning, they are
* removed. If the value cannot be parsed, 0.0 will be returned. If units are
* supplied, they will also be removed.
*
* Example: "100k" => 1000, "2.2uF" => 0.0000022
*/
real str_to_units(string subject) {
real value = 0.0;
int len = 0;
// Find first integer or real value.
int pos = strxstr(subject, "[\\d\\.]*", 0, len);
if (pos >= 0) {
// Extract found integer or real and convert to real.
value = strtod(strsub(subject, pos, len));
// Find first scale factor if any.
pos = strxstr(strupr(subject), "(MIL|MEG|T|G|K|M|U|N|P|F)", pos, len);
if (pos >= 0) {
// Multiply the value by the scale factor.
value = value * scale_to_multiplier(strsub(subject, pos, len));
}
}
return value;
}
/**
* math_replace
*
* Replaces all math operations with the calculated value.
*
* This function currently evaluates the following operations:
* / Division
* * Multiplication
* + Addition
* - Subtraction
* LEN Logarithm
* LOG Natural logarithm
* EXP Raise the left term to the power of the right.
*
* Example: {100k * {5 * 2.2k}}
*/
string math_replace(string subject) {
// Regex to find math operators in a substitution.
string operator_re = "((\\s+[*/+\\-])|log|LOG|ln|LN|exp|EXP)\\s+";
// Regex to find math substitutions.
string substitution_re = "\\{[^{}]*" + operator_re + "[^{}]+\\}";
// Loop through all possible math substitutions.
while (strxstr(subject, substitution_re, 0) >= 0) {
// The length of the substitution.
int len = 0;
// Find the position of the substitution.
int pos = strxstr(subject, substitution_re, 0, len);
// Save the text before and after this substitution.
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
// Get the substitution.
string substitution = strsub(subject, pos, len);
// Find the operator.
int operator_len = 0;
int operator_pos = strxstr(substitution, operator_re, 0, operator_len);
// The left term (if it exists);
real left = str_to_units(str_trim(strsub(substitution, 1, operator_pos)));
// The operator.
string operator = strupr(str_trim(strsub(substitution, operator_pos, operator_len)));
// The right term.
real right = str_to_units(str_trim(strsub(substitution, operator_pos + operator_len - 1)));
// The calculated value.
real value = 0;
// Do the math.
if (operator == "+") {
value = left + right;
} else if(operator == "-") {
value = left - right;
} else if(operator == "*") {
value = left * right;
} else if(operator == "/") {
value = left / right;
} else if(operator == "LOG") {
value = log10(right);
} else if(operator == "LN") {
value = log(right);
} else if(operator == "EXP") {
value = pow(left, right);
}
// make the substitution
sprintf(subject, "%s%f%s", before, value, after);
}
return subject;
}
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
// Return value.
int ret = 0;
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
// Determine the filename.
string outfile = filesetext(SCHEM.name, ".cir");
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
// Substitute the pin net name for "{G.P.NET}" where "G" is the gate name.
out = str_replace("{" + I.gate.name + "." + PIN.name + ".NET}", PIN.net, out);
}
}
// Iterate over each part attribute.
P.attributes(A) {
// Substitute value of attribute named "A" for "{ATTR.A}"
out = str_replace("{ATTR." + A.name + "}", A.value, out);
}
// Evaluate operations.
out = math_replace(out);
// Handle newlines last so other substitutions can use them.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Process global SPICE data.
SCHEM.attributes(A) {
if (A.name == "SPICE") {
string out = A.value;
// Iterate over other global attributes.
SCHEM.attributes(B) {
out = str_replace("{ATTR." + B.name + "}", B.value, out);
}
// Evaluate operations.
out = math_replace(out);
// Handle newlines.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Open output file
output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
+ // Automatically run simulations. Must be first command.
+ printf(".CONTROL\nrun\n.ENDC\n");
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
/**
* Launch the file.
*
* Mac OS X
* --------
*
* The `open` command will handle everything perfectly.
*
* Windows
* -------
*
* This needs to be done with the `start` windows shell command to
* open the output file with the preferred application. It's a huge
* headache to use `start` directly from Eagle though. To make it,
* easier, we've included the `open.exe` utility, which accepts a
* filename argument.
*/
// Check for drive letter and colon to determine OS.
if (strchr(outfile, ':') == 1) {
// Windows host.
ret = system(filedir(argv[0]) + "open.exe \"" + outfile + "\"");
} else {
// Mac host.
ret = system("open \"" + outfile + "\"");
}
}
}
return ret;
}
\ No newline at end of file
|
xdissent/monowave-eagle
|
78b96b8545ae418d2f1014eebd5a90b3d11d6c7b
|
Added LF347 op amp. Added LM348 op amp.
|
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
index 999252c..d09dbbb 100644
Binary files a/Libraries/Op Amps.lbr and b/Libraries/Op Amps.lbr differ
|
xdissent/monowave-eagle
|
eb03549400f6d57161aa870092658c0b61406fd4
|
Added EXP operator to Eagle to Spice ULP.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index c794f1a..a0e34c1 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,433 +1,437 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
* Global SPICE data for a schematic can be added to the "SPICE" global
* attribute. It is recommended that you define things like VCC the supply
* voltage globally. Note that Global SPICE data may only contain attribute
* substitutions, newlines, operations.
*
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
* Placeholder Replacement
* ----------- -----------
* {NAME} The name of the part in the schematic.
* {VALUE} The value of the part in the schematic.
* {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is
* attached.
* {ATTR.<ATTR>} The value of the attribute named <ATTR>.
* \n A newline character. This is required for multiline SPICE data
* because Eagle does not allow multiline attributes for parts.
*
* Example:
* ATTRIBUTE C1 'SPICE' 'C{NAME} {A.NET} {C.NET} {VALUE}'
*
* Operations
* ==========
*
* "SPICE" attributes may contain simple operations to calculate complex values
* at runtime. Operations may be nested and always return a real value without
* units. Either term in the operation may contain a scale factor and/or units,
* and conversion to a real number will be done before the operation is evaluated.
*
* Available operations:
*
* Operator Operation
* -------- ---------
* LN <RIGHT> Natural logarithm of value.
* LOG <RIGHT> Base 10 logarithm of value.
* <LEFT> / <RIGHT> Division.
* <LEFT> * <RIGHT> Multiplication.
* <LEFT> + <RIGHT> Addition.
* <LEFT> - <RIGHT> Subtraction.
*
* Example:
* ATTRIBUTE R1 'SPICE' 'R{NAME} {1.NET} {2.NET} {{{VALUE} * {{ATTR.POSITION} / 100}} + 0.001}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_rreplace
*
* Replaces all occurrences of a regex pattern found within a string.
*
* Care has been taken to ensure that the replacement text is never
* tested against the regex to prevent infinite loops.
*/
string str_rreplace(string search, string replace, string subject) {
int lastpos = 0;
while (strxstr(subject, search, lastpos) >= 0) {
int len = 0;
int pos = strxstr(subject, search, lastpos, len);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_trim
*
* Removes whitespace from the beginning and end of a string.
* If the scale factor isn't one of the predefined SPICE values,
* 1 will be returned.
*
*/
string str_trim(string subject) {
int pos = 0;
int len = 0;
pos = strxstr(subject, "\\S+", pos, len);
return strsub(subject, pos, len);
}
/**
* scale_to_multiplier
*
* Returns the multiplier for the given scale.
*
* The scale will be trimmed of whitespace before processing.
*
* Example: "K" => 1000
*
*/
real scale_to_multiplier(string scale) {
scale = strupr(str_trim(scale));
if (scale == "T") {
return pow(10, 12);
} else if (scale == "G") {
return pow(10, 9);
} else if (scale == "MEG") {
return pow(10, 6);
} else if (scale == "K") {
return pow(10, 3);
} else if (scale == "MIL") {
return 2.54 * pow(10, -6);
} else if (scale == "M") {
return pow(10, -3);
} else if (scale == "U") {
return pow(10, -6);
} else if (scale == "N") {
return pow(10, -9);
} else if (scale == "P") {
return pow(10, -12);
} else if (scale == "F") {
return pow(10, -15);
}
return 1;
}
/**
* str_to_units
*
* Converts a string to a real value taking into account the units supplied.
*
* If the subject supplied has non-numeric characters at the beginning, they are
* removed. If the value cannot be parsed, 0.0 will be returned. If units are
* supplied, they will also be removed.
*
* Example: "100k" => 1000, "2.2uF" => 0.0000022
*/
real str_to_units(string subject) {
real value = 0.0;
int len = 0;
// Find first integer or real value.
int pos = strxstr(subject, "[\\d\\.]*", 0, len);
if (pos >= 0) {
// Extract found integer or real and convert to real.
value = strtod(strsub(subject, pos, len));
// Find first scale factor if any.
pos = strxstr(strupr(subject), "(MIL|MEG|T|G|K|M|U|N|P|F)", pos, len);
if (pos >= 0) {
// Multiply the value by the scale factor.
value = value * scale_to_multiplier(strsub(subject, pos, len));
}
}
return value;
}
/**
* math_replace
*
* Replaces all math operations with the calculated value.
*
* This function currently evaluates the following operations:
* / Division
* * Multiplication
* + Addition
* - Subtraction
* LEN Logarithm
- * LOG Natural logarithm
+ * LOG Natural logarithm
+ * EXP Raise the left term to the power of the right.
*
* Example: {100k * {5 * 2.2k}}
*/
string math_replace(string subject) {
// Regex to find math operators in a substitution.
- string operator_re = "((\\s+[*/+\\-])|log|LOG|LN|ln)\\s+";
+ string operator_re = "((\\s+[*/+\\-])|log|LOG|ln|LN|exp|EXP)\\s+";
// Regex to find math substitutions.
string substitution_re = "\\{[^{}]*" + operator_re + "[^{}]+\\}";
// Loop through all possible math substitutions.
while (strxstr(subject, substitution_re, 0) >= 0) {
// The length of the substitution.
int len = 0;
// Find the position of the substitution.
int pos = strxstr(subject, substitution_re, 0, len);
// Save the text before and after this substitution.
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
// Get the substitution.
string substitution = strsub(subject, pos, len);
// Find the operator.
int operator_len = 0;
int operator_pos = strxstr(substitution, operator_re, 0, operator_len);
// The left term (if it exists);
real left = str_to_units(str_trim(strsub(substitution, 1, operator_pos)));
// The operator.
string operator = strupr(str_trim(strsub(substitution, operator_pos, operator_len)));
// The right term.
real right = str_to_units(str_trim(strsub(substitution, operator_pos + operator_len - 1)));
// The calculated value.
real value = 0;
// Do the math.
if (operator == "+") {
value = left + right;
} else if(operator == "-") {
value = left - right;
} else if(operator == "*") {
value = left * right;
} else if(operator == "/") {
value = left / right;
} else if(operator == "LOG") {
value = log10(right);
} else if(operator == "LN") {
value = log(right);
+ } else if(operator == "EXP") {
+ value = pow(left, right);
}
// make the substitution
sprintf(subject, "%s%f%s", before, value, after);
}
return subject;
}
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
// Return value.
int ret = 0;
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
// Determine the filename.
string outfile = filesetext(SCHEM.name, ".cir");
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
+
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
// Substitute the pin net name for "{G.P.NET}" where "G" is the gate name.
out = str_replace("{" + I.gate.name + "." + PIN.name + ".NET}", PIN.net, out);
}
}
// Iterate over each part attribute.
P.attributes(A) {
// Substitute value of attribute named "A" for "{ATTR.A}"
out = str_replace("{ATTR." + A.name + "}", A.value, out);
}
// Evaluate operations.
out = math_replace(out);
// Handle newlines last so other substitutions can use them.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Process global SPICE data.
SCHEM.attributes(A) {
if (A.name == "SPICE") {
string out = A.value;
// Iterate over other global attributes.
SCHEM.attributes(B) {
out = str_replace("{ATTR." + B.name + "}", B.value, out);
}
// Evaluate operations.
out = math_replace(out);
// Handle newlines.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Open output file
output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
/**
* Launch the file.
*
* Mac OS X
* --------
*
* The `open` command will handle everything perfectly.
*
* Windows
* -------
*
* This needs to be done with the `start` windows shell command to
* open the output file with the preferred application. It's a huge
* headache to use `start` directly from Eagle though. To make it,
* easier, we've included the `open.exe` utility, which accepts a
* filename argument.
*/
// Check for drive letter and colon to determine OS.
if (strchr(outfile, ':') == 1) {
// Windows host.
ret = system(filedir(argv[0]) + "open.exe \"" + outfile + "\"");
} else {
// Mac host.
ret = system("open \"" + outfile + "\"");
}
}
}
return ret;
}
\ No newline at end of file
|
xdissent/monowave-eagle
|
790da8ec6907ab967f1ab8c5049f984d1d75c934
|
Removed automatic plotting from signal generator.
|
diff --git a/Libraries/SPICE Tools.lbr b/Libraries/SPICE Tools.lbr
index 8c9dfa4..a7d91a9 100644
Binary files a/Libraries/SPICE Tools.lbr and b/Libraries/SPICE Tools.lbr differ
|
xdissent/monowave-eagle
|
a044a710bd342085973f0af6c5f17e3a85855ce3
|
Added SPICE data for potentiometers with different tapers.
|
diff --git a/Libraries/Passives/Potentiometers.lbr b/Libraries/Passives/Potentiometers.lbr
index bc6ee96..4f0e19c 100644
Binary files a/Libraries/Passives/Potentiometers.lbr and b/Libraries/Passives/Potentiometers.lbr differ
|
xdissent/monowave-eagle
|
6828b4722c5846b644c6c7eb6372c97490dd9c6b
|
Added prefix FRM to frames.
|
diff --git a/Libraries/Frames.lbr b/Libraries/Frames.lbr
index b7c9dc5..9b875a6 100644
Binary files a/Libraries/Frames.lbr and b/Libraries/Frames.lbr differ
|
xdissent/monowave-eagle
|
3c1be6253fb4e7e7ce1290f01e2b727267647389
|
Fixed screwy characters that were breaking the op amps library.
|
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
index 8751d17..999252c 100644
Binary files a/Libraries/Op Amps.lbr and b/Libraries/Op Amps.lbr differ
|
xdissent/monowave-eagle
|
1b2d87d48b2494839722f56b6606752436155501
|
Added operations to Eagle to Spice ULP.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index 8c39cda..f09fda9 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,231 +1,408 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
* Global SPICE data for a schematic can be added to the "SPICE" global
* attribute. It is recommended that you define things like VCC the supply
* voltage globally.
*
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
* Placeholder Replacement
* ----------- -----------
* {NAME} The name of the part in the schematic.
* {VALUE} The value of the part in the schematic.
* {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is
* attached.
* {ATTR.<ATTR>} The value of the attribute named <ATTR>.
* \n A newline character. This is required for multiline SPICE data
* because Eagle does not allow multiline attributes for parts.
*
* Example:
- * ATTRIBUTE C1 'SPICE' '{NAME} {A.NET} {C.NET} {VALUE}'
+ * ATTRIBUTE C1 'SPICE' 'C{NAME} {A.NET} {C.NET} {VALUE}'
+ *
+ * Operations
+ * ==========
+ *
+ * "SPICE" attributes may contain simple operations to calculate complex values
+ * at runtime. Operations may be nested and always return a real value without
+ * units. Either term in the operation may contain a scale factor and/or units,
+ * and conversion to a real number will be done before the operation is evaluated.
+ *
+ * Available operations:
+ *
+ * Operator Operation
+ * -------- ---------
+ * LN <RIGHT> Natural logarithm of value.
+ * LOG <RIGHT> Base 10 logarithm of value.
+ * <LEFT> / <RIGHT> Division.
+ * <LEFT> * <RIGHT> Multiplication.
+ * <LEFT> + <RIGHT> Addition.
+ * <LEFT> - <RIGHT> Subtraction.
+ *
+ * Example:
+ * ATTRIBUTE R1 'SPICE' 'R{NAME} {1.NET} {2.NET} {{{VALUE} * {{ATTR.POSITION} / 100}} + 0.001}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_rreplace
*
* Replaces all occurrences of a regex pattern found within a string.
*
* Care has been taken to ensure that the replacement text is never
* tested against the regex to prevent infinite loops.
*/
string str_rreplace(string search, string replace, string subject) {
int lastpos = 0;
- while(strxstr(subject, search, lastpos) >= 0) {
+ while (strxstr(subject, search, lastpos) >= 0) {
int len = 0;
int pos = strxstr(subject, search, lastpos, len);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
+/**
+ * str_trim
+ *
+ * Removes whitespace from the beginning and end of a string.
+ *
+ */
+string str_trim(string subject) {
+ int pos = 0;
+ int len = 0;
+ pos = strxstr(subject, "\\S+", pos, len);
+ return strsub(subject, pos, len);
+}
+
+/**
+ * scale_to_multiplier
+ *
+ * Returns the multiplier for the given scale.
+ *
+ * Example: "K" => 1000
+ *
+ */
+real scale_to_multiplier(string scale) {
+ scale = strupr(scale);
+
+ if (scale == "") {
+ return 1;
+ } else if (scale == "T") {
+ return pow(10, 12);
+ } else if (scale == "G") {
+ return pow(10, 9);
+ } else if (scale == "MEG") {
+ return pow(10, 6);
+ } else if (scale == "K") {
+ return pow(10, 3);
+ } else if (scale == "MIL") {
+ return 2.54 * pow(10, -6);
+ } else if (scale == "M") {
+ return pow(10, -3);
+ } else if (scale == "U") {
+ return pow(10, -6);
+ } else if (scale == "N") {
+ return pow(10, -9);
+ } else if (scale == "P") {
+ return pow(10, -12);
+ } else if (scale == "F") {
+ return pow(10, -15);
+ }
+ return 0;
+}
+
+/**
+ * str_to_units
+ *
+ * Converts a string to a real value taking into account the units supplied.
+ *
+ * Example: "100k" => 1000, "2.2uF" => 0.0000022
+ */
+real str_to_units(string subject) {
+ real value = 0.0;
+ int len = 0;
+
+ // Find first integer or real value.
+ int pos = strxstr(subject, "[\\d\\.]*", 0, len);
+ if (pos >= 0) {
+
+ // Extract found integer or real and convert to real.
+ value = strtod(strsub(subject, pos, len));
+
+ // Find first scale factor if any.
+ pos = strxstr(strupr(subject), "(MIL|MEG|T|G|K|M|U|N|P|F)", pos, len);
+ if (pos >= 0) {
+
+ // Multiply the value by the scale factor.
+ value = value * scale_to_multiplier(strsub(subject, pos, len));
+ }
+ }
+ return value;
+}
+
+/**
+ * math_replace
+ *
+ * Replaces all math operations with the calculated value.
+ *
+ * This function currently evaluates the following operations:
+ * / Division
+ * * Multiplication
+ * + Addition
+ * - Subtraction
+ * LEN Logarithm
+ * LOG Natural logarithm
+ *
+ * Example: {100k * {5 * 2.2k}}
+ */
+string math_replace(string subject) {
+ // Regex to find math operators in a substitution.
+ string operator_re = "((\\s+[*/+\\-])|log|LOG|LN|ln)\\s+";
+
+ // Regex to find math substitutions.
+ string substitution_re = "\\{[^{}]*" + operator_re + "[^{}]+\\}";
+
+ // Loop through all possible math substitutions.
+ while (strxstr(subject, substitution_re, 0) >= 0) {
+
+ // The length of the substitution.
+ int len = 0;
+
+ // Find the position of the substitution.
+ int pos = strxstr(subject, substitution_re, 0, len);
+
+ // Save the text before and after this substitution.
+ string before = strsub(subject, 0, pos);
+ string after = strsub(subject, pos + len);
+
+ // Get the substitution.
+ string substitution = strsub(subject, pos, len);
+
+ // Find the operator.
+ int operator_len = 0;
+ int operator_pos = strxstr(substitution, operator_re, 0, operator_len);
+
+ // The left term (if it exists);
+ real left = str_to_units(str_trim(strsub(substitution, 1, operator_pos)));
+
+ // The operator.
+ string operator = strupr(str_trim(strsub(substitution, operator_pos, operator_len)));
+
+ // The right term.
+ real right = str_to_units(str_trim(strsub(substitution, operator_pos + operator_len - 1)));
+
+ // The calculated value.
+ real value = 0;
+
+ // Do the math.
+ if (operator == "+") {
+ value = left + right;
+ } else if(operator == "-") {
+ value = left - right;
+ } else if(operator == "*") {
+ value = left * right;
+ } else if(operator == "/") {
+ value = left / right;
+ } else if(operator == "LOG") {
+ value = log10(right);
+ } else if(operator == "LN") {
+ value = log(right);
+ }
+
+ // make the substitution
+ sprintf(subject, "%s%f%s", before, value, after);
+ }
+
+ return subject;
+}
+
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
// Return value.
int ret = 0;
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
// Determine the filename.
string outfile = filesetext(SCHEM.name, ".cir");
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
// Substitute the pin net name for "{G.P.NET}" where "G" is the gate name.
out = str_replace("{" + I.gate.name + "." + PIN.name + ".NET}", PIN.net, out);
}
}
// Iterate over each part attribute.
P.attributes(A) {
// Substitute value of attribute named "A" for "{ATTR.A}"
out = str_replace("{ATTR." + A.name + "}", A.value, out);
}
// Handle newlines last so other substitutions can use them.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Process global SPICE data.
SCHEM.attributes(A) {
if (A.name == "SPICE") {
string out = A.value;
// Handle newlines.
out = str_replace("\\n", "\n", out);
netlist[n++] = out;
}
}
// Open output file
output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
/**
* Launch the file.
*
* Mac OS X
* --------
*
* The `open` command will handle everything perfectly.
*
* Windows
* -------
*
* This needs to be done with the `start` windows shell command to
* open the output file with the preferred application. It's a huge
* headache to use `start` directly from Eagle though. To make it,
* easier, we've included the `open.exe` utility, which accepts a
* filename argument.
*/
// Check for drive letter and colon to determine OS.
if (strchr(outfile, ':') == 1) {
// Windows host.
ret = system(filedir(argv[0]) + "open.exe \"" + outfile + "\"");
} else {
// Mac host.
ret = system("open \"" + outfile + "\"");
}
}
}
return ret;
}
\ No newline at end of file
|
xdissent/monowave-eagle
|
80faa19ea8f5b150b3c3abdf47b2b956b39ca07b
|
Added TextMate temp files to .gitignore.
|
diff --git a/.gitignore b/.gitignore
index 496a39a..6f1edf6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
*.?#[0-9#]
.DS_Store
+._*
|
xdissent/monowave-eagle
|
fdf9ca37cf84bfc20cda38889cb457ffd39229fe
|
Added attribute substitution and global attributes to Eagle to Spice ULP.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index e319b02..8c39cda 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,204 +1,231 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
+ * Global SPICE data for a schematic can be added to the "SPICE" global
+ * attribute. It is recommended that you define things like VCC the supply
+ * voltage globally.
+ *
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
- * Placeholder Replacement
- * ----------- -----------
- * {NAME} The name of the part in the schematic.
- * {VALUE} The value of the part in the schematic.
- * {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is attached.
- * \n A newline character. This is required for multiline SPICE data
- * because Eagle does not allow multiline attributes for parts.
+ * Placeholder Replacement
+ * ----------- -----------
+ * {NAME} The name of the part in the schematic.
+ * {VALUE} The value of the part in the schematic.
+ * {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is
+ * attached.
+ * {ATTR.<ATTR>} The value of the attribute named <ATTR>.
+ * \n A newline character. This is required for multiline SPICE data
+ * because Eagle does not allow multiline attributes for parts.
*
* Example:
* ATTRIBUTE C1 'SPICE' '{NAME} {A.NET} {C.NET} {VALUE}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
int lastpos = 0;
while(strstr(subject, search, lastpos) >= 0) {
int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* str_rreplace
*
* Replaces all occurrences of a regex pattern found within a string.
*
* Care has been taken to ensure that the replacement text is never
* tested against the regex to prevent infinite loops.
*/
string str_rreplace(string search, string replace, string subject) {
int lastpos = 0;
while(strxstr(subject, search, lastpos) >= 0) {
int len = 0;
int pos = strxstr(subject, search, lastpos, len);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + len);
subject = before + replace + after;
lastpos = pos + strlen(replace);
}
return subject;
}
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
// Return value.
int ret = 0;
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
// Determine the filename.
string outfile = filesetext(SCHEM.name, ".cir");
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
-
- // Handle newlines.
- out = str_replace("\\n", "\n", out);
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
+
+ // Substitute the pin net name for "{G.P.NET}" where "G" is the gate name.
+ out = str_replace("{" + I.gate.name + "." + PIN.name + ".NET}", PIN.net, out);
}
}
+ // Iterate over each part attribute.
+ P.attributes(A) {
+ // Substitute value of attribute named "A" for "{ATTR.A}"
+ out = str_replace("{ATTR." + A.name + "}", A.value, out);
+ }
+
+ // Handle newlines last so other substitutions can use them.
+ out = str_replace("\\n", "\n", out);
+
+ netlist[n++] = out;
+ }
+ }
+
+ // Process global SPICE data.
+ SCHEM.attributes(A) {
+ if (A.name == "SPICE") {
+ string out = A.value;
+
+ // Handle newlines.
+ out = str_replace("\\n", "\n", out);
+
netlist[n++] = out;
}
}
// Open output file
output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
/**
* Launch the file.
*
* Mac OS X
* --------
*
* The `open` command will handle everything perfectly.
*
* Windows
* -------
*
* This needs to be done with the `start` windows shell command to
* open the output file with the preferred application. It's a huge
* headache to use `start` directly from Eagle though. To make it,
* easier, we've included the `open.exe` utility, which accepts a
* filename argument.
*/
// Check for drive letter and colon to determine OS.
if (strchr(outfile, ':') == 1) {
// Windows host.
ret = system(filedir(argv[0]) + "open.exe \"" + outfile + "\"");
} else {
// Mac host.
ret = system("open \"" + outfile + "\"");
}
}
}
return ret;
}
\ No newline at end of file
|
xdissent/monowave-eagle
|
83fc8a9da06662e96531169ee916f479471a4c5e
|
Added standard op-amps and their SPICE data.
|
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
index 3496f39..8751d17 100644
Binary files a/Libraries/Op Amps.lbr and b/Libraries/Op Amps.lbr differ
|
xdissent/monowave-eagle
|
c1c8aa02128e08cdf735627acbbb5f7ee0255811
|
Changed SPICE tools to be configured using attributes.
|
diff --git a/Libraries/SPICE Tools.lbr b/Libraries/SPICE Tools.lbr
new file mode 100644
index 0000000..8c9dfa4
Binary files /dev/null and b/Libraries/SPICE Tools.lbr differ
|
xdissent/monowave-eagle
|
a61e5a6e5df33fe44577be3699cb397ca9015559
|
Added SPICE data for MC14007 to CMOS library.
|
diff --git a/Libraries/CMOS.lbr b/Libraries/CMOS.lbr
index 8c9aea9..5562a8b 100644
Binary files a/Libraries/CMOS.lbr and b/Libraries/CMOS.lbr differ
|
xdissent/monowave-eagle
|
eb298ec9686026c0aa0a3813507fef1a9cf42313
|
Recreated all switch possibilities in a more manageable sorting arrangement. Added SPICE data for all switches.
|
diff --git a/Libraries/Switches.lbr b/Libraries/Switches.lbr
index 9ef0422..00d40a3 100644
Binary files a/Libraries/Switches.lbr and b/Libraries/Switches.lbr differ
|
xdissent/monowave-eagle
|
a97f53b65f564a0a78b12072ed35a9130d4fce5e
|
Changed DIP14 in CMOS library to metric.
|
diff --git a/Libraries/CMOS.lbr b/Libraries/CMOS.lbr
index e6e9c65..8c9aea9 100644
Binary files a/Libraries/CMOS.lbr and b/Libraries/CMOS.lbr differ
|
xdissent/monowave-eagle
|
292df9134c0faf289025da006240f7131fa1650c
|
Moved 1n4148 to variant of DIODE. Added ideal diode spice model. Added DO-35 package and removed old metric package.
|
diff --git a/Libraries/Diodes.lbr b/Libraries/Diodes.lbr
index 2d44034..d44d947 100644
Binary files a/Libraries/Diodes.lbr and b/Libraries/Diodes.lbr differ
|
xdissent/monowave-eagle
|
0c0cb9a3d5ff0a1f6c453d1a5043191e79e19be3
|
Added value to control sheet title in document fields.
|
diff --git a/Libraries/Frames.lbr b/Libraries/Frames.lbr
index 83eb9ae..b7c9dc5 100644
Binary files a/Libraries/Frames.lbr and b/Libraries/Frames.lbr differ
|
xdissent/monowave-eagle
|
0a932da5da66964d01402e9614addb89df60678b
|
Added standard practices to readme.
|
diff --git a/README.rst b/README.rst
index e3a3e1e..ec5cc6f 100644
--- a/README.rst
+++ b/README.rst
@@ -1,76 +1,193 @@
Eagle Support Files for Monowave Labs
=====================================
This package contains all libraries, user scripts, CAM files, etc. which are
used in the design and production of Monowave Labs circuit boards.
Device Libraries
----------------
Complete, standardized Eagle libraries are hard to come by. We created our
own from scratch to eliminate all the guesswork involved with using the
default Eagle libraries. In addition to providing a consistency that helps
us sleep better at night, these libraries contain devices compatible with
other parts of this package, like SPICE simulation and the BOM manager.
SPICE Simulation
----------------
A User Language Program exists, Eagle to Spice, which allows you to generate
a SPICE compatible circuit. Most devices in the Monowave libraries already
contain SPICE data for circuit simulation, and special devices are provided
that aid in manipulating and plotting simulation data. Check the comments in
the `Eagle to Spice.ulp` file for more information.
+Standard Practices
+------------------
+
+If at all possible, you should follow the following guidelines when working
+with the libraries and tools in this package:
+
+Symbols
+~~~~~~~
+
+* Symbols use a 0.1 inch grid.
+
+* Pins for non-polarized devices are named `1` and `2` (`3`, `4` etc).
+
+* Pins for polarized 2 terminal devices are named `+` and `-`.
+
+* Pins for bipolar transistors are named `C`, `B` and `E`.
+
+* Pins for potentiometers are named `1`, `2` and `3` with `1` indicating
+ "clockwise".
+
+* Pins for multi-ganged potentiometers are named `X1`, `X2` and `X3` where
+ `X` is the gate name. Example: `A2`.
+
+* Pins for supply symbols are named for the common supply net they represent.
+ For example, the `VCC` symbol will always represent the `VCC` supply.
+
+Packages
+~~~~~~~~
+
+* Package pads fall on a 0.1 inch grid where possible.
+
+* Package holes use metric units. Preferred hole sizes:
+
+ + 0.7 mm
+
+ + 0.9 mm
+
+ + 1.1 mm
+
+ + 1.3 mm
+
+* Packages are centered about the origin except when pads won't fall on
+ the 0.1 inch grid.
+
+* Each package has a visible name with the following properties:
+
+ + **Layer**: `tNames`
+
+ + **Size**: 0.006 in.
+
+ + **Font**: Vector
+
+ + **Ratio**: 0.08
+
+ + **Value**: `>NAME`
+
+* Each package has a visible value with the following properties:
+
+ + **Layer**: `tValues`
+
+ + **Size**: 0.004 in.
+
+ + **Font**: Vector
+
+ + **Ratio**: 0.08
+
+ + **Value**: `>VALUE`
+
+* The package name appears above the component, left justified.
+
+* The package value appears inside the component where possible, or at
+ the bottom, left justified.
+
+Devices
+~~~~~~~
+
+* Gates are named `A` and `B` (`C`, `D` etc).
+
+* Supply devices may include only supply symbols with a single supply pin
+ named for the device itself.
+
+Schematics
+~~~~~~~~~~
+
+* Schematics use a 0.1 inch grid.
+
+* Multiple sheets should be used to separate logical blocks.
+
+* The `0` device represents *true* ground. Any other ground symbol must be
+ connected to an instance of this device to be considered ground. For
+ example, a `DGND` device may represent all digital ground points in a
+ circuit, and could be tied to true ground through some kind of filtering
+ network.
+
+* Each supply voltage should use a different symbol, as follows:
+
+ + **VAA**: Large, unregulated/unfiltered positive supply.
+
+ + **VBB**: Large, regulated/filtered positive supply.
+
+ + **VCC**: General regulated/filtered positive supply.
+
+ + **VDD**: Misc supply.
+
+ + **VEE**: General regulated/filtered negative supply.
+
+ + **VFF**: Large regulated/filtered negative supply.
+
+ + **VGG**: Large unregulated/unfiltered positive supply.
+
+ + **VHH** - **VZZ**: Misc supply.
+
+Boards
+~~~~~~
+
+* Boards use a 0.1 inch grid.
+
Metric vs Imperial
------------------
A lot of thought was put into coming up with standard measurement grids for
use in the Monowave libraries. Initially, every pad and hole was laid out on
a metric grid with 1mm spacing. We really wanted to go full-on metric to
stand aside our more progressive world citizens and make it easier to
interact with foreign board houses and manufacturers who primarily are
tooled to operate in metric units. Unfortunately there were a few obstacles
which led to our abandonment of this grandiose ideal for a 0.1 inch grid.
Firstly, the schematic editor uses a 0.1 inch grid. That means every pin
on each symbol also has to land on a 0.1 inch grid or you won't be able
to connect any nets to pins. Eagle is pretty stubborn about this detail
and chances are EVERY library or schematic you get from any other Eagle
user will use a 0.1 inch grid, so it's practically impossible to get around
imperial here. That means half of the Eagle experience is already out of
the question for metric. It's not the fact the board and schematic grids
*have* to agree, but that they *wouldn't* - that's the first strike
against the use of metric in product design.
History, unfortunately, is also not on metric's side of the debate either
it seems. Since the ridiculous majority of early semiconductors were designed
right here in the good old USA, the footprint standards that arose happened
to make heavy use of imperial grids. Most designs will use a least a DIP or
two, which automatically ties you to a 0.1 inch grid lead spacing. So we've
got a decades old invisible hand pushing us further back towards imperial.
Of course, most actual devices are *manufactured* in a metric friendly country
regardless of the origins of their design. That means the overwhelming
majority of parts will have data sheets using metric units. Every measurement
would have to be converted to metric before placing a pad if the grid
is was set to imperial. And with more and more manufacturers converting to
metric, the problem is only going to get worse.
The good news is conversion is simple in Eagle, because you can freely change
the grid back and forth from imperial to metric without altering the pad
placement. Regardless of the chosen standard grid, as long as the part is
centered, it won't mess things up. Things only get confusing if you are
editing parts that use different internal grids.
Since a lot of designs are prototyped on a breadboard, it makes sense to
go with a grid that translates well to an actual PCB design. Breadboards all
use a 0.1 inch grid to accommodate DIPs, so laying out a board on the same
grid is like second nature.
It's obvious that any choice is a compromise in this situation, but the
benefits of using an imperial grid outweigh the warm fuzzy feeling we'd get
by using metric. In the future it might make sense to switch, and we'd love
to. But for now the rule of thumb is to use a 0.1 inch grid in *every*
situation. We apologize to the rest of the industrialized world for succumbing
to im*peer*ial pressure...
\ No newline at end of file
|
xdissent/monowave-eagle
|
770702c0ad0cfc8468dc781d750a32af55655ce5
|
Added OS detection to open spice circuit with appropriate application.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index 861674d..e319b02 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,155 +1,204 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
* Placeholder Replacement
* ----------- -----------
* {NAME} The name of the part in the schematic.
* {VALUE} The value of the part in the schematic.
* {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is attached.
* \n A newline character. This is required for multiline SPICE data
* because Eagle does not allow multiline attributes for parts.
*
* Example:
* ATTRIBUTE C1 'SPICE' '{NAME} {A.NET} {C.NET} {VALUE}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
- while(strstr(subject, search) >= 0) {
- int pos = strstr(subject, search);
+ int lastpos = 0;
+ while(strstr(subject, search, lastpos) >= 0) {
+ int pos = strstr(subject, search, lastpos);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
+ lastpos = pos + strlen(replace);
+ }
+ return subject;
+}
+
+/**
+ * str_rreplace
+ *
+ * Replaces all occurrences of a regex pattern found within a string.
+ *
+ * Care has been taken to ensure that the replacement text is never
+ * tested against the regex to prevent infinite loops.
+ */
+string str_rreplace(string search, string replace, string subject) {
+ int lastpos = 0;
+ while(strxstr(subject, search, lastpos) >= 0) {
+ int len = 0;
+ int pos = strxstr(subject, search, lastpos, len);
+ string before = strsub(subject, 0, pos);
+ string after = strsub(subject, pos + len);
+ subject = before + replace + after;
+ lastpos = pos + strlen(replace);
}
return subject;
}
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
// Return value.
int ret = 0;
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
// Determine the filename.
string outfile = filesetext(SCHEM.name, ".cir");
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
}
}
netlist[n++] = out;
}
}
// Open output file
output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
- // Try to launch the spice file.
+ /**
+ * Launch the file.
+ *
+ * Mac OS X
+ * --------
+ *
+ * The `open` command will handle everything perfectly.
+ *
+ * Windows
+ * -------
+ *
+ * This needs to be done with the `start` windows shell command to
+ * open the output file with the preferred application. It's a huge
+ * headache to use `start` directly from Eagle though. To make it,
+ * easier, we've included the `open.exe` utility, which accepts a
+ * filename argument.
+ */
+
+ // Check for drive letter and colon to determine OS.
+ if (strchr(outfile, ':') == 1) {
+ // Windows host.
+ ret = system(filedir(argv[0]) + "open.exe \"" + outfile + "\"");
+ } else {
+ // Mac host.
+ ret = system("open \"" + outfile + "\"");
+ }
+
}
}
return ret;
}
\ No newline at end of file
diff --git a/User Language Programs/open.exe b/User Language Programs/open.exe
new file mode 100644
index 0000000..f17dd74
Binary files /dev/null and b/User Language Programs/open.exe differ
|
xdissent/monowave-eagle
|
cf2af526eeedc2ab5d0afc79f84fbac10fe83445
|
Trying to get MacSpice to launch.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
index e233a4a..861674d 100644
--- a/User Language Programs/Eagle to Spice.ulp
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -1,146 +1,155 @@
/**
* Eagle to Spice
*
* This User Language Program will generate a SPICE circuit from an Eagle
* schematic, ready for simulation.
*
* To incorporate SPICE data into your Eagle schematic, parts can be given
* a "SPICE" attribute. The value of this attribute will be used to generate
* the SPICE netlist for that part. It may contain placeholders for any of the
* available substitutions (see below) or any other valid SPICE data.
*
* It is recommended that you add "SPICE" attributes to the Eagle Library
* devices you want to use in simulations. These attributes are inherited by
* instances of that device automatically, and can be overridden in the
* schematic for specific parts that need tweaking. The monowave-eagle
* package (http://github.com/xdissent/monowave-eagle), in which this file
* is included, contains valid SPICE data for most devices in its libraries,
* as well as a few useful devices used specifically for SPICE simulations.
*
* Substitutions
* =============
*
* The "SPICE" attribute for an Eagle part may contain placeholders, which
* will be replaced with a value determined at runtime to generate the
* SPICE netlist for that part. This allows you to include part specific data
* in the SPICE netlist when defining the "SPICE" attribute for the Eagle
* device.
*
* Available substitutions:
*
* Placeholder Replacement
* ----------- -----------
* {NAME} The name of the part in the schematic.
* {VALUE} The value of the part in the schematic.
* {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is attached.
* \n A newline character. This is required for multiline SPICE data
* because Eagle does not allow multiline attributes for parts.
*
* Example:
* ATTRIBUTE C1 'SPICE' '{NAME} {A.NET} {C.NET} {VALUE}'
*
* SPICE Models
* ============
*
* Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
* attribute. The value may only contain the "\n" placeholder. Each model
* is only defined once in the final circuit file. (not implemented yet!)
*
* Example:
* ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
*/
#usage "en: Eagle to Spice\n"
"This User Language Program will generate a SPICE circuit from an Eagle\n"
"schematic, ready for simulation."
/**
* str_replace
*
* Replaces all occurrences of a substring found within a string.
*/
string str_replace(string search, string replace, string subject) {
while(strstr(subject, search) >= 0) {
int pos = strstr(subject, search);
string before = strsub(subject, 0, pos);
string after = strsub(subject, pos + strlen(search));
subject = before + replace + after;
}
return subject;
}
/**
* main
*
* Generates the SPICE circuit.
*/
int main() {
+
+ // Return value.
+ int ret = 0;
+
// Only valid in schematic mode.
if (schematic) {
// Use the entire schematic.
schematic(SCHEM) {
+ // Determine the filename.
+ string outfile = filesetext(SCHEM.name, ".cir");
+
// Create a models array.
string models[];
int m = 0;
// Create a netlist array.
string netlist[];
int n = 0;
// Iterate over each part.
SCHEM.parts(P) {
// Check to see if it has SPICE models defined.
if (P.attribute["SPICEMOD"]) {
// The SPICE data to output.
string out = P.attribute["SPICEMOD"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
models[m++] = out;
}
// Check to see if it has SPICE data defined.
if (P.attribute["SPICE"]) {
// The SPICE data to output.
string out = P.attribute["SPICE"];
// Handle newlines.
out = str_replace("\\n", "\n", out);
// Substitute the name for "{NAME}".
out = str_replace("{NAME}", P.name, out);
// Substitute the value for "{VALUE}".
out = str_replace("{VALUE}", P.value, out);
// Iterate over each part instance.
P.instances(I) {
// Iterate over each instance's pins.
I.gate.symbol.pins(PIN) {
// Substitute the pin net name for "{P.NET}" where "P" is the pin name.
out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
}
}
netlist[n++] = out;
}
}
// Open output file
- output(filesetext(SCHEM.name, ".cir")) {
+ output(outfile) {
printf(filesetext(filename(SCHEM.name), "\n"));
printf(strjoin(models, '\n'));
printf(strjoin(netlist, '\n'));
}
+
+ // Try to launch the spice file.
}
}
- return 0;
+ return ret;
}
\ No newline at end of file
|
xdissent/monowave-eagle
|
06bdec463aa947297cb6ceaa12667413f8aba2f0
|
Fixed supply library.
|
diff --git a/Libraries/Supply.lbr b/Libraries/Supply.lbr
index 6005257..332e20a 100644
Binary files a/Libraries/Supply.lbr and b/Libraries/Supply.lbr differ
|
xdissent/monowave-eagle
|
780beefdd10f76d3112ec9ff20da78925a3f97a5
|
Corrected op amp spice data.
|
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
index 5ee68e8..45c5d77 100644
Binary files a/Libraries/Op Amps.lbr and b/Libraries/Op Amps.lbr differ
|
xdissent/monowave-eagle
|
9dfd9188e25766c9eb721fee95e6d17b07c88a96
|
Added generic NPN device SPICE data.
|
diff --git a/Libraries/Transistors.lbr b/Libraries/Transistors.lbr
index 2b4001e..6cbf13f 100644
Binary files a/Libraries/Transistors.lbr and b/Libraries/Transistors.lbr differ
|
xdissent/monowave-eagle
|
98fbb406dbe0e51db78e519584e66b268fa4fb94
|
Added .DS_Store to git ignore file.
|
diff --git a/.gitignore b/.gitignore
index ff3a7d1..496a39a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
*.?#[0-9#]
+.DS_Store
|
xdissent/monowave-eagle
|
25e7f8a947e463a62e5a1ce079e5250f820c8394
|
Added SPICE data to diodes, resistors, capacitors, and supply libraries.
|
diff --git a/Libraries/Diodes.lbr b/Libraries/Diodes.lbr
index 6406bce..2d44034 100644
Binary files a/Libraries/Diodes.lbr and b/Libraries/Diodes.lbr differ
diff --git a/Libraries/Passives/Capacitors.lbr b/Libraries/Passives/Capacitors.lbr
index 5ed90b5..0cff343 100644
Binary files a/Libraries/Passives/Capacitors.lbr and b/Libraries/Passives/Capacitors.lbr differ
diff --git a/Libraries/Passives/Resistors.lbr b/Libraries/Passives/Resistors.lbr
index 6323de0..6b56fdc 100644
Binary files a/Libraries/Passives/Resistors.lbr and b/Libraries/Passives/Resistors.lbr differ
diff --git a/Libraries/Supply.lbr b/Libraries/Supply.lbr
index c470aab..6005257 100644
Binary files a/Libraries/Supply.lbr and b/Libraries/Supply.lbr differ
|
xdissent/monowave-eagle
|
542a0eac327889d9c7972b31d34e2fa9cb2fec6c
|
Added transistors library.
|
diff --git a/Libraries/Transistors.lbr b/Libraries/Transistors.lbr
new file mode 100644
index 0000000..2b4001e
Binary files /dev/null and b/Libraries/Transistors.lbr differ
|
xdissent/monowave-eagle
|
6f9504f9e8cd889d66558cc88cd4751a756fa610
|
Added Eagle to Spice ULP.
|
diff --git a/User Language Programs/Eagle to Spice.ulp b/User Language Programs/Eagle to Spice.ulp
new file mode 100644
index 0000000..a4e934f
--- /dev/null
+++ b/User Language Programs/Eagle to Spice.ulp
@@ -0,0 +1,142 @@
+/**
+ * Eagle to Spice.ulp
+ *
+ * This User Language Program will generate a SPICE circuit from an Eagle
+ * schematic, ready for simulation.
+ *
+ * To incorporate SPICE data into your Eagle schematic, parts can be given
+ * a "SPICE" attribute. The value of this attribute will be used to generate
+ * the SPICE netlist for that part. It may contain placeholders for any of the
+ * available substitutions (see below) or any other valid SPICE data.
+ *
+ * It is recommended that you add "SPICE" attributes to the Eagle Library
+ * devices you want to use in simulations. These attributes are inherited by
+ * instances of that device automatically, and can be overridden in the
+ * schematic for specific parts that need tweaking. The monowave-eagle
+ * package (http://github.com/xdissent/monowave-eagle), in which this file
+ * is included, contains valid SPICE data for most devices in its libraries,
+ * as well as a few useful devices used specifically for SPICE simulations.
+ *
+ * Substitutions
+ * =============
+ *
+ * The "SPICE" attribute for an Eagle part may contain placeholders, which
+ * will be replaced with a value determined at runtime to generate the
+ * SPICE netlist for that part. This allows you to include part specific data
+ * in the SPICE netlist when defining the "SPICE" attribute for the Eagle
+ * device.
+ *
+ * Available substitutions:
+ *
+ * Placeholder Replacement
+ * ----------- -----------
+ * {NAME} The name of the part in the schematic.
+ * {VALUE} The value of the part in the schematic.
+ * {<PIN>.NET} The net (SPICE node) to which the pin named <PIN> is attached.
+ * \n A newline character. This is required for multiline SPICE data
+ * because Eagle does not allow multiline attributes for parts.
+ *
+ * Example:
+ * ATTRIBUTE C1 'SPICE' '{NAME} {A.NET} {C.NET} {VALUE}'
+ *
+ * SPICE Models
+ * ============
+ *
+ * Including SPICE models in Eagle parts is possible by defining the "SPICEMOD"
+ * attribute. The value may only contain the "\n" placeholder. Each model
+ * is only defined once in the final circuit file. (not implemented yet!)
+ *
+ * Example:
+ * ATTRIBUTE D1 'SPICEMOD' '.model 1N4148 D (IS=0.1PA, RS=16 CJO=2PF TT=12N BV=100 IBV=1nA)'
+ */
+
+/**
+ * str_replace
+ *
+ * Replaces all occurrences of a substring found within a string.
+ */
+string str_replace(string search, string replace, string subject) {
+ while(strstr(subject, search) >= 0) {
+ int pos = strstr(subject, search);
+ string before = strsub(subject, 0, pos);
+ string after = strsub(subject, pos + strlen(search));
+ subject = before + replace + after;
+ }
+ return subject;
+}
+
+/**
+ * main
+ *
+ * Generates the SPICE circuit.
+ */
+int main() {
+ // Only valid in schematic mode.
+ if (schematic) {
+
+ // Use the entire schematic.
+ schematic(SCHEM) {
+
+ // Create a models array.
+ string models[];
+ int m = 0;
+
+ // Create a netlist array.
+ string netlist[];
+ int n = 0;
+
+ // Iterate over each part.
+ SCHEM.parts(P) {
+
+ // Check to see if it has SPICE models defined.
+ if (P.attribute["SPICEMOD"]) {
+
+ // The SPICE data to output.
+ string out = P.attribute["SPICEMOD"];
+
+ // Handle newlines.
+ out = str_replace("\\n", "\n", out);
+
+ models[m++] = out;
+ }
+
+ // Check to see if it has SPICE data defined.
+ if (P.attribute["SPICE"]) {
+
+ // The SPICE data to output.
+ string out = P.attribute["SPICE"];
+
+ // Handle newlines.
+ out = str_replace("\\n", "\n", out);
+
+ // Substitute the name for "{NAME}".
+ out = str_replace("{NAME}", P.name, out);
+
+ // Substitute the value for "{VALUE}".
+ out = str_replace("{VALUE}", P.value, out);
+
+ // Iterate over each part instance.
+ P.instances(I) {
+
+ // Iterate over each instance's pins.
+ I.gate.symbol.pins(PIN) {
+
+ // Substitute the pin net name for "{P.NET}" where "P" is the pin name.
+ out = str_replace("{" + PIN.name + ".NET}", PIN.net, out);
+ }
+ }
+
+ netlist[n++] = out;
+ }
+ }
+
+ // Open output file
+ output(filesetext(SCHEM.name, ".cir")) {
+ printf(filesetext(filename(SCHEM.name), "\n"));
+ printf(strjoin(models, '\n'));
+ printf(strjoin(netlist, '\n'));
+ }
+ }
+ }
+ return 0;
+}
\ No newline at end of file
|
xdissent/monowave-eagle
|
1adc6c9a98e269a52fb0732f0d93f49f4a612191
|
Added power jacks, added horizontal switches, and fixed audio jacks.
|
diff --git a/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr
index 048242a..d7a5168 100644
Binary files a/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr and b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr differ
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
index c5be23a..5ee68e8 100644
Binary files a/Libraries/Op Amps.lbr and b/Libraries/Op Amps.lbr differ
diff --git a/Libraries/Passives/Potentiometers.lbr b/Libraries/Passives/Potentiometers.lbr
index f9da605..bc6ee96 100644
Binary files a/Libraries/Passives/Potentiometers.lbr and b/Libraries/Passives/Potentiometers.lbr differ
diff --git a/Libraries/Power Jacks.lbr b/Libraries/Power Jacks.lbr
new file mode 100644
index 0000000..1daa9d6
Binary files /dev/null and b/Libraries/Power Jacks.lbr differ
diff --git a/Libraries/Switches.lbr b/Libraries/Switches.lbr
index dc62f8b..9ef0422 100644
Binary files a/Libraries/Switches.lbr and b/Libraries/Switches.lbr differ
|
xdissent/monowave-eagle
|
fd8ba2184a048ddc6f21fcb564db1ce8aa6eff8e
|
Added diodes library with 1n4148. Added switch library with SPST and DPDT footprints for Multicomp vertical switches.
|
diff --git a/Libraries/Diodes.lbr b/Libraries/Diodes.lbr
new file mode 100644
index 0000000..6406bce
Binary files /dev/null and b/Libraries/Diodes.lbr differ
diff --git a/Libraries/Switches.lbr b/Libraries/Switches.lbr
new file mode 100644
index 0000000..dc62f8b
Binary files /dev/null and b/Libraries/Switches.lbr differ
|
xdissent/monowave-eagle
|
f8fc5338c34bc1daa14a20989c165223104d1447
|
Fixed mis-named carbon film resistor variant.
|
diff --git a/Libraries/Passives/Resistors.lbr b/Libraries/Passives/Resistors.lbr
index 4b4444d..6323de0 100644
Binary files a/Libraries/Passives/Resistors.lbr and b/Libraries/Passives/Resistors.lbr differ
|
xdissent/monowave-eagle
|
046d335bd67405a85b5d1278c5afaffd5b70778b
|
Hid pin names on audio jacks.
|
diff --git a/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr
index 191948a..048242a 100644
Binary files a/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr and b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr differ
|
xdissent/monowave-eagle
|
6060e897465ba2c0df5ba123fd1d8b4b367cf76e
|
Added resistors with standard footprints.
|
diff --git a/Libraries/Passives/Resistors.lbr b/Libraries/Passives/Resistors.lbr
new file mode 100644
index 0000000..4b4444d
Binary files /dev/null and b/Libraries/Passives/Resistors.lbr differ
|
xdissent/monowave-eagle
|
2b5db1b4282f7bae42eeb670328d3690f41959a7
|
Added potentiometers library with 11m top adjustable Alpha pot footprint.
|
diff --git a/Libraries/Passives/Potentiometers.lbr b/Libraries/Passives/Potentiometers.lbr
new file mode 100644
index 0000000..f9da605
Binary files /dev/null and b/Libraries/Passives/Potentiometers.lbr differ
|
xdissent/monowave-eagle
|
4a558837271556c145216e04b7484b86b1ef66ab
|
Added capacitors library with box film, aluminum electrolytic, and tantalum variants.
|
diff --git a/Libraries/Passives/Capacitors.lbr b/Libraries/Passives/Capacitors.lbr
new file mode 100644
index 0000000..5ed90b5
Binary files /dev/null and b/Libraries/Passives/Capacitors.lbr differ
|
xdissent/monowave-eagle
|
2c4ba2bddbe863dff9d63e9f9a21e223b3955d15
|
Added Op Amp library including generic op amps and TL062.
|
diff --git a/Libraries/Op Amps.lbr b/Libraries/Op Amps.lbr
new file mode 100644
index 0000000..c5be23a
Binary files /dev/null and b/Libraries/Op Amps.lbr differ
|
xdissent/monowave-eagle
|
0dcabd4e09967c0bee64e3fbc8825992674790ff
|
Added CMOS library with MC14007.
|
diff --git a/Libraries/CMOS.lbr b/Libraries/CMOS.lbr
new file mode 100644
index 0000000..e6e9c65
Binary files /dev/null and b/Libraries/CMOS.lbr differ
|
xdissent/monowave-eagle
|
b1c716f84b0e5ca1f98d80ac205c6384f16cf60b
|
Added supply library.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ff3a7d1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+*.?#[0-9#]
diff --git a/CAM Jobs/Monowave Gerber Generator.cam b/CAM Jobs/Monowave Gerber Generator.cam
new file mode 100644
index 0000000..4c59026
--- /dev/null
+++ b/CAM Jobs/Monowave Gerber Generator.cam
@@ -0,0 +1,173 @@
+[CAM Processor Job]
+Description[en]="Monowave Labs Gerber Generator\n\nThis CAM job creates the seven needed files to have a PCB created. Based on the original Eagle gerb274x.cam file.\n\nYou will get seven gerber files that contain data for:\n\nGerber Top Layer (copper layer): *.GTL\nGerber Top Overlay (silkscreen layer): *.GTO\nGerber Top Soldermask (soldermask layer): *.GTS\n\nGerber Bottom Layer (copper layer): *.GBL\nGerber Bottom Overlay (silkscreen layer): *.GBO\nGerber Bottom Soldermask (soldermask layer): *.GBS\n\nExcellon Drill File: *.TXT\n\nThese files are required for production of Monowave Labs circuit boards."
+Section=Sec_1
+Section=Sec_2
+Section=Sec_3
+Section=Sec_4
+Section=Sec_5
+Section=Sec_6
+Section=Sec_7
+Section=Sec_8
+Section=Sec_9
+
+[Sec_1]
+Name[en]="Top Copper"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=""
+Rack=""
+Scale=1
+Output=".GTL"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 1 17 18 20"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_2]
+Name[en]="Bottom Copper"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GBL"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 16 17 18"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_3]
+Name[en]="Top Silkscreen"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GTO"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 21"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_4]
+Name[en]="Top Paste"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GTP"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 31"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_5]
+Name[en]="Bottom Silkscreen"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GBO"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 22"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_6]
+Name[en]="Top Soldermask"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GTS"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 29"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_7]
+Name[en]="Bottom Soldermask"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=".whl"
+Rack=""
+Scale=1
+Output=".GBS"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 30"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_8]
+Name[en]="Drill File"
+Prompt[en]=""
+Device="EXCELLON"
+Wheel=""
+Rack=""
+Scale=1
+Output=".TXT"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="12000.0mil 8000.0mil"
+Layers=" 44 45"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
+
+[Sec_9]
+Name[en]="Mill Layer"
+Prompt[en]=""
+Device="GERBER_RS274X"
+Wheel=""
+Rack=""
+Scale=1
+Output=".GML"
+Flags="0 0 0 1 0 1 1"
+Emulate="0 0 0"
+Offset="0.0mil 0.0mil"
+Sheet=1
+Tolerance="0 0 0 0 0 0"
+Pen="0.0mil 0"
+Page="11000.0mil 16000.0mil"
+Layers=" 46"
+Colors=" 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 6 6 4 8 8 8 8 8 8 8 8 8 8 8 8 8 4 4 1 1 1 1 3 3 1 2 6 8 8 5 8 8 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 2 4 3 6 6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0"
diff --git a/Design Rules/Monowave.dru b/Design Rules/Monowave.dru
new file mode 100644
index 0000000..b1905b2
--- /dev/null
+++ b/Design Rules/Monowave.dru
@@ -0,0 +1,72 @@
+description[en] = Monowave Labs Design Rules\n\nThese rules extend the Eagle defaults, tailored for all Monowave Labs projects.
+layerSetup = (1*16)
+mtCopper = 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm 0.035mm
+mtIsolate = 1.5mm 0.15mm 0.2mm 0.15mm 0.2mm 0.15mm 0.2mm 0.15mm 0.2mm 0.15mm 0.2mm 0.15mm 0.2mm 0.15mm 0.2mm
+mdWireWire = 8mil
+mdWirePad = 8mil
+mdWireVia = 8mil
+mdPadPad = 8mil
+mdPadVia = 8mil
+mdViaVia = 8mil
+mdSmdPad = 8mil
+mdSmdVia = 8mil
+mdSmdSmd = 8mil
+mdViaViaSameLayer = 8mil
+mnLayersViaInSmd = 2
+mdCopperDimension = 10mil
+mdDrill = 8mil
+mdSmdStop = 0mil
+msWidth = 8mil
+msDrill = 20mil
+msMicroVia = 9.99mm
+msBlindViaRatio = 0.500000
+rvPadTop = 0.250000
+rvPadInner = 0.250000
+rvPadBottom = 0.250000
+rvViaOuter = 0.250000
+rvViaInner = 0.250000
+rvMicroViaOuter = 0.250000
+rvMicroViaInner = 0.250000
+rlMinPadTop = 12mil
+rlMaxPadTop = 20mil
+rlMinPadInner = 10mil
+rlMaxPadInner = 20mil
+rlMinPadBottom = 12mil
+rlMaxPadBottom = 20mil
+rlMinViaOuter = 10mil
+rlMaxViaOuter = 20mil
+rlMinViaInner = 10mil
+rlMaxViaInner = 20mil
+rlMinMicroViaOuter = 4mil
+rlMaxMicroViaOuter = 20mil
+rlMinMicroViaInner = 4mil
+rlMaxMicroViaInner = 20mil
+psTop = -1
+psBottom = -1
+psFirst = -1
+psElongationLong = 100
+psElongationOffset = 100
+mvStopFrame = 1.000000
+mvCreamFrame = 0.000000
+mlMinStopFrame = 4mil
+mlMaxStopFrame = 4mil
+mlMinCreamFrame = 0mil
+mlMaxCreamFrame = 0mil
+mlViaStopLimit = 25mil
+srRoundness = 0.000000
+srMinRoundness = 0mil
+srMaxRoundness = 0mil
+slThermalGap = 0.500000
+slMinThermalGap = 20mil
+slMaxThermalGap = 100mil
+slAnnulusIsolate = 20mil
+slThermalIsolate = 10mil
+slAnnulusRestring = 0
+slThermalRestring = 1
+slThermalsForVias = 0
+checkGrid = 0
+checkAngle = 0
+checkFont = 1
+checkRestrict = 1
+useDiameter = 13
+maxErrors = 50
diff --git a/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr
new file mode 100644
index 0000000..191948a
Binary files /dev/null and b/Libraries/Audio Jacks/Audio Jacks 0.25 inch.lbr differ
diff --git a/Libraries/Frames.lbr b/Libraries/Frames.lbr
new file mode 100644
index 0000000..83eb9ae
Binary files /dev/null and b/Libraries/Frames.lbr differ
diff --git a/Libraries/Supply.lbr b/Libraries/Supply.lbr
new file mode 100644
index 0000000..c470aab
Binary files /dev/null and b/Libraries/Supply.lbr differ
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..aa50094
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,5 @@
+Eagle Support Files for Monowave Labs
+=====================================
+
+This package contains all libraries, user scripts, CAM files, etc. which are
+used in the design and production of Monowave Labs circuit boards.
\ No newline at end of file
|
gary-rafferty/RlzyCall
|
2f1cbb7cea047c3b3f34bbf25721a7fc8a0b7470
|
Added some TODO features
|
diff --git a/README b/README
index be6272e..56bd3fd 100644
--- a/README
+++ b/README
@@ -1,9 +1,14 @@
RlzyCall
A really simple utility for android.
Displays a list of contacts, sends a Meteor "call-me" message to whomever you select.
This just makes things a little bit easier than the usual way of texting the recepients number to 50001
Based on droid 1.5 as that's what my HTC hero is running.
+TODO:
+Add support for selecting multiple contacts
+Add support for removing selected contacts
+Have the confirmation dialog confirm selected contacts
+
|
gary-rafferty/RlzyCall
|
6c6660374a7ab174c025b118878f603169546fe7
|
Added README
|
diff --git a/README b/README
new file mode 100644
index 0000000..be6272e
--- /dev/null
+++ b/README
@@ -0,0 +1,9 @@
+RlzyCall
+
+A really simple utility for android.
+
+Displays a list of contacts, sends a Meteor "call-me" message to whomever you select.
+This just makes things a little bit easier than the usual way of texting the recepients number to 50001
+
+Based on droid 1.5 as that's what my HTC hero is running.
+
|
ryanwood/rails-templates
|
4b7c9a5bdeb490da35d7def84debab589c169fd7
|
Updating versions and other minor issues
|
diff --git a/authentication.rb b/authentication.rb
index 2ac6150..9ee2cb9 100644
--- a/authentication.rb
+++ b/authentication.rb
@@ -1,245 +1,254 @@
# Sets up authentication using AuthLogic
# Depends on HAML
gem 'authlogic'
# Session
generate(:session, "user_session")
generate(:controller, "user_sessions") # Call generate mainly for the tests
# Session Controller
file "app/controllers/user_sessions_controller.rb", <<CODE
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
redirect_to account_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
redirect_to new_user_session_url
end
end
CODE
# Login Form
file "app/views/user_sessions/new.html.haml", <<CODE
+%h1 Login
- form_for @user_session, :url => user_session_path do |f|
= f.error_messages
%p
= f.label :login
%br
= f.text_field :login
%p
= f.label :password
%br
= f.password_field :password
%p
= f.submit "Login"
CODE
# User Management
generate(:controller, "users") # for tests
file "app/controllers/users_controller.rb", <<CODE
class UsersController < ApplicationController
# before_filter :require_no_user, :only => [:new, :create]
before_filter :login_required, :only => [:show, :edit, :update]
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Account registered!"
redirect_back_or_default account_url
else
render :action => :new
end
end
def show
@user = @current_user
end
def edit
@user = @current_user
end
def update
@user = @current_user # makes our views "cleaner" and more consistent
if @user.update_attributes(params[:user])
flash[:notice] = "Account updated!"
redirect_to account_url
else
render :action => :edit
end
end
end
CODE
generate(:model, "user --skip-migration --skip-fixture") # for tests
file "app/models/user.rb", <<CODE
class User < ActiveRecord::Base
acts_as_authentic
+
+ def name
+ "#{first_name} #{last_name}"
+ end
end
CODE
# User Views
file "app/views/users/_form.html.haml", <<CODE
%p
= form.label :first_name
%br
= form.text_field :first_name
%p
= form.label :last_name
%br
= form.text_field :last_name
%p
= form.label :email
%br
= form.text_field :email
%p
= form.label :login
%br
= form.text_field :login
%p
= form.label :password, form.object.new_record? ? nil : "Change password"
%br
= form.password_field :password
%p
= form.label :password_confirmation
%br
= form.password_field :password_confirmation
CODE
file "app/views/users/new.html.haml", <<CODE
%h1 Register
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Register"
CODE
file "app/views/users/edit.html.haml", <<CODE
%h1 Edit my Account
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Update"
%p= link_to "My Profile", account_path
CODE
file "app/views/users/show.html.haml", <<CODE
+%h1 Your Account
+%p
+ %strong Name:
+ =h @user.name
%p
%strong Login:
=h @user.login
%p
%strong Login Count:
=h @user.login_count
%p
%strong Last request at:
=h @user.last_request_at
%p
%strong Last login at:
=h @user.last_login_at
%p
%strong Current login at::
=h @user.current_login_at
%p
%strong Last login ip:
=h @user.last_login_ip
%p
%strong Current login ip:
=h @user.current_login_ip
%p= link_to 'Edit', edit_account_path
CODE
# Create user migration manually for User
file "db/migrate/#{Time.now.strftime('%Y%m%d%H%M%S')}_create_users.rb", <<CODE
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :login, :null => false # optional, you can use email instead, or both
t.string :email, :null => false # optional, you can use login instead, or both
t.string :crypted_password, :null => false # optional, see below
t.string :password_salt, :null => false # optional, but highly recommended
t.string :persistence_token, :null => false # required
t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params
t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability
# Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present.
t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns
t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns
t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns
t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns
t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns
t.timestamps
end
end
def self.down
drop_table :users
end
end
CODE
# Update application_controller.rb
gsub_file "app/controllers/application_controller.rb", /^end/i do |match|
" helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def login_required
unless current_user
store_location
flash[:notice] = \"You must be logged in to access this page\"
redirect_to new_user_session_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
#{match}"
end
# Add Authentication Routes
gsub_file "config/routes.rb", /^ActionController::Routing::Routes.draw do \|map\|/i do |match|
"#{match}
map.resource :account, :controller => \"users\"
map.resources :users
map.resource :user_session
map.root :controller => \"user_sessions\", :action => \"new\"
"
end
\ No newline at end of file
diff --git a/base.rb b/base.rb
index a94d2d2..47c2207 100644
--- a/base.rb
+++ b/base.rb
@@ -1,57 +1,77 @@
# Sourcescape base template
template_path = '/Users/ryanwood/rails-templates'
+rspec = yes?("Do you want to use RSpec for testing?")
+
+# Testing
+if rspec
+ gem "rspec", :env => :test, :lib => false
+ gem "rspec-rails", :env => :test, :lib => false
+else
+ gem "mocha", :env => :test
+end
+
+gem "factory_girl", :env => :test, :source => "http://gemcutter.org"
+gem "shoulda", :env => :test, :source => "http://gemcutter.org"
+
+gem "formtastic", :source => "http://gemcutter.org"
+gem "haml"
+run('haml --rails .')
git :init
run "touch tmp/.gitignore log/.gitignore vendor/.gitignore"
file '.gitignore', <<CODE
-log/\\*.log
-log/\\*.pid
-db/\\*.db
-db/\\*.sqlite3
+log/*.log
+db/*.db
+db/*.sqlite3
db/schema.rb
-tmp/\\*\\*/\\*
+tmp/**/*
.DS_Store
doc/api
doc/app
config/database.yml
CODE
# Move the index
run "mv public/index.html public/index2.html"
-load_template "#{template_path}/jquery.rb"
-load_template "#{template_path}/shoulda.rb"
-load_template "#{template_path}/settings.rb"
+# Use jQuery
+if yes?("Use jQuery?")
+ load_template "#{template_path}/jquery.rb"
+end
+
+generate :nifty_layout, "--haml --sass"
+generate :nifty_config
+generate :rspec if rspec
+
+if yes?("Do you want to add Clearance Authentication?")
+ gem "clearance",
+ :source => 'http://gemcutter.org',
+ :version => '0.8.3'
+ generate :clearance
+end
+
+# if rspec
+# generate :nifty_authentication, "--haml --shoulda"
+# else
+# generate :nifty_authentication, "--haml --rspec"
+# end
# Handle Errors
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git', :submodule => true
gsub_file 'app/controllers/application_controller.rb', /class ApplicationController < ActionController::Base/ do |match|
"#{match}\n include ExceptionNotifiable"
end
initializer "exceptions.rb", "ExceptionNotifier.exception_recipients = %w([email protected])"
-# gem 'mislav-will-paginate'
-# gem 'rubyist-aasm'
-
-gem 'haml'
-run('haml --rails .')
-generate :nifty_layout, "--haml"
-
rakefile "bootstrap.rake", <<CODE
namespace :app do
task :bootstrap do
end
-
- task :seed do
- end
end
CODE
-load_template "#{template_path}/authentication.rb"
-
gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
git :submodule => "init"
-git :add => '.'
git :commit => "-a -m 'Initial commit'"
\ No newline at end of file
diff --git a/jquery.rb b/jquery.rb
index 871f78e..81bd39a 100644
--- a/jquery.rb
+++ b/jquery.rb
@@ -1,6 +1,5 @@
# Use JQuery instead of Prototype
-%w(prototype scriptaculous controls dragdrop effects slider).each do |f|
- run("rm -f public/javascripts/#{f}.js")
-end
+prototype_files = %w(prototype scriptaculous controls dragdrop effects slider).map { |f| "public/javascripts/#{f}.js" }
+run "rm -f #{prototype_files.join(' ')}"
run "curl -L http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js > public/javascripts/jquery.js"
run "curl -L http://jqueryjs.googlecode.com/svn/trunk/plugins/form/jquery.form.js > public/javascripts/jquery.form.js"
\ No newline at end of file
diff --git a/shoulda.rb b/shoulda.rb
index fd1b5bd..61f8af2 100644
--- a/shoulda.rb
+++ b/shoulda.rb
@@ -1,2 +1,3 @@
+gem "mocha"
gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => "http://gems.github.com"
gem "thoughtbot-shoulda", :lib => "shoulda", :source => "http://gems.github.com"
\ No newline at end of file
|
ryanwood/rails-templates
|
da4becdd18f2cf59d01dfc15c042a7ccdd79ec55
|
Fixed password field
|
diff --git a/authentication.rb b/authentication.rb
index c0eec95..2ac6150 100644
--- a/authentication.rb
+++ b/authentication.rb
@@ -1,245 +1,245 @@
# Sets up authentication using AuthLogic
# Depends on HAML
gem 'authlogic'
# Session
generate(:session, "user_session")
generate(:controller, "user_sessions") # Call generate mainly for the tests
# Session Controller
file "app/controllers/user_sessions_controller.rb", <<CODE
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
redirect_to account_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
redirect_to new_user_session_url
end
end
CODE
# Login Form
file "app/views/user_sessions/new.html.haml", <<CODE
- form_for @user_session, :url => user_session_path do |f|
= f.error_messages
%p
= f.label :login
%br
= f.text_field :login
%p
= f.label :password
%br
- = f.text_field :password
+ = f.password_field :password
%p
= f.submit "Login"
CODE
# User Management
generate(:controller, "users") # for tests
file "app/controllers/users_controller.rb", <<CODE
class UsersController < ApplicationController
# before_filter :require_no_user, :only => [:new, :create]
before_filter :login_required, :only => [:show, :edit, :update]
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Account registered!"
redirect_back_or_default account_url
else
render :action => :new
end
end
def show
@user = @current_user
end
def edit
@user = @current_user
end
def update
@user = @current_user # makes our views "cleaner" and more consistent
if @user.update_attributes(params[:user])
flash[:notice] = "Account updated!"
redirect_to account_url
else
render :action => :edit
end
end
end
CODE
generate(:model, "user --skip-migration --skip-fixture") # for tests
file "app/models/user.rb", <<CODE
class User < ActiveRecord::Base
acts_as_authentic
end
CODE
# User Views
file "app/views/users/_form.html.haml", <<CODE
%p
= form.label :first_name
%br
= form.text_field :first_name
%p
= form.label :last_name
%br
= form.text_field :last_name
%p
= form.label :email
%br
= form.text_field :email
%p
= form.label :login
%br
= form.text_field :login
%p
= form.label :password, form.object.new_record? ? nil : "Change password"
%br
= form.password_field :password
%p
= form.label :password_confirmation
%br
= form.password_field :password_confirmation
CODE
file "app/views/users/new.html.haml", <<CODE
%h1 Register
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Register"
CODE
file "app/views/users/edit.html.haml", <<CODE
%h1 Edit my Account
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Update"
%p= link_to "My Profile", account_path
CODE
file "app/views/users/show.html.haml", <<CODE
%p
%strong Login:
=h @user.login
%p
%strong Login Count:
=h @user.login_count
%p
%strong Last request at:
=h @user.last_request_at
%p
%strong Last login at:
=h @user.last_login_at
%p
%strong Current login at::
=h @user.current_login_at
%p
%strong Last login ip:
=h @user.last_login_ip
%p
%strong Current login ip:
=h @user.current_login_ip
%p= link_to 'Edit', edit_account_path
CODE
# Create user migration manually for User
file "db/migrate/#{Time.now.strftime('%Y%m%d%H%M%S')}_create_users.rb", <<CODE
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :login, :null => false # optional, you can use email instead, or both
t.string :email, :null => false # optional, you can use login instead, or both
t.string :crypted_password, :null => false # optional, see below
t.string :password_salt, :null => false # optional, but highly recommended
t.string :persistence_token, :null => false # required
t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params
t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability
# Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present.
t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns
t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns
t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns
t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns
t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns
t.timestamps
end
end
def self.down
drop_table :users
end
end
CODE
# Update application_controller.rb
gsub_file "app/controllers/application_controller.rb", /^end/i do |match|
" helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def login_required
unless current_user
store_location
flash[:notice] = \"You must be logged in to access this page\"
redirect_to new_user_session_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
#{match}"
end
# Add Authentication Routes
gsub_file "config/routes.rb", /^ActionController::Routing::Routes.draw do \|map\|/i do |match|
"#{match}
map.resource :account, :controller => \"users\"
map.resources :users
map.resource :user_session
map.root :controller => \"user_sessions\", :action => \"new\"
"
end
\ No newline at end of file
|
ryanwood/rails-templates
|
8d58feef93202a1bfbeecef5bc88d923c467ac9d
|
Broken out settings from base
|
diff --git a/base.rb b/base.rb
index a87339c..a94d2d2 100644
--- a/base.rb
+++ b/base.rb
@@ -1,59 +1,57 @@
# Sourcescape base template
template_path = '/Users/ryanwood/rails-templates'
git :init
run "touch tmp/.gitignore log/.gitignore vendor/.gitignore"
file '.gitignore', <<CODE
log/\\*.log
log/\\*.pid
db/\\*.db
db/\\*.sqlite3
db/schema.rb
tmp/\\*\\*/\\*
.DS_Store
doc/api
doc/app
config/database.yml
CODE
# Move the index
run "mv public/index.html public/index2.html"
load_template "#{template_path}/jquery.rb"
load_template "#{template_path}/shoulda.rb"
+load_template "#{template_path}/settings.rb"
# Handle Errors
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git', :submodule => true
gsub_file 'app/controllers/application_controller.rb', /class ApplicationController < ActionController::Base/ do |match|
"#{match}\n include ExceptionNotifiable"
end
initializer "exceptions.rb", "ExceptionNotifier.exception_recipients = %w([email protected])"
-# Application Config
-gem "settingslogic"
-
# gem 'mislav-will-paginate'
# gem 'rubyist-aasm'
gem 'haml'
run('haml --rails .')
generate :nifty_layout, "--haml"
rakefile "bootstrap.rake", <<CODE
namespace :app do
task :bootstrap do
end
task :seed do
end
end
CODE
load_template "#{template_path}/authentication.rb"
gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
git :submodule => "init"
git :add => '.'
git :commit => "-a -m 'Initial commit'"
\ No newline at end of file
diff --git a/settings.rb b/settings.rb
new file mode 100644
index 0000000..644a60e
--- /dev/null
+++ b/settings.rb
@@ -0,0 +1,20 @@
+# Application Config
+gem "settingslogic"
+
+file "app/config/application.yml", <<CODE
+defaults: &defaults
+ cool:
+ saweet: nested settings
+ neat_setting: 24
+ awesome_setting: <%= "Did you know 5 + 5 = " + (5 + 5) + "?" %>
+
+development:
+ <<: *defaults
+ neat_setting: 800
+
+test:
+ <<: *defaults
+
+production:
+ <<: *defaults
+CODE
\ No newline at end of file
|
ryanwood/rails-templates
|
04994e26e39e9e96b704a57353ec8fcb54ca3d9b
|
Lots of authentication fixes
|
diff --git a/authentication.rb b/authentication.rb
index 91a0a53..c0eec95 100644
--- a/authentication.rb
+++ b/authentication.rb
@@ -1,175 +1,245 @@
# Sets up authentication using AuthLogic
# Depends on HAML
gem 'authlogic'
# Session
generate(:session, "user_session")
-generate(:controller, "user_session") # Call generate mainly for the tests
+generate(:controller, "user_sessions") # Call generate mainly for the tests
# Session Controller
-file "app/controllers/user_session_controller.rb", <<CODE
+file "app/controllers/user_sessions_controller.rb", <<CODE
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
redirect_to account_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
redirect_to new_user_session_url
end
end
CODE
# Login Form
-file "app/views/user_session/new.html.haml", <<CODE
-- form_for @user_session do |f|
+file "app/views/user_sessions/new.html.haml", <<CODE
+- form_for @user_session, :url => user_session_path do |f|
= f.error_messages
%p
= f.label :login
%br
= f.text_field :login
%p
= f.label :password
%br
= f.text_field :password
%p
= f.submit "Login"
CODE
# User Management
-generate(:controller, "user")
-generate(:model, "user --skip-migration --skip-fixture")
+generate(:controller, "users") # for tests
+file "app/controllers/users_controller.rb", <<CODE
+class UsersController < ApplicationController
+ # before_filter :require_no_user, :only => [:new, :create]
+ before_filter :login_required, :only => [:show, :edit, :update]
+
+ def new
+ @user = User.new
+ end
+
+ def create
+ @user = User.new(params[:user])
+ if @user.save
+ flash[:notice] = "Account registered!"
+ redirect_back_or_default account_url
+ else
+ render :action => :new
+ end
+ end
+
+ def show
+ @user = @current_user
+ end
+
+ def edit
+ @user = @current_user
+ end
+
+ def update
+ @user = @current_user # makes our views "cleaner" and more consistent
+ if @user.update_attributes(params[:user])
+ flash[:notice] = "Account updated!"
+ redirect_to account_url
+ else
+ render :action => :edit
+ end
+ end
+end
+CODE
+generate(:model, "user --skip-migration --skip-fixture") # for tests
file "app/models/user.rb", <<CODE
class User < ActiveRecord::Base
acts_as_authentic
end
CODE
# User Views
-file "app/views/user/_form.html.haml", <<CODE
+file "app/views/users/_form.html.haml", <<CODE
%p
= form.label :first_name
%br
= form.text_field :first_name
%p
= form.label :last_name
%br
= form.text_field :last_name
+%p
+ = form.label :email
+ %br
+ = form.text_field :email
%p
= form.label :login
%br
= form.text_field :login
%p
= form.label :password, form.object.new_record? ? nil : "Change password"
%br
= form.password_field :password
%p
= form.label :password_confirmation
%br
= form.password_field :password_confirmation
CODE
-file "app/views/user/new.html.haml", <<CODE
+file "app/views/users/new.html.haml", <<CODE
%h1 Register
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Register"
CODE
-file "app/views/user/edit.html.haml", <<CODE
+file "app/views/users/edit.html.haml", <<CODE
%h1 Edit my Account
- form_for @user, :url => account_path do |f|
= f.error_messages
= render :partial => "form", :object => f
= f.submit "Update"
%p= link_to "My Profile", account_path
CODE
-file "app/views/user/show.html.haml", <<CODE
+file "app/views/users/show.html.haml", <<CODE
%p
%strong Login:
=h @user.login
%p
%strong Login Count:
=h @user.login_count
%p
%strong Last request at:
=h @user.last_request_at
%p
%strong Last login at:
=h @user.last_login_at
%p
%strong Current login at::
=h @user.current_login_at
%p
%strong Last login ip:
=h @user.last_login_ip
%p
%strong Current login ip:
=h @user.current_login_ip
%p= link_to 'Edit', edit_account_path
CODE
# Create user migration manually for User
-file "db/migrations/#{Time.now.strftime('%Y%m%d%H%M%S')}_create_users.rb", <<CODE
+file "db/migrate/#{Time.now.strftime('%Y%m%d%H%M%S')}_create_users.rb", <<CODE
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :login, :null => false # optional, you can use email instead, or both
t.string :email, :null => false # optional, you can use login instead, or both
t.string :crypted_password, :null => false # optional, see below
t.string :password_salt, :null => false # optional, but highly recommended
t.string :persistence_token, :null => false # required
t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params
t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability
# Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present.
t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns
t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns
t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns
t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns
t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns
t.timestamps
end
end
def self.down
drop_table :users
end
end
CODE
# Update application_controller.rb
gsub_file "app/controllers/application_controller.rb", /^end/i do |match|
" helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
+
+ def login_required
+ unless current_user
+ store_location
+ flash[:notice] = \"You must be logged in to access this page\"
+ redirect_to new_user_session_url
+ return false
+ end
+ end
+
+ def store_location
+ session[:return_to] = request.request_uri
+ end
+
+ def redirect_back_or_default(default)
+ redirect_to(session[:return_to] || default)
+ session[:return_to] = nil
+ end
#{match}"
+end
+
+# Add Authentication Routes
+gsub_file "config/routes.rb", /^ActionController::Routing::Routes.draw do \|map\|/i do |match|
+ "#{match}
+ map.resource :account, :controller => \"users\"
+ map.resources :users
+ map.resource :user_session
+ map.root :controller => \"user_sessions\", :action => \"new\"
+ "
end
\ No newline at end of file
diff --git a/base.rb b/base.rb
index 9b64a31..a87339c 100644
--- a/base.rb
+++ b/base.rb
@@ -1,59 +1,59 @@
# Sourcescape base template
template_path = '/Users/ryanwood/rails-templates'
git :init
run "touch tmp/.gitignore log/.gitignore vendor/.gitignore"
file '.gitignore', <<CODE
log/\\*.log
log/\\*.pid
db/\\*.db
db/\\*.sqlite3
db/schema.rb
tmp/\\*\\*/\\*
.DS_Store
doc/api
doc/app
config/database.yml
CODE
# Move the index
run "mv public/index.html public/index2.html"
load_template "#{template_path}/jquery.rb"
load_template "#{template_path}/shoulda.rb"
# Handle Errors
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git', :submodule => true
-gsub_file 'app/controllers/application_controller.rb', /(class ApplicationController < ActionController::Base)/ do |match|
+gsub_file 'app/controllers/application_controller.rb', /class ApplicationController < ActionController::Base/ do |match|
"#{match}\n include ExceptionNotifiable"
end
initializer "exceptions.rb", "ExceptionNotifier.exception_recipients = %w([email protected])"
# Application Config
gem "settingslogic"
# gem 'mislav-will-paginate'
# gem 'rubyist-aasm'
gem 'haml'
run('haml --rails .')
generate :nifty_layout, "--haml"
rakefile "bootstrap.rake", <<CODE
namespace :app do
task :bootstrap do
end
task :seed do
end
end
CODE
load_template "#{template_path}/authentication.rb"
gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
git :submodule => "init"
git :add => '.'
git :commit => "-a -m 'Initial commit'"
\ No newline at end of file
|
glejeune/ruby-xslt
|
af43b466aaaea73194170d24670c462dcf8320d4
|
Open file in binary mode need to correct ftell calcualtion
|
diff --git a/ext/xslt_lib/parser.c b/ext/xslt_lib/parser.c
index 6c10134..d22e450 100644
--- a/ext/xslt_lib/parser.c
+++ b/ext/xslt_lib/parser.c
@@ -1,195 +1,195 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
#include "parser.h"
extern VALUE cXSLT;
xmlDocPtr parse_xml( char* xml, int iXmlType ) {
xmlDocPtr tXMLDocument = NULL;
/** Act: Parse XML */
if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_STR ) {
tXMLDocument = xmlParseMemory( xml, strlen( xml ) );
} else if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_FILE ) {
tXMLDocument = xmlParseFile( xml );
}
if( tXMLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XML parsing error" );
return( NULL );
}
return( tXMLDocument );
}
xsltStylesheetPtr parse_xsl( char* xsl, int iXslType ) {
xsltStylesheetPtr tParsedXslt = NULL;
xmlDocPtr tXSLDocument = NULL;
/** Rem: For encoding */
xmlCharEncodingHandlerPtr encoder = NULL;
const xmlChar *encoding = NULL;
/** Act: Encoding support */
xmlInitCharEncodingHandlers( );
/** Act: Parse XSL */
if( iXslType == RUBY_XSLT_XSLSRC_TYPE_STR ) {
tXSLDocument = xmlParseMemory( xsl, strlen( xsl ) );
if( tXSLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XSL parsing error" );
return( NULL );
}
tParsedXslt = xsltParseStylesheetDoc( tXSLDocument );
} else if( iXslType == RUBY_XSLT_XSLSRC_TYPE_FILE ) {
tParsedXslt = xsltParseStylesheetFile( BAD_CAST xsl );
}
if( tParsedXslt == NULL ) {
rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
return( NULL );
}
/** Act: Get encoding */
XSLT_GET_IMPORT_PTR( encoding, tParsedXslt, encoding )
encoder = xmlFindCharEncodingHandler((char *)encoding);
if( encoding != NULL ) {
encoder = xmlFindCharEncodingHandler((char *)encoding);
if( (encoder != NULL) && (xmlStrEqual((const xmlChar *)encoder->name, (const xmlChar *) "UTF-8")) ) {
encoder = NULL;
}
}
return( tParsedXslt );
}
/**
* xOut = parser( char *xml, int iXmlType, char *xslt, int iXslType, char **pxParams );
*/
char* parse( xsltStylesheetPtr tParsedXslt, xmlDocPtr tXMLDocument, char **pxParams ) {
xmlDocPtr tXMLDocumentResult = NULL;
int iXMLDocumentResult;
xmlChar *tXMLDocumentResultString;
int tXMLDocumentResultLenght;
tXMLDocumentResult = xsltApplyStylesheet( tParsedXslt, tXMLDocument, (const char**) pxParams );
if( tXMLDocumentResult == NULL ) {
rb_raise( eXSLTTransformationError, "Stylesheet transformation error" );
return( NULL );
}
iXMLDocumentResult = xsltSaveResultToString( &tXMLDocumentResultString, &tXMLDocumentResultLenght, tXMLDocumentResult, tParsedXslt );
xmlFreeDoc(tXMLDocumentResult);
return((char*)tXMLDocumentResultString);
}
/**
* vOut = object_to_string( VALUE object );
*/
VALUE object_to_string( VALUE object ) {
VALUE vOut = Qnil;
switch( TYPE( object ) ) {
case T_STRING:
{
if( isFile( StringValuePtr( object ) ) == 0 ) {
vOut = object;
} else {
long iBufferLength;
long iCpt;
char *xBuffer;
- FILE* fStream = fopen( StringValuePtr( object ), "r" );
+ FILE* fStream = fopen( StringValuePtr( object ), "rb" );
if( fStream == NULL ) {
return( Qnil );
}
fseek( fStream, 0L, 2 );
iBufferLength = ftell( fStream );
xBuffer = (char *)malloc( (int)iBufferLength + 1 );
if( !xBuffer )
rb_raise( rb_eNoMemError, "Memory allocation error" );
xBuffer[iBufferLength] = 0;
fseek( fStream, 0L, 0 );
iCpt = fread( xBuffer, 1, (int)iBufferLength, fStream );
if( iCpt != iBufferLength ) {
free( (char *)xBuffer );
rb_raise( rb_eSystemCallError, "Read file error" );
}
vOut = rb_str_new2( xBuffer );
free( xBuffer );
fclose( fStream );
}
}
break;
case T_DATA:
case T_OBJECT:
{
if( strcmp( getRubyObjectName( object ), "XML::Smart::Dom" ) == 0 ||
strcmp( getRubyObjectName( object ), "XML::Simple::Dom" ) == 0 ) {
vOut = rb_funcall( object, rb_intern( "to_s" ), 0 );
} else if ( strcmp( getRubyObjectName( object ), "REXML::Document" ) == 0 ) {
vOut = rb_funcall( object, rb_intern( "to_s" ), 0 );
} else {
rb_raise( rb_eSystemCallError, "Can't read XML from object %s", getRubyObjectName( object ) );
}
}
break;
default:
rb_raise( rb_eArgError, "XML object #0x%x not supported", TYPE( object ) );
}
return( vOut );
}
/**
* bOut = objectIsFile( VALUE object );
*/
int objectIsFile( VALUE object ) {
int bOut = 0;
switch( TYPE( object ) ) {
case T_STRING:
{
if( isFile( StringValuePtr( object ) ) == 0 )
bOut = 0;
else
bOut = 1;
}
break;
case T_DATA:
case T_OBJECT:
default:
bOut = 0;
}
return( bOut );
}
|
glejeune/ruby-xslt
|
ce46703de1852a3a541fcb31867517d98342c027
|
Removing unneeded rb_define_const to fix libxslt 1.30 compatibility
|
diff --git a/ext/xslt_lib/xslt_lib.c b/ext/xslt_lib/xslt_lib.c
index 8d964f0..597da47 100644
--- a/ext/xslt_lib/xslt_lib.c
+++ b/ext/xslt_lib/xslt_lib.c
@@ -52,549 +52,548 @@ void ruby_xslt_mark( RbTxslt *pRbTxslt ) {
if( !NIL_P(pRbTxslt->xXmlResultCache) ) rb_gc_mark( pRbTxslt->xXmlResultCache );
if( !NIL_P(pRbTxslt->pxParams) ) rb_gc_mark( pRbTxslt->pxParams );
}
/**
* oXSLT = XML::XSLT::new()
*
* Create a new XML::XSLT object
*/
VALUE ruby_xslt_new( VALUE class ) {
RbTxslt *pRbTxslt;
pRbTxslt = (RbTxslt *)malloc(sizeof(RbTxslt));
if( pRbTxslt == NULL )
rb_raise(rb_eNoMemError, "No memory left for XSLT struct");
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlData = Qnil;
pRbTxslt->oXmlObject = Qnil;
pRbTxslt->xXmlString = Qnil;
pRbTxslt->tXMLDocument = NULL;
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_NULL;
pRbTxslt->xXslData = Qnil;
pRbTxslt->oXslObject = Qnil;
pRbTxslt->xXslString = Qnil;
pRbTxslt->tParsedXslt = NULL;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->pxParams = Qnil;
pRbTxslt->iNbParams = 0;
xmlInitMemory();
xmlSubstituteEntitiesDefault( 1 );
xmlLoadExtDtdDefaultValue = 1;
return( Data_Wrap_Struct( class, ruby_xslt_mark, ruby_xslt_free, pRbTxslt ) );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xml=<data|REXML::Document|XML::Smart|file>
*
* Set XML data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xml = <<XML
* <?xml version="1.0" encoding="UTF-8"?>
* <test>This is a test string</test>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xml = REXML::Document.new File.open( "test.xml" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xml = XML::Smart.open( "test.xml" )
*
* # Parameter as Filename
* oXSLT.xml = "test.xml"
*/
VALUE ruby_xslt_xml_obj_set( VALUE self, VALUE xml_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXmlObject = xml_doc_obj;
pRbTxslt->xXmlString = object_to_string( xml_doc_obj );
if( pRbTxslt->xXmlString == Qnil ) {
rb_raise( eXSLTError, "Can't get XML data" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_STR;
pRbTxslt->xXmlData = pRbTxslt->xXmlString;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tXMLDocument != NULL ) {
xmlFreeDoc(pRbTxslt->tXMLDocument);
}
pRbTxslt->tXMLDocument = parse_xml( StringValuePtr( pRbTxslt->xXmlData ), pRbTxslt->iXmlType );
if( pRbTxslt->tXMLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XML parsing error" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file>
*/
VALUE ruby_xslt_xml_obj_set_d( VALUE self, VALUE xml_doc_obj ) {
rb_warn( "XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file> !" );
return( ruby_xslt_xml_obj_set( self, xml_doc_obj ) );
}
/**
* string = oXSLT.xml
*
* Return XML, set by XML::XSLT#xml=, as string
*/
VALUE ruby_xslt_xml_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXmlString );
}
/**
* object = oXSLT.xmlobject
*
* Return the XML object set by XML::XSLT#xml=
*/
VALUE ruby_xslt_xml_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXmlObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xsl=<data|REXML::Document|XML::Smart|file>
*
* Set XSL data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xsl = <<XML
* <?xml version="1.0" ?>
* <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
* <xsl:template match="/">
* <xsl:apply-templates />
* </xsl:template>
* </xsl:stylesheet>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xsl = REXML::Document.new File.open( "test.xsl" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xsl = XML::Smart.open( "test.xsl" )
*
* # Parameter as Filename
* oXSLT.xsl = "test.xsl"
*/
VALUE ruby_xslt_xsl_obj_set( VALUE self, VALUE xsl_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXslObject = xsl_doc_obj;
pRbTxslt->xXslString = object_to_string( xsl_doc_obj );
if( pRbTxslt->xXslString == Qnil ) {
rb_raise( eXSLTError, "Can't get XSL data" );
}
if( objectIsFile( xsl_doc_obj ) ) {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_FILE;
pRbTxslt->xXslData = pRbTxslt->oXslObject;
} else {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_STR;
pRbTxslt->xXslData = pRbTxslt->xXslString;
}
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tParsedXslt != NULL ) {
xsltFreeStylesheet(pRbTxslt->tParsedXslt);
}
pRbTxslt->tParsedXslt = parse_xsl( StringValuePtr( pRbTxslt->xXslData ), pRbTxslt->iXslType );
if( pRbTxslt->tParsedXslt == NULL ) {
rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
}
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file>
*/
VALUE ruby_xslt_xsl_obj_set_d( VALUE self, VALUE xsl_doc_obj ) {
rb_warning( "XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file> !" );
return( ruby_xslt_xsl_obj_set( self, xsl_doc_obj ) );
}
/**
* string = oXSLT.xsl
*
* Return XSL, set by XML::XSLT#xsl=, as string
*/
VALUE ruby_xslt_xsl_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXslString );
}
/**
* object = oXSLT.xslobject
*
* Return the XSL object set by XML::XSLT#xsl=
*/
VALUE ruby_xslt_xsl_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXslObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* output_string = oXSLT.serve( )
*
* Return the stylesheet transformation
*/
VALUE ruby_xslt_serve( VALUE self ) {
RbTxslt *pRbTxslt;
char *xOut;
char **pxParams = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( pRbTxslt->iXmlResultType == RUBY_XSLT_XMLSRC_TYPE_NULL ) {
if( pRbTxslt->pxParams != Qnil ){
int iCpt;
pxParams = (char **)ALLOCA_N( void *, pRbTxslt->iNbParams );
MEMZERO( pxParams, void *, pRbTxslt->iNbParams );
for( iCpt = 0; iCpt <= pRbTxslt->iNbParams - 3; iCpt++ ) {
VALUE tmp = rb_ary_entry( pRbTxslt->pxParams, iCpt );
pxParams[iCpt] = StringValuePtr( tmp );
}
}
if( pRbTxslt->iXslType != RUBY_XSLT_XSLSRC_TYPE_NULL &&
pRbTxslt->iXmlType != RUBY_XSLT_XMLSRC_TYPE_NULL ) {
xOut = parse( pRbTxslt->tParsedXslt, pRbTxslt->tXMLDocument, pxParams );
if( xOut == NULL ) {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
} else {
pRbTxslt->xXmlResultCache = rb_str_new2( xOut );
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_STR;
free( xOut );
}
} else {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
}
return( pRbTxslt->xXmlResultCache );
}
/**
* oXSLT.save( "result.xml" )
*
* Save the stylesheet transformation to file
*/
VALUE ruby_xslt_save( VALUE self, VALUE xOutFilename ) {
char *xOut;
VALUE rOut;
FILE *fOutFile;
rOut = ruby_xslt_serve( self );
if( rOut != Qnil ) {
xOut = StringValuePtr( rOut );
fOutFile = fopen( StringValuePtr( xOutFilename ), "w" );
if( fOutFile == NULL ) {
free( xOut );
rb_raise( rb_eRuntimeError, "Can't create file %s\n", StringValuePtr( xOutFilename ) );
rOut = Qnil;
} else {
fwrite( xOut, 1, strlen( xOut ), fOutFile );
fclose( fOutFile );
}
}
return( rOut );
}
/**
* ----------------------------------------------------------------------------
*/
#ifdef USE_ERROR_HANDLER
/**
* Brendan Taylor
* [email protected]
*/
/*
* libxml2/libxslt error handling function
*
* converts the error to a String and passes it off to a block
* registered using XML::XSLT.register_error_handler
*/
void ruby_xslt_error_handler(void *ctx, const char *msg, ...) {
va_list ap;
char *str;
char *larger;
int chars;
int size = 150;
VALUE block = rb_cvar_get(cXSLT, rb_intern("@@error_handler"));
/* the following was cut&pasted from the libxslt python bindings */
str = (char *) xmlMalloc(150);
if (str == NULL)
return;
while (1) {
va_start(ap, msg);
chars = vsnprintf(str, size, msg, ap);
va_end(ap);
if ((chars > -1) && (chars < size))
break;
if (chars > -1)
size += chars + 1;
else
size += 100;
if ((larger = (char *) xmlRealloc(str, size)) == NULL) {
xmlFree(str);
return;
}
str = larger;
}
rb_funcall( block, rb_intern("call"), 1, rb_str_new2(str));
}
#endif
/**
* ----------------------------------------------------------------------------
*/
/**
* parameters support, patch from :
*
* Eustáquio "TaQ" Rangel
* [email protected]
* http://beam.to/taq
*
* Corrections : Greg
*/
/**
* oXSLT.parameters={ "key" => "value", "key" => "value", ... }
*/
VALUE ruby_xslt_parameters_set( VALUE self, VALUE parameters ) {
RbTxslt *pRbTxslt;
Check_Type( parameters, T_HASH );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( !NIL_P(parameters) ){
pRbTxslt->pxParams = rb_ary_new( );
// each_pair and process_pair defined ind parameters.c
(void)rb_iterate( each_pair, parameters, process_pair, pRbTxslt->pxParams );
pRbTxslt->iNbParams = FIX2INT( rb_funcall( parameters, rb_intern("size"), 0, 0 ) ) * 2 + 2;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
return( Qnil );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* media type information, path from :
*
* Brendan Taylor
* [email protected]
*
*/
/**
* mediaTypeString = oXSLT.mediaType( )
*
* Return the XSL output's media type
*/
VALUE ruby_xslt_media_type( VALUE self ) {
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
vXSLTSheet = pRbTxslt->tParsedXslt;
if ( (vXSLTSheet == NULL) || (vXSLTSheet->mediaType == NULL) ) {
return Qnil;
} else {
return rb_str_new2( (char *)(vXSLTSheet->mediaType) );
}
}
/**
* ----------------------------------------------------------------------------
*/
/**
* internal use only.
*/
VALUE ruby_xslt_reg_function( VALUE class, VALUE namespace, VALUE name ) {
xsltRegisterExtModuleFunction( BAD_CAST StringValuePtr(name), BAD_CAST StringValuePtr(namespace), xmlXPathFuncCallback );
return Qnil;
}
/**
* string = oXSLT.xsl_to_s( )
*/
VALUE ruby_xslt_to_s( VALUE self ) {
VALUE vStrOut;
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
const char *xKlassName = rb_class2name( CLASS_OF( self ) );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
//vXSLTSheet = xsltParseStylesheetDoc( xmlParseMemory( StringValuePtr( pRbTxslt->xXslData ), strlen( StringValuePtr( pRbTxslt->xXslData ) ) ) );
vXSLTSheet = pRbTxslt->tParsedXslt;
if (vXSLTSheet == NULL) return Qnil;
vStrOut = rb_str_new( 0, strlen(xKlassName)+1024 );
(void) sprintf( RSTRING_PTR(vStrOut),
"#<%s: parent=%p,next=%p,imports=%p,docList=%p,"
"doc=%p,stripSpaces=%p,stripAll=%d,cdataSection=%p,"
"variables=%p,templates=%p,templatesHash=%p,"
"rootMatch=%p,keyMatch=%p,elemMatch=%p,"
"attrMatch=%p,parentMatch=%p,textMatch=%p,"
"piMatch=%p,commentMatch=%p,nsAliases=%p,"
"attributeSets=%p,nsHash=%p,nsDefs=%p,keys=%p,"
"method=%s,methodURI=%s,version=%s,encoding=%s,"
"omitXmlDeclaration=%d,decimalFormat=%p,standalone=%d,"
"doctypePublic=%s,doctypeSystem=%s,indent=%d,"
"mediaType=%s,preComps=%p,warnings=%d,errors=%d,"
"exclPrefix=%s,exclPrefixTab=%p,exclPrefixNr=%d,"
"exclPrefixMax=%d>",
xKlassName,
vXSLTSheet->parent, vXSLTSheet->next, vXSLTSheet->imports, vXSLTSheet->docList,
vXSLTSheet->doc, vXSLTSheet->stripSpaces, vXSLTSheet->stripAll, vXSLTSheet->cdataSection,
vXSLTSheet->variables, vXSLTSheet->templates, vXSLTSheet->templatesHash,
vXSLTSheet->rootMatch, vXSLTSheet->keyMatch, vXSLTSheet->elemMatch,
vXSLTSheet->attrMatch, vXSLTSheet->parentMatch, vXSLTSheet->textMatch,
vXSLTSheet->piMatch, vXSLTSheet->commentMatch, vXSLTSheet->nsAliases,
vXSLTSheet->attributeSets, vXSLTSheet->nsHash, vXSLTSheet->nsDefs, vXSLTSheet->keys,
vXSLTSheet->method, vXSLTSheet->methodURI, vXSLTSheet->version, vXSLTSheet->encoding,
vXSLTSheet->omitXmlDeclaration, vXSLTSheet->decimalFormat, vXSLTSheet->standalone,
vXSLTSheet->doctypePublic, vXSLTSheet->doctypeSystem, vXSLTSheet->indent,
vXSLTSheet->mediaType, vXSLTSheet->preComps, vXSLTSheet->warnings, vXSLTSheet->errors,
vXSLTSheet->exclPrefix, vXSLTSheet->exclPrefixTab, vXSLTSheet->exclPrefixNr,
vXSLTSheet->exclPrefixMax );
vStrOut = strlen(RSTRING_PTR(vStrOut));
if( OBJ_TAINTED(self) ) OBJ_TAINT(vStrOut);
// xsltFreeStylesheet(vXSLTSheet);
return( vStrOut );
}
/**
* ----------------------------------------------------------------------------
*/
void Init_xslt_lib( void ) {
mXML = rb_define_module( "XML" );
cXSLT = rb_define_class_under( mXML, "XSLT", rb_cObject );
eXSLTError = rb_define_class_under( cXSLT, "XSLTError", rb_eRuntimeError );
eXSLTParsingError = rb_define_class_under( cXSLT, "ParsingError", eXSLTError );
eXSLTTransformationError = rb_define_class_under( cXSLT, "TransformationError", eXSLTError );
rb_define_const( cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth) );
rb_define_const( cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT) );
rb_define_const( cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion) );
rb_define_const( cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion) );
rb_define_const( cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion) );
rb_define_const( cXSLT, "XSLT_NAMESPACE", rb_str_new2((char *)XSLT_NAMESPACE) );
rb_define_const( cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR) );
rb_define_const( cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION) );
rb_define_const( cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL) );
rb_define_const( cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((char *)XSLT_LIBXSLT_NAMESPACE) );
- rb_define_const( cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((char *)XSLT_NORM_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_SAXON", rb_str_new2((char *)XSLT_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XT", rb_str_new2((char *)XSLT_XT_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XALAN", rb_str_new2((char *)XSLT_XALAN_NAMESPACE) );
rb_define_const( cXSLT, "RUBY_XSLT_VERSION", rb_str_new2(RUBY_XSLT_VERSION) );
rb_define_singleton_method( cXSLT, "new", ruby_xslt_new, 0 );
rb_define_singleton_method( cXSLT, "registerFunction", ruby_xslt_reg_function, 2);
rb_define_method( cXSLT, "serve", ruby_xslt_serve, 0 );
rb_define_method( cXSLT, "save", ruby_xslt_save, 1 );
rb_define_method( cXSLT, "xml=", ruby_xslt_xml_obj_set, 1 );
rb_define_method( cXSLT, "xmlfile=", ruby_xslt_xml_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xml", ruby_xslt_xml_2str_get, 0 );
rb_define_method( cXSLT, "xmlobject", ruby_xslt_xml_2obj_get, 0 );
rb_define_method( cXSLT, "xsl=", ruby_xslt_xsl_obj_set, 1 );
rb_define_method( cXSLT, "xslfile=", ruby_xslt_xsl_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xsl", ruby_xslt_xsl_2str_get, 0 );
rb_define_method( cXSLT, "xslobject", ruby_xslt_xsl_2obj_get, 0 );
rb_define_method( cXSLT, "parameters=", ruby_xslt_parameters_set, 1 );
rb_define_method( cXSLT, "xsl_to_s", ruby_xslt_to_s, 0 );
rb_define_method( cXSLT, "mediaType", ruby_xslt_media_type, 0 );
#ifdef USE_ERROR_HANDLER
xmlSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
xsltSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
#endif
#ifdef USE_EXSLT
exsltRegisterAll();
#endif
}
|
glejeune/ruby-xslt
|
86f00be2704b9c489a1adc53c58afae18ccd0e87
|
Version bump to 0.9.10
|
diff --git a/VERSION b/VERSION
index 6f060dc..ea8f4fd 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.9.9
\ No newline at end of file
+0.9.10
\ No newline at end of file
|
glejeune/ruby-xslt
|
b920a15e86f2a6bbde8b64c8d0f0627d736356fe
|
Ignore .rake_tasks
|
diff --git a/.gitignore b/.gitignore
index c2a64a5..6c69b66 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,25 +1,26 @@
## MAC OS
.DS_Store
## TEXTMATE
*.tmproj
tmtags
## EMACS
*~
\#*
.\#*
## VIM
*.swp
## PROJECT::GENERAL
coverage
rdoc
pkg
+.rake_tasks
## PROJECT::SPECIFIC
ext/xslt_lib/Makefile
ext/xslt_lib/extconf.h
ext/xslt_lib/mkmf.log
examples
|
glejeune/ruby-xslt
|
6267d16da49bc01b13b76fa240d477ef24c5b4d2
|
Suppress warnings
|
diff --git a/ChangeLog b/ChangeLog
index d443a4d..0d86d6e 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,90 +1,91 @@
0.9.9 :
+* Major bug correction
0.9.8 :
* Replace STR2CSTR by StringValuePtr
0.9.7 :
* Ruby 1.9
* Bug correction (Issue #1)
0.9.6 :
* "found and patched some serious memory leaks" (thanks to Tom)
0.9.5 :
* Bugfix in extconf.c (thanks to Stephane Mariel)
0.9.4 :
* ...
0.9.3 :
* Due to recent changes in Gentoo Linux's install system, ruby-xslt no longer installs correctly. Brendan fixed this.
* Cleaned up extconf.rb
* Removed unused debugging code (memwatch)
* Moved some things out of C into Ruby
* Made error handling much more useful
* Added some unit tests
0.9.2 :
* Changes to the way XSLT files are loaded, so that we can keep their base URI straight - Sorry Brendan !!!
* Major corrections
0.9.1 :
* Add XML/Smart support. XML/Simple support is still available
* Add REXML support.
* Add error classes and sets libxml error function
* Move samples scripts from tests to examples and add unit tests
* Changes to the way XSLT files are loaded, so that we can keep their base URI straight
* Major bugs corrections
0.8.2 :
* Configuration changes:
ruby extconf.rb --enable-exslt (on by default) : enables libexslt support <http://exslt.org/>
ruby extconf.rb --enable-error-handler (off by default) : enables a VERY crude error handler. error messages are appended to the class variable XML::XSLT and can be accessed with the class method XML::XSLT.errors (not very good, but better than trapping $stderr)
* API changes:
XML::XSLT.new.extFunction("do-this", "http://fake.none", MyClass, "do_this")
is now
XML::XSLT.extFunction("do-this", "http://fake.none", MyClass)
The callback function will now call the function with the same name as the function that was called. One (possibly confusing) exception is that when you register a function with a '-' in it the name of the ruby method called has the '-'s replaced with '_'s. This is because there seems to be a convention of naming XPath functions with hyphens and they're illegal in Ruby method names.
The big stability change is that the external function table is now stored in a hash of hashes on the XSLT class object. (rather than a global xmlHash) It makes more sense to make it a property of the class and the hashes are an easy way to implement it.
The type of objects that are passed to and returned from extension functions has changed to be more sane. REXML is now required to convert an xmlXPathObj to and from a VALUE; nodesets are passed to Ruby as an array of REXML::Elements and REXML::Elements / REXML::Documents returned from Ruby get turned into nodesets.
* Potential problems:
xsltCleanupGlobals() shouldn't be called until we're done with whatever functions that are registered (probably when our program doesn't need ruby-xslt at all any more).
0.8.1 :
* Major bug correction
0.8.0 :
* Major bug correction in parameters support
0.7.0 :
* Add external functions support
0.6.0 :
* Major bug correction
0.5.0 :
* Add XML/Simple support
* Add parameters support
0.4.0 :
* Add cache
0.3.0 :
* Major bug correction
0.2.0 :
* Major bug correction
0.1.0 :
* Initial version
diff --git a/ext/xslt_lib/extfunc.c b/ext/xslt_lib/extfunc.c
index 9e7cadd..e300e98 100644
--- a/ext/xslt_lib/extfunc.c
+++ b/ext/xslt_lib/extfunc.c
@@ -1,213 +1,218 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
extern VALUE mXML;
extern VALUE cXSLT;
/**
* external function support, patch from :
*
* Brendan Taylor
* [email protected]
*
*/
/* converts an xmlXPathObjectPtr to a Ruby VALUE
* number -> float
* boolean -> boolean
* string -> string
* nodeset -> an array of REXML::Elements
*/
VALUE xpathObj2value(xmlXPathObjectPtr obj, xmlDocPtr doc)
{
VALUE ret = Qnil;
if (obj == NULL) {
return ret;
}
switch (obj->type) {
case XPATH_NODESET:
rb_require("rexml/document");
ret = rb_ary_new();
if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) {
xmlBufferPtr buff = xmlBufferCreate();
xmlNodePtr node;
int i;
// this assumes all the nodes are elements, which is a bad idea
for (i = 0; i < obj->nodesetval->nodeNr; i++) {
node = obj->nodesetval->nodeTab[i];
if( node->type == XML_ELEMENT_NODE ) {
+ VALUE cREXML;
+ VALUE cDocument;
+ VALUE rDocument;
+ VALUE rElement;
+
xmlNodeDump(buff, doc, node, 0, 0);
- VALUE cREXML = rb_const_get(rb_cObject, rb_intern("REXML"));
- VALUE cDocument = rb_const_get(cREXML, rb_intern("Document"));
- VALUE rDocument = rb_funcall(cDocument, rb_intern("new"), 1,rb_str_new2((char *)buff->content));
- VALUE rElement = rb_funcall(rDocument, rb_intern("root"), 0);
+ cREXML = rb_const_get(rb_cObject, rb_intern("REXML"));
+ cDocument = rb_const_get(cREXML, rb_intern("Document"));
+ rDocument = rb_funcall(cDocument, rb_intern("new"), 1,rb_str_new2((char *)buff->content));
+ rElement = rb_funcall(rDocument, rb_intern("root"), 0);
rb_ary_push(ret, rElement);
// empty the buffer (xmlNodeDump appends rather than replaces)
xmlBufferEmpty(buff);
} else if ( node->type == XML_TEXT_NODE ) {
rb_ary_push(ret, rb_str_new2((char *)node->content));
} else if ( node->type == XML_ATTRIBUTE_NODE ) {
// BUG: should ensure children is not null (shouldn't)
rb_ary_push(ret, rb_str_new2((char *)node->children->content));
} else {
rb_warning( "Unsupported node type in node set: %d", node->type );
}
}
xmlBufferFree(buff);
}
break;
case XPATH_BOOLEAN:
ret = obj->boolval ? Qtrue : Qfalse;
break;
case XPATH_NUMBER:
ret = rb_float_new(obj->floatval);
break;
case XPATH_STRING:
ret = rb_str_new2((char *) obj->stringval);
break;
/* these cases were in libxslt's python bindings, but i don't know what they are, so i'll leave them alone */
case XPATH_XSLT_TREE:
case XPATH_POINT:
case XPATH_RANGE:
case XPATH_LOCATIONSET:
default:
rb_warning("xpathObj2value: can't convert XPath object type %d to Ruby object\n", obj->type );
}
xmlXPathFreeObject(obj);
return ret;
}
/*
* converts a Ruby VALUE to an xmlXPathObjectPtr
* boolean -> boolean
* number -> number
* string -> escaped string
* array -> array of parsed nodes
*/
xmlXPathObjectPtr value2xpathObj (VALUE val) {
xmlXPathObjectPtr ret = NULL;
switch (TYPE(val)) {
case T_TRUE:
case T_FALSE:
ret = xmlXPathNewBoolean(RTEST(val));
break;
case T_FIXNUM:
case T_FLOAT:
ret = xmlXPathNewFloat(NUM2DBL(val));
break;
case T_STRING:
{
xmlChar *str;
// we need the Strdup (this is the major bugfix for 0.8.1)
str = xmlStrdup((const xmlChar *) StringValuePtr(val));
ret = xmlXPathWrapString(str);
}
break;
case T_NIL:
ret = xmlXPathNewNodeSet(NULL);
break;
case T_ARRAY: {
- int i,j;
+ long i,j;
ret = xmlXPathNewNodeSet(NULL);
for(i = RARRAY_LEN(val); i > 0; i--) {
xmlXPathObjectPtr obj = value2xpathObj( rb_ary_shift( val ) );
if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) {
for(j = 0; j < obj->nodesetval->nodeNr; j++) {
xmlXPathNodeSetAdd( ret->nodesetval, obj->nodesetval->nodeTab[j] );
}
}
}
break; }
case T_DATA:
case T_OBJECT: {
if( strcmp( getRubyObjectName( val ), "REXML::Document" ) == 0 || strcmp(getRubyObjectName( val ), "REXML::Element") == 0 ) {
VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 );
xmlDocPtr doc = xmlParseDoc((xmlChar *) StringValuePtr(to_s));
ret = xmlXPathNewNodeSet((xmlNode *)doc->children);
break;
} else if( strcmp( getRubyObjectName( val ), "REXML::Text" ) == 0 ) {
VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 );
xmlChar *str;
str = xmlStrdup((const xmlChar *) StringValuePtr(to_s));
ret = xmlXPathWrapString(str);
break;
}
// this drops through so i can reuse the error message
}
default:
rb_warning( "value2xpathObj: can't convert class %s to XPath object\n", getRubyObjectName(val));
return NULL;
}
return ret;
}
/*
* chooses what registered function to call and calls it
*/
void xmlXPathFuncCallback( xmlXPathParserContextPtr ctxt, int nargs) {
VALUE result, arguments[nargs];
VALUE ns_hash, func_hash, block;
const xmlChar *namespace, *name;
xmlXPathObjectPtr obj;
int i;
if (ctxt == NULL || ctxt->context == NULL)
return;
name = ctxt->context->function;
namespace = ctxt->context->functionURI;
ns_hash = rb_cvar_get(cXSLT, rb_intern("@@extFunctions"));
func_hash = rb_hash_aref(ns_hash, rb_str_new2((char *)namespace));
if(func_hash == Qnil) {
rb_warning( "xmlXPathFuncCallback: namespace %s not registered!\n", namespace );
}
block = rb_hash_aref(func_hash, rb_str_new2((char *)name));
for (i = nargs - 1; i >= 0; i--) {
obj = valuePop(ctxt);
arguments[i] = xpathObj2value(obj, ctxt->context->doc);
}
result = rb_funcall2( block, rb_intern("call"), nargs, arguments);
obj = value2xpathObj(result);
valuePush(ctxt, obj);
}
diff --git a/ext/xslt_lib/xslt_lib.c b/ext/xslt_lib/xslt_lib.c
index f7953ee..8d964f0 100644
--- a/ext/xslt_lib/xslt_lib.c
+++ b/ext/xslt_lib/xslt_lib.c
@@ -1,600 +1,600 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
VALUE mXML;
VALUE cXSLT;
VALUE eXSLTError;
VALUE eXSLTParsingError;
VALUE eXSLTTransformationError;
void ruby_xslt_free( RbTxslt *pRbTxslt ) {
if( pRbTxslt != NULL ) {
if( pRbTxslt->tParsedXslt != NULL )
xsltFreeStylesheet(pRbTxslt->tParsedXslt);
if( pRbTxslt->tXMLDocument != NULL )
xmlFreeDoc(pRbTxslt->tXMLDocument);
free( pRbTxslt );
}
xsltCleanupGlobals();
xmlCleanupParser();
xmlMemoryDump();
}
void ruby_xslt_mark( RbTxslt *pRbTxslt ) {
if( pRbTxslt == NULL ) return;
if( !NIL_P(pRbTxslt->xXmlData) ) rb_gc_mark( pRbTxslt->xXmlData );
if( !NIL_P(pRbTxslt->oXmlObject) ) rb_gc_mark( pRbTxslt->oXmlObject );
if( !NIL_P(pRbTxslt->xXmlString) ) rb_gc_mark( pRbTxslt->xXmlString );
if( !NIL_P(pRbTxslt->xXslData) ) rb_gc_mark( pRbTxslt->xXslData );
if( !NIL_P(pRbTxslt->oXslObject) ) rb_gc_mark( pRbTxslt->oXslObject );
if( !NIL_P(pRbTxslt->xXslString) ) rb_gc_mark( pRbTxslt->xXslString );
if( !NIL_P(pRbTxslt->xXmlResultCache) ) rb_gc_mark( pRbTxslt->xXmlResultCache );
if( !NIL_P(pRbTxslt->pxParams) ) rb_gc_mark( pRbTxslt->pxParams );
}
/**
* oXSLT = XML::XSLT::new()
*
* Create a new XML::XSLT object
*/
VALUE ruby_xslt_new( VALUE class ) {
RbTxslt *pRbTxslt;
pRbTxslt = (RbTxslt *)malloc(sizeof(RbTxslt));
if( pRbTxslt == NULL )
rb_raise(rb_eNoMemError, "No memory left for XSLT struct");
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlData = Qnil;
pRbTxslt->oXmlObject = Qnil;
pRbTxslt->xXmlString = Qnil;
pRbTxslt->tXMLDocument = NULL;
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_NULL;
pRbTxslt->xXslData = Qnil;
pRbTxslt->oXslObject = Qnil;
pRbTxslt->xXslString = Qnil;
pRbTxslt->tParsedXslt = NULL;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->pxParams = Qnil;
pRbTxslt->iNbParams = 0;
xmlInitMemory();
xmlSubstituteEntitiesDefault( 1 );
xmlLoadExtDtdDefaultValue = 1;
return( Data_Wrap_Struct( class, ruby_xslt_mark, ruby_xslt_free, pRbTxslt ) );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xml=<data|REXML::Document|XML::Smart|file>
*
* Set XML data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xml = <<XML
* <?xml version="1.0" encoding="UTF-8"?>
* <test>This is a test string</test>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xml = REXML::Document.new File.open( "test.xml" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xml = XML::Smart.open( "test.xml" )
*
* # Parameter as Filename
* oXSLT.xml = "test.xml"
*/
VALUE ruby_xslt_xml_obj_set( VALUE self, VALUE xml_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXmlObject = xml_doc_obj;
pRbTxslt->xXmlString = object_to_string( xml_doc_obj );
if( pRbTxslt->xXmlString == Qnil ) {
rb_raise( eXSLTError, "Can't get XML data" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_STR;
pRbTxslt->xXmlData = pRbTxslt->xXmlString;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tXMLDocument != NULL ) {
xmlFreeDoc(pRbTxslt->tXMLDocument);
}
pRbTxslt->tXMLDocument = parse_xml( StringValuePtr( pRbTxslt->xXmlData ), pRbTxslt->iXmlType );
if( pRbTxslt->tXMLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XML parsing error" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file>
*/
VALUE ruby_xslt_xml_obj_set_d( VALUE self, VALUE xml_doc_obj ) {
rb_warn( "XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file> !" );
return( ruby_xslt_xml_obj_set( self, xml_doc_obj ) );
}
/**
* string = oXSLT.xml
*
* Return XML, set by XML::XSLT#xml=, as string
*/
VALUE ruby_xslt_xml_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXmlString );
}
/**
* object = oXSLT.xmlobject
*
* Return the XML object set by XML::XSLT#xml=
*/
VALUE ruby_xslt_xml_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXmlObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xsl=<data|REXML::Document|XML::Smart|file>
*
* Set XSL data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xsl = <<XML
* <?xml version="1.0" ?>
* <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
* <xsl:template match="/">
* <xsl:apply-templates />
* </xsl:template>
* </xsl:stylesheet>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xsl = REXML::Document.new File.open( "test.xsl" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xsl = XML::Smart.open( "test.xsl" )
*
* # Parameter as Filename
* oXSLT.xsl = "test.xsl"
*/
VALUE ruby_xslt_xsl_obj_set( VALUE self, VALUE xsl_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXslObject = xsl_doc_obj;
pRbTxslt->xXslString = object_to_string( xsl_doc_obj );
if( pRbTxslt->xXslString == Qnil ) {
rb_raise( eXSLTError, "Can't get XSL data" );
}
if( objectIsFile( xsl_doc_obj ) ) {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_FILE;
pRbTxslt->xXslData = pRbTxslt->oXslObject;
} else {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_STR;
pRbTxslt->xXslData = pRbTxslt->xXslString;
}
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tParsedXslt != NULL ) {
xsltFreeStylesheet(pRbTxslt->tParsedXslt);
}
pRbTxslt->tParsedXslt = parse_xsl( StringValuePtr( pRbTxslt->xXslData ), pRbTxslt->iXslType );
if( pRbTxslt->tParsedXslt == NULL ) {
rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
}
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file>
*/
VALUE ruby_xslt_xsl_obj_set_d( VALUE self, VALUE xsl_doc_obj ) {
rb_warning( "XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file> !" );
return( ruby_xslt_xsl_obj_set( self, xsl_doc_obj ) );
}
/**
* string = oXSLT.xsl
*
* Return XSL, set by XML::XSLT#xsl=, as string
*/
VALUE ruby_xslt_xsl_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXslString );
}
/**
* object = oXSLT.xslobject
*
* Return the XSL object set by XML::XSLT#xsl=
*/
VALUE ruby_xslt_xsl_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXslObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* output_string = oXSLT.serve( )
*
* Return the stylesheet transformation
*/
VALUE ruby_xslt_serve( VALUE self ) {
RbTxslt *pRbTxslt;
char *xOut;
char **pxParams = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( pRbTxslt->iXmlResultType == RUBY_XSLT_XMLSRC_TYPE_NULL ) {
if( pRbTxslt->pxParams != Qnil ){
int iCpt;
pxParams = (char **)ALLOCA_N( void *, pRbTxslt->iNbParams );
MEMZERO( pxParams, void *, pRbTxslt->iNbParams );
for( iCpt = 0; iCpt <= pRbTxslt->iNbParams - 3; iCpt++ ) {
VALUE tmp = rb_ary_entry( pRbTxslt->pxParams, iCpt );
pxParams[iCpt] = StringValuePtr( tmp );
}
}
if( pRbTxslt->iXslType != RUBY_XSLT_XSLSRC_TYPE_NULL &&
pRbTxslt->iXmlType != RUBY_XSLT_XMLSRC_TYPE_NULL ) {
xOut = parse( pRbTxslt->tParsedXslt, pRbTxslt->tXMLDocument, pxParams );
if( xOut == NULL ) {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
} else {
pRbTxslt->xXmlResultCache = rb_str_new2( xOut );
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_STR;
free( xOut );
}
} else {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
}
return( pRbTxslt->xXmlResultCache );
}
/**
* oXSLT.save( "result.xml" )
*
* Save the stylesheet transformation to file
*/
VALUE ruby_xslt_save( VALUE self, VALUE xOutFilename ) {
char *xOut;
VALUE rOut;
FILE *fOutFile;
rOut = ruby_xslt_serve( self );
if( rOut != Qnil ) {
xOut = StringValuePtr( rOut );
fOutFile = fopen( StringValuePtr( xOutFilename ), "w" );
if( fOutFile == NULL ) {
free( xOut );
rb_raise( rb_eRuntimeError, "Can't create file %s\n", StringValuePtr( xOutFilename ) );
rOut = Qnil;
} else {
fwrite( xOut, 1, strlen( xOut ), fOutFile );
fclose( fOutFile );
}
}
return( rOut );
}
/**
* ----------------------------------------------------------------------------
*/
#ifdef USE_ERROR_HANDLER
/**
* Brendan Taylor
* [email protected]
*/
/*
* libxml2/libxslt error handling function
*
* converts the error to a String and passes it off to a block
* registered using XML::XSLT.register_error_handler
*/
void ruby_xslt_error_handler(void *ctx, const char *msg, ...) {
va_list ap;
char *str;
char *larger;
int chars;
int size = 150;
VALUE block = rb_cvar_get(cXSLT, rb_intern("@@error_handler"));
/* the following was cut&pasted from the libxslt python bindings */
str = (char *) xmlMalloc(150);
if (str == NULL)
return;
while (1) {
va_start(ap, msg);
chars = vsnprintf(str, size, msg, ap);
va_end(ap);
if ((chars > -1) && (chars < size))
break;
if (chars > -1)
size += chars + 1;
else
size += 100;
if ((larger = (char *) xmlRealloc(str, size)) == NULL) {
xmlFree(str);
return;
}
str = larger;
}
rb_funcall( block, rb_intern("call"), 1, rb_str_new2(str));
}
#endif
/**
* ----------------------------------------------------------------------------
*/
/**
* parameters support, patch from :
*
* Eustáquio "TaQ" Rangel
* [email protected]
* http://beam.to/taq
*
* Corrections : Greg
*/
/**
* oXSLT.parameters={ "key" => "value", "key" => "value", ... }
*/
VALUE ruby_xslt_parameters_set( VALUE self, VALUE parameters ) {
RbTxslt *pRbTxslt;
Check_Type( parameters, T_HASH );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( !NIL_P(parameters) ){
pRbTxslt->pxParams = rb_ary_new( );
// each_pair and process_pair defined ind parameters.c
(void)rb_iterate( each_pair, parameters, process_pair, pRbTxslt->pxParams );
pRbTxslt->iNbParams = FIX2INT( rb_funcall( parameters, rb_intern("size"), 0, 0 ) ) * 2 + 2;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
return( Qnil );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* media type information, path from :
*
* Brendan Taylor
* [email protected]
*
*/
/**
* mediaTypeString = oXSLT.mediaType( )
*
* Return the XSL output's media type
*/
VALUE ruby_xslt_media_type( VALUE self ) {
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
vXSLTSheet = pRbTxslt->tParsedXslt;
if ( (vXSLTSheet == NULL) || (vXSLTSheet->mediaType == NULL) ) {
return Qnil;
} else {
return rb_str_new2( (char *)(vXSLTSheet->mediaType) );
}
}
/**
* ----------------------------------------------------------------------------
*/
/**
* internal use only.
*/
VALUE ruby_xslt_reg_function( VALUE class, VALUE namespace, VALUE name ) {
xsltRegisterExtModuleFunction( BAD_CAST StringValuePtr(name), BAD_CAST StringValuePtr(namespace), xmlXPathFuncCallback );
return Qnil;
}
/**
* string = oXSLT.xsl_to_s( )
*/
VALUE ruby_xslt_to_s( VALUE self ) {
VALUE vStrOut;
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
- char *xKlassName = rb_class2name( CLASS_OF( self ) );
+ const char *xKlassName = rb_class2name( CLASS_OF( self ) );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
//vXSLTSheet = xsltParseStylesheetDoc( xmlParseMemory( StringValuePtr( pRbTxslt->xXslData ), strlen( StringValuePtr( pRbTxslt->xXslData ) ) ) );
vXSLTSheet = pRbTxslt->tParsedXslt;
if (vXSLTSheet == NULL) return Qnil;
vStrOut = rb_str_new( 0, strlen(xKlassName)+1024 );
(void) sprintf( RSTRING_PTR(vStrOut),
"#<%s: parent=%p,next=%p,imports=%p,docList=%p,"
"doc=%p,stripSpaces=%p,stripAll=%d,cdataSection=%p,"
"variables=%p,templates=%p,templatesHash=%p,"
"rootMatch=%p,keyMatch=%p,elemMatch=%p,"
"attrMatch=%p,parentMatch=%p,textMatch=%p,"
"piMatch=%p,commentMatch=%p,nsAliases=%p,"
"attributeSets=%p,nsHash=%p,nsDefs=%p,keys=%p,"
"method=%s,methodURI=%s,version=%s,encoding=%s,"
"omitXmlDeclaration=%d,decimalFormat=%p,standalone=%d,"
"doctypePublic=%s,doctypeSystem=%s,indent=%d,"
"mediaType=%s,preComps=%p,warnings=%d,errors=%d,"
"exclPrefix=%s,exclPrefixTab=%p,exclPrefixNr=%d,"
"exclPrefixMax=%d>",
xKlassName,
vXSLTSheet->parent, vXSLTSheet->next, vXSLTSheet->imports, vXSLTSheet->docList,
vXSLTSheet->doc, vXSLTSheet->stripSpaces, vXSLTSheet->stripAll, vXSLTSheet->cdataSection,
vXSLTSheet->variables, vXSLTSheet->templates, vXSLTSheet->templatesHash,
vXSLTSheet->rootMatch, vXSLTSheet->keyMatch, vXSLTSheet->elemMatch,
vXSLTSheet->attrMatch, vXSLTSheet->parentMatch, vXSLTSheet->textMatch,
vXSLTSheet->piMatch, vXSLTSheet->commentMatch, vXSLTSheet->nsAliases,
vXSLTSheet->attributeSets, vXSLTSheet->nsHash, vXSLTSheet->nsDefs, vXSLTSheet->keys,
vXSLTSheet->method, vXSLTSheet->methodURI, vXSLTSheet->version, vXSLTSheet->encoding,
vXSLTSheet->omitXmlDeclaration, vXSLTSheet->decimalFormat, vXSLTSheet->standalone,
vXSLTSheet->doctypePublic, vXSLTSheet->doctypeSystem, vXSLTSheet->indent,
vXSLTSheet->mediaType, vXSLTSheet->preComps, vXSLTSheet->warnings, vXSLTSheet->errors,
vXSLTSheet->exclPrefix, vXSLTSheet->exclPrefixTab, vXSLTSheet->exclPrefixNr,
vXSLTSheet->exclPrefixMax );
vStrOut = strlen(RSTRING_PTR(vStrOut));
if( OBJ_TAINTED(self) ) OBJ_TAINT(vStrOut);
// xsltFreeStylesheet(vXSLTSheet);
return( vStrOut );
}
/**
* ----------------------------------------------------------------------------
*/
void Init_xslt_lib( void ) {
mXML = rb_define_module( "XML" );
cXSLT = rb_define_class_under( mXML, "XSLT", rb_cObject );
eXSLTError = rb_define_class_under( cXSLT, "XSLTError", rb_eRuntimeError );
eXSLTParsingError = rb_define_class_under( cXSLT, "ParsingError", eXSLTError );
eXSLTTransformationError = rb_define_class_under( cXSLT, "TransformationError", eXSLTError );
rb_define_const( cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth) );
rb_define_const( cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT) );
rb_define_const( cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion) );
rb_define_const( cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion) );
rb_define_const( cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion) );
rb_define_const( cXSLT, "XSLT_NAMESPACE", rb_str_new2((char *)XSLT_NAMESPACE) );
rb_define_const( cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR) );
rb_define_const( cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION) );
rb_define_const( cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL) );
rb_define_const( cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((char *)XSLT_LIBXSLT_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((char *)XSLT_NORM_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_SAXON", rb_str_new2((char *)XSLT_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XT", rb_str_new2((char *)XSLT_XT_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XALAN", rb_str_new2((char *)XSLT_XALAN_NAMESPACE) );
rb_define_const( cXSLT, "RUBY_XSLT_VERSION", rb_str_new2(RUBY_XSLT_VERSION) );
rb_define_singleton_method( cXSLT, "new", ruby_xslt_new, 0 );
rb_define_singleton_method( cXSLT, "registerFunction", ruby_xslt_reg_function, 2);
rb_define_method( cXSLT, "serve", ruby_xslt_serve, 0 );
rb_define_method( cXSLT, "save", ruby_xslt_save, 1 );
rb_define_method( cXSLT, "xml=", ruby_xslt_xml_obj_set, 1 );
rb_define_method( cXSLT, "xmlfile=", ruby_xslt_xml_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xml", ruby_xslt_xml_2str_get, 0 );
rb_define_method( cXSLT, "xmlobject", ruby_xslt_xml_2obj_get, 0 );
rb_define_method( cXSLT, "xsl=", ruby_xslt_xsl_obj_set, 1 );
rb_define_method( cXSLT, "xslfile=", ruby_xslt_xsl_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xsl", ruby_xslt_xsl_2str_get, 0 );
rb_define_method( cXSLT, "xslobject", ruby_xslt_xsl_2obj_get, 0 );
rb_define_method( cXSLT, "parameters=", ruby_xslt_parameters_set, 1 );
rb_define_method( cXSLT, "xsl_to_s", ruby_xslt_to_s, 0 );
rb_define_method( cXSLT, "mediaType", ruby_xslt_media_type, 0 );
#ifdef USE_ERROR_HANDLER
xmlSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
xsltSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
#endif
#ifdef USE_EXSLT
exsltRegisterAll();
#endif
}
|
glejeune/ruby-xslt
|
e5211a4ce8e24276883821ec8011a3ad37af4b2f
|
Major bug correction with Ruby 1.9.3
|
diff --git a/.gitignore b/.gitignore
index 35645cd..c2a64a5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,24 +1,25 @@
## MAC OS
.DS_Store
## TEXTMATE
*.tmproj
tmtags
## EMACS
*~
\#*
.\#*
## VIM
*.swp
## PROJECT::GENERAL
coverage
rdoc
pkg
## PROJECT::SPECIFIC
ext/xslt_lib/Makefile
+ext/xslt_lib/extconf.h
ext/xslt_lib/mkmf.log
-examples
\ No newline at end of file
+examples
diff --git a/Rakefile b/Rakefile
index df882fd..5446dab 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,53 +1,54 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "ruby-xslt"
- gem.summary = %Q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/> }
- gem.description = gem.summary
+ gem.summary = %Q{Ruby/XSLT is a simple XSLT class}
+ gem.description = %Q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>}
gem.email = "[email protected]"
gem.homepage = "http://github.com/glejeune/ruby-xslt"
gem.authors = ["Gregoire Lejeune"]
gem.extensions = FileList["ext/**/extconf.rb"].to_a
gem.test_files = Dir.glob('test/**/*.rb')
+ gem.add_development_dependency 'rdoc'
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
begin
require 'rcov/rcovtask'
Rcov::RcovTask.new do |test|
test.libs << 'test'
test.pattern = 'test/**/test_*.rb'
test.verbose = true
end
rescue LoadError
task :rcov do
abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
end
end
task :test => :check_dependencies
task :default => :test
-require 'rake/rdoctask'
-Rake::RDocTask.new do |rdoc|
+require 'rdoc/task'
+RDoc::Task.new do |rdoc|
version = File.exist?('VERSION') ? File.read('VERSION') : ""
rdoc.rdoc_dir = 'rdoc'
- rdoc.title = "syncftp #{version}"
+ rdoc.title = "Ruby/XSLT #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h
index e726c45..4f797e7 100644
--- a/ext/xslt_lib/xslt.h
+++ b/ext/xslt_lib/xslt.h
@@ -1,102 +1,102 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Please see the LICENSE file for copyright and distribution information */
-#ifndef __RUBY_XSLT_H__
-#define __RUBY_XSLT_H__
-
-#include <ruby.h>
-#ifdef RUBY_1_8
- #include <rubyio.h>
-#else
- #include <ruby/io.h>
-#endif
-
-#include <string.h>
-
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/extra.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libxslt/imports.h>
#ifdef USE_EXSLT
#include <libexslt/exslt.h>
#endif
+#ifndef __RUBY_XSLT_H__
+#define __RUBY_XSLT_H__
+
+#include <ruby.h>
+#ifdef RUBY_1_8
+ #include <rubyio.h>
+#else
+ #include <ruby/io.h>
+#endif
+
+#include <string.h>
+
#ifdef MEMWATCH
#include "memwatch.h"
#endif
#include "rb_utils.h"
#include "parser.h"
#include "parameters.h"
#include "extfunc.h"
#define RUBY_XSLT_VERSION "0.9.9"
#define RUBY_XSLT_VERNUM 099
#define RUBY_XSLT_XSLSRC_TYPE_NULL 0
#define RUBY_XSLT_XSLSRC_TYPE_STR 1
#define RUBY_XSLT_XSLSRC_TYPE_FILE 2
#define RUBY_XSLT_XSLSRC_TYPE_REXML 4
#define RUBY_XSLT_XSLSRC_TYPE_SMART 8
#define RUBY_XSLT_XSLSRC_TYPE_PARSED 16
#define RUBY_XSLT_XMLSRC_TYPE_NULL 0
#define RUBY_XSLT_XMLSRC_TYPE_STR 1
#define RUBY_XSLT_XMLSRC_TYPE_FILE 2
#define RUBY_XSLT_XMLSRC_TYPE_REXML 4
#define RUBY_XSLT_XMLSRC_TYPE_SMART 8
#define RUBY_XSLT_XMLSRC_TYPE_PARSED 16
RUBY_EXTERN VALUE eXSLTError;
RUBY_EXTERN VALUE eXSLTParsingError;
RUBY_EXTERN VALUE eXSLTTransformationError;
typedef struct RbTxslt {
int iXmlType;
VALUE xXmlData;
VALUE oXmlObject;
VALUE xXmlString;
xmlDocPtr tXMLDocument;
int iXslType;
VALUE xXslData;
VALUE oXslObject;
VALUE xXslString;
xsltStylesheetPtr tParsedXslt;
int iXmlResultType;
VALUE xXmlResultCache;
VALUE pxParams;
int iNbParams;
} RbTxslt;
#endif
diff --git a/ruby-xslt.gemspec b/ruby-xslt.gemspec
index 56b8126..2aca4c8 100644
--- a/ruby-xslt.gemspec
+++ b/ruby-xslt.gemspec
@@ -1,65 +1,65 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
- s.name = %q{ruby-xslt}
- s.version = "0.9.8"
+ s.name = "ruby-xslt"
+ s.version = "0.9.9"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Gregoire Lejeune"]
- s.date = %q{2010-11-26}
- s.description = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>}
- s.email = %q{[email protected]}
+ s.date = "2012-02-15"
+ s.description = "Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>"
+ s.email = "[email protected]"
s.extensions = ["ext/xslt_lib/extconf.rb"]
s.extra_rdoc_files = [
"ChangeLog",
"README.rdoc"
]
s.files = [
"AUTHORS",
"COPYING",
"ChangeLog",
"README.rdoc",
"Rakefile",
"VERSION",
"ext/xslt_lib/extconf.rb",
"ext/xslt_lib/extfunc.c",
"ext/xslt_lib/extfunc.h",
"ext/xslt_lib/parameters.c",
"ext/xslt_lib/parameters.h",
"ext/xslt_lib/parser.c",
"ext/xslt_lib/parser.h",
"ext/xslt_lib/rb_utils.c",
"ext/xslt_lib/rb_utils.h",
"ext/xslt_lib/xslt.h",
"ext/xslt_lib/xslt_lib.c",
"lib/xml/xslt.rb",
"ruby-xslt.gemspec",
"setup.rb",
"test/subdir/result.xsl",
"test/subdir/test.xsl",
"test/t.xml",
"test/t.xsl",
"test/test.rb"
]
- s.homepage = %q{http://github.com/glejeune/ruby-xslt}
+ s.homepage = "http://github.com/glejeune/ruby-xslt"
s.require_paths = ["lib"]
- s.rubygems_version = %q{1.3.7}
- s.summary = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>}
- s.test_files = [
- "test/test.rb"
- ]
+ s.rubygems_version = "1.8.10"
+ s.summary = "Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>"
+ s.test_files = ["test/test.rb"]
if s.respond_to? :specification_version then
- current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
+ s.add_development_dependency(%q<rdoc>, [">= 0"])
else
+ s.add_dependency(%q<rdoc>, [">= 0"])
end
else
+ s.add_dependency(%q<rdoc>, [">= 0"])
end
end
|
glejeune/ruby-xslt
|
25c44b350f587010663f35fa979120ab6ffde2b0
|
Version bump to 0.9.9
|
diff --git a/VERSION b/VERSION
index e3e1807..6f060dc 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.9.8
+0.9.9
\ No newline at end of file
|
glejeune/ruby-xslt
|
7e8b060b3f86b7b6c1f57b158ba7cf6778b7210e
|
Replace STR2CSTR by StringValuePtr
|
diff --git a/ChangeLog b/ChangeLog
index a3e99f7..bd42d14 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,85 +1,88 @@
+0.9.8 :
+* Replace STR2CSTR by StringValuePtr
+
0.9.7 :
* Ruby 1.9
* Bug correction (Issue #1)
0.9.6 :
* "found and patched some serious memory leaks" (thanks to Tom)
0.9.5 :
* Bugfix in extconf.c (thanks to Stephane Mariel)
0.9.4 :
* ...
0.9.3 :
* Due to recent changes in Gentoo Linux's install system, ruby-xslt no longer installs correctly. Brendan fixed this.
* Cleaned up extconf.rb
* Removed unused debugging code (memwatch)
* Moved some things out of C into Ruby
* Made error handling much more useful
* Added some unit tests
0.9.2 :
* Changes to the way XSLT files are loaded, so that we can keep their base URI straight - Sorry Brendan !!!
* Major corrections
0.9.1 :
* Add XML/Smart support. XML/Simple support is still available
* Add REXML support.
* Add error classes and sets libxml error function
* Move samples scripts from tests to examples and add unit tests
* Changes to the way XSLT files are loaded, so that we can keep their base URI straight
* Major bugs corrections
0.8.2 :
* Configuration changes:
ruby extconf.rb --enable-exslt (on by default) : enables libexslt support <http://exslt.org/>
ruby extconf.rb --enable-error-handler (off by default) : enables a VERY crude error handler. error messages are appended to the class variable XML::XSLT and can be accessed with the class method XML::XSLT.errors (not very good, but better than trapping $stderr)
* API changes:
XML::XSLT.new.extFunction("do-this", "http://fake.none", MyClass, "do_this")
is now
XML::XSLT.extFunction("do-this", "http://fake.none", MyClass)
The callback function will now call the function with the same name as the function that was called. One (possibly confusing) exception is that when you register a function with a '-' in it the name of the ruby method called has the '-'s replaced with '_'s. This is because there seems to be a convention of naming XPath functions with hyphens and they're illegal in Ruby method names.
The big stability change is that the external function table is now stored in a hash of hashes on the XSLT class object. (rather than a global xmlHash) It makes more sense to make it a property of the class and the hashes are an easy way to implement it.
The type of objects that are passed to and returned from extension functions has changed to be more sane. REXML is now required to convert an xmlXPathObj to and from a VALUE; nodesets are passed to Ruby as an array of REXML::Elements and REXML::Elements / REXML::Documents returned from Ruby get turned into nodesets.
* Potential problems:
xsltCleanupGlobals() shouldn't be called until we're done with whatever functions that are registered (probably when our program doesn't need ruby-xslt at all any more).
0.8.1 :
* Major bug correction
0.8.0 :
* Major bug correction in parameters support
0.7.0 :
* Add external functions support
0.6.0 :
* Major bug correction
0.5.0 :
* Add XML/Simple support
* Add parameters support
0.4.0 :
* Add cache
0.3.0 :
* Major bug correction
0.2.0 :
* Major bug correction
0.1.0 :
* Initial version
diff --git a/ext/xslt_lib/extfunc.c b/ext/xslt_lib/extfunc.c
index 613ccb8..9e7cadd 100644
--- a/ext/xslt_lib/extfunc.c
+++ b/ext/xslt_lib/extfunc.c
@@ -1,213 +1,213 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
extern VALUE mXML;
extern VALUE cXSLT;
/**
* external function support, patch from :
*
* Brendan Taylor
* [email protected]
*
*/
/* converts an xmlXPathObjectPtr to a Ruby VALUE
* number -> float
* boolean -> boolean
* string -> string
* nodeset -> an array of REXML::Elements
*/
VALUE xpathObj2value(xmlXPathObjectPtr obj, xmlDocPtr doc)
{
VALUE ret = Qnil;
if (obj == NULL) {
return ret;
}
switch (obj->type) {
case XPATH_NODESET:
rb_require("rexml/document");
ret = rb_ary_new();
if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) {
xmlBufferPtr buff = xmlBufferCreate();
xmlNodePtr node;
int i;
// this assumes all the nodes are elements, which is a bad idea
for (i = 0; i < obj->nodesetval->nodeNr; i++) {
node = obj->nodesetval->nodeTab[i];
if( node->type == XML_ELEMENT_NODE ) {
xmlNodeDump(buff, doc, node, 0, 0);
VALUE cREXML = rb_const_get(rb_cObject, rb_intern("REXML"));
VALUE cDocument = rb_const_get(cREXML, rb_intern("Document"));
VALUE rDocument = rb_funcall(cDocument, rb_intern("new"), 1,rb_str_new2((char *)buff->content));
VALUE rElement = rb_funcall(rDocument, rb_intern("root"), 0);
rb_ary_push(ret, rElement);
// empty the buffer (xmlNodeDump appends rather than replaces)
xmlBufferEmpty(buff);
} else if ( node->type == XML_TEXT_NODE ) {
rb_ary_push(ret, rb_str_new2((char *)node->content));
} else if ( node->type == XML_ATTRIBUTE_NODE ) {
// BUG: should ensure children is not null (shouldn't)
rb_ary_push(ret, rb_str_new2((char *)node->children->content));
} else {
rb_warning( "Unsupported node type in node set: %d", node->type );
}
}
xmlBufferFree(buff);
}
break;
case XPATH_BOOLEAN:
ret = obj->boolval ? Qtrue : Qfalse;
break;
case XPATH_NUMBER:
ret = rb_float_new(obj->floatval);
break;
case XPATH_STRING:
ret = rb_str_new2((char *) obj->stringval);
break;
/* these cases were in libxslt's python bindings, but i don't know what they are, so i'll leave them alone */
case XPATH_XSLT_TREE:
case XPATH_POINT:
case XPATH_RANGE:
case XPATH_LOCATIONSET:
default:
rb_warning("xpathObj2value: can't convert XPath object type %d to Ruby object\n", obj->type );
}
xmlXPathFreeObject(obj);
return ret;
}
/*
* converts a Ruby VALUE to an xmlXPathObjectPtr
* boolean -> boolean
* number -> number
* string -> escaped string
* array -> array of parsed nodes
*/
xmlXPathObjectPtr value2xpathObj (VALUE val) {
xmlXPathObjectPtr ret = NULL;
switch (TYPE(val)) {
case T_TRUE:
case T_FALSE:
ret = xmlXPathNewBoolean(RTEST(val));
break;
case T_FIXNUM:
case T_FLOAT:
ret = xmlXPathNewFloat(NUM2DBL(val));
break;
case T_STRING:
{
xmlChar *str;
// we need the Strdup (this is the major bugfix for 0.8.1)
- str = xmlStrdup((const xmlChar *) STR2CSTR(val));
+ str = xmlStrdup((const xmlChar *) StringValuePtr(val));
ret = xmlXPathWrapString(str);
}
break;
case T_NIL:
ret = xmlXPathNewNodeSet(NULL);
break;
case T_ARRAY: {
int i,j;
ret = xmlXPathNewNodeSet(NULL);
for(i = RARRAY_LEN(val); i > 0; i--) {
xmlXPathObjectPtr obj = value2xpathObj( rb_ary_shift( val ) );
if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) {
for(j = 0; j < obj->nodesetval->nodeNr; j++) {
xmlXPathNodeSetAdd( ret->nodesetval, obj->nodesetval->nodeTab[j] );
}
}
}
break; }
case T_DATA:
case T_OBJECT: {
if( strcmp( getRubyObjectName( val ), "REXML::Document" ) == 0 || strcmp(getRubyObjectName( val ), "REXML::Element") == 0 ) {
VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 );
- xmlDocPtr doc = xmlParseDoc((xmlChar *) STR2CSTR(to_s));
+ xmlDocPtr doc = xmlParseDoc((xmlChar *) StringValuePtr(to_s));
ret = xmlXPathNewNodeSet((xmlNode *)doc->children);
break;
} else if( strcmp( getRubyObjectName( val ), "REXML::Text" ) == 0 ) {
VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 );
xmlChar *str;
- str = xmlStrdup((const xmlChar *) STR2CSTR(to_s));
+ str = xmlStrdup((const xmlChar *) StringValuePtr(to_s));
ret = xmlXPathWrapString(str);
break;
}
// this drops through so i can reuse the error message
}
default:
rb_warning( "value2xpathObj: can't convert class %s to XPath object\n", getRubyObjectName(val));
return NULL;
}
return ret;
}
/*
* chooses what registered function to call and calls it
*/
void xmlXPathFuncCallback( xmlXPathParserContextPtr ctxt, int nargs) {
VALUE result, arguments[nargs];
VALUE ns_hash, func_hash, block;
const xmlChar *namespace, *name;
xmlXPathObjectPtr obj;
int i;
if (ctxt == NULL || ctxt->context == NULL)
return;
name = ctxt->context->function;
namespace = ctxt->context->functionURI;
ns_hash = rb_cvar_get(cXSLT, rb_intern("@@extFunctions"));
func_hash = rb_hash_aref(ns_hash, rb_str_new2((char *)namespace));
if(func_hash == Qnil) {
rb_warning( "xmlXPathFuncCallback: namespace %s not registered!\n", namespace );
}
block = rb_hash_aref(func_hash, rb_str_new2((char *)name));
for (i = nargs - 1; i >= 0; i--) {
obj = valuePop(ctxt);
arguments[i] = xpathObj2value(obj, ctxt->context->doc);
}
result = rb_funcall2( block, rb_intern("call"), nargs, arguments);
obj = value2xpathObj(result);
valuePush(ctxt, obj);
}
diff --git a/ext/xslt_lib/parameters.c b/ext/xslt_lib/parameters.c
index 5cb2693..8b6e44f 100644
--- a/ext/xslt_lib/parameters.c
+++ b/ext/xslt_lib/parameters.c
@@ -1,59 +1,59 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
/**
* parameters support, patch from :
*
* Eustáquio "TaQ" Rangel
* [email protected]
* http://beam.to/taq
*
*/
VALUE each_pair( VALUE obj ) {
return rb_funcall( obj, rb_intern("each"), 0, 0 );
}
VALUE process_pair( VALUE pair, VALUE rbparams ) {
VALUE key, value;
// Thx to alex__
int count = FIX2INT( rb_funcall( rbparams, rb_intern("size"), 0, 0 ) );
// static int count = 0;
char *xValue = NULL;
Check_Type( pair, T_ARRAY );
key = RARRAY_PTR(pair)[0];
value = rb_obj_clone( RARRAY_PTR(pair)[1] );
Check_Type( key, T_STRING );
Check_Type( value, T_STRING );
- xValue = STR2CSTR( value );
+ xValue = StringValuePtr( value );
if( xValue[0] != '\'' && xValue[strlen( xValue ) - 1] != '\'' ) {
value = rb_str_concat( value, rb_str_new2( "'" ) );
value = rb_str_concat( rb_str_new2( "'" ), value );
}
rb_ary_store( rbparams, count, key );
rb_ary_store( rbparams, count + 1, value );
count += 2;
return Qnil;
}
diff --git a/ext/xslt_lib/parser.c b/ext/xslt_lib/parser.c
index 6fd72f5..6c10134 100644
--- a/ext/xslt_lib/parser.c
+++ b/ext/xslt_lib/parser.c
@@ -1,195 +1,195 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
#include "parser.h"
extern VALUE cXSLT;
xmlDocPtr parse_xml( char* xml, int iXmlType ) {
xmlDocPtr tXMLDocument = NULL;
/** Act: Parse XML */
if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_STR ) {
tXMLDocument = xmlParseMemory( xml, strlen( xml ) );
} else if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_FILE ) {
tXMLDocument = xmlParseFile( xml );
}
if( tXMLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XML parsing error" );
return( NULL );
}
return( tXMLDocument );
}
xsltStylesheetPtr parse_xsl( char* xsl, int iXslType ) {
xsltStylesheetPtr tParsedXslt = NULL;
xmlDocPtr tXSLDocument = NULL;
/** Rem: For encoding */
xmlCharEncodingHandlerPtr encoder = NULL;
const xmlChar *encoding = NULL;
/** Act: Encoding support */
xmlInitCharEncodingHandlers( );
/** Act: Parse XSL */
if( iXslType == RUBY_XSLT_XSLSRC_TYPE_STR ) {
tXSLDocument = xmlParseMemory( xsl, strlen( xsl ) );
if( tXSLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XSL parsing error" );
return( NULL );
}
tParsedXslt = xsltParseStylesheetDoc( tXSLDocument );
} else if( iXslType == RUBY_XSLT_XSLSRC_TYPE_FILE ) {
tParsedXslt = xsltParseStylesheetFile( BAD_CAST xsl );
}
if( tParsedXslt == NULL ) {
rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
return( NULL );
}
/** Act: Get encoding */
XSLT_GET_IMPORT_PTR( encoding, tParsedXslt, encoding )
encoder = xmlFindCharEncodingHandler((char *)encoding);
if( encoding != NULL ) {
encoder = xmlFindCharEncodingHandler((char *)encoding);
if( (encoder != NULL) && (xmlStrEqual((const xmlChar *)encoder->name, (const xmlChar *) "UTF-8")) ) {
encoder = NULL;
}
}
return( tParsedXslt );
}
/**
* xOut = parser( char *xml, int iXmlType, char *xslt, int iXslType, char **pxParams );
*/
char* parse( xsltStylesheetPtr tParsedXslt, xmlDocPtr tXMLDocument, char **pxParams ) {
xmlDocPtr tXMLDocumentResult = NULL;
int iXMLDocumentResult;
xmlChar *tXMLDocumentResultString;
int tXMLDocumentResultLenght;
tXMLDocumentResult = xsltApplyStylesheet( tParsedXslt, tXMLDocument, (const char**) pxParams );
if( tXMLDocumentResult == NULL ) {
rb_raise( eXSLTTransformationError, "Stylesheet transformation error" );
return( NULL );
}
iXMLDocumentResult = xsltSaveResultToString( &tXMLDocumentResultString, &tXMLDocumentResultLenght, tXMLDocumentResult, tParsedXslt );
xmlFreeDoc(tXMLDocumentResult);
return((char*)tXMLDocumentResultString);
}
/**
* vOut = object_to_string( VALUE object );
*/
VALUE object_to_string( VALUE object ) {
VALUE vOut = Qnil;
switch( TYPE( object ) ) {
case T_STRING:
{
- if( isFile( STR2CSTR( object ) ) == 0 ) {
+ if( isFile( StringValuePtr( object ) ) == 0 ) {
vOut = object;
} else {
long iBufferLength;
long iCpt;
char *xBuffer;
- FILE* fStream = fopen( STR2CSTR( object ), "r" );
+ FILE* fStream = fopen( StringValuePtr( object ), "r" );
if( fStream == NULL ) {
return( Qnil );
}
fseek( fStream, 0L, 2 );
iBufferLength = ftell( fStream );
xBuffer = (char *)malloc( (int)iBufferLength + 1 );
if( !xBuffer )
rb_raise( rb_eNoMemError, "Memory allocation error" );
xBuffer[iBufferLength] = 0;
fseek( fStream, 0L, 0 );
iCpt = fread( xBuffer, 1, (int)iBufferLength, fStream );
if( iCpt != iBufferLength ) {
free( (char *)xBuffer );
rb_raise( rb_eSystemCallError, "Read file error" );
}
vOut = rb_str_new2( xBuffer );
free( xBuffer );
fclose( fStream );
}
}
break;
case T_DATA:
case T_OBJECT:
{
if( strcmp( getRubyObjectName( object ), "XML::Smart::Dom" ) == 0 ||
strcmp( getRubyObjectName( object ), "XML::Simple::Dom" ) == 0 ) {
vOut = rb_funcall( object, rb_intern( "to_s" ), 0 );
} else if ( strcmp( getRubyObjectName( object ), "REXML::Document" ) == 0 ) {
vOut = rb_funcall( object, rb_intern( "to_s" ), 0 );
} else {
rb_raise( rb_eSystemCallError, "Can't read XML from object %s", getRubyObjectName( object ) );
}
}
break;
default:
rb_raise( rb_eArgError, "XML object #0x%x not supported", TYPE( object ) );
}
return( vOut );
}
/**
* bOut = objectIsFile( VALUE object );
*/
int objectIsFile( VALUE object ) {
int bOut = 0;
switch( TYPE( object ) ) {
case T_STRING:
{
- if( isFile( STR2CSTR( object ) ) == 0 )
+ if( isFile( StringValuePtr( object ) ) == 0 )
bOut = 0;
else
bOut = 1;
}
break;
case T_DATA:
case T_OBJECT:
default:
bOut = 0;
}
return( bOut );
}
diff --git a/ext/xslt_lib/rb_utils.c b/ext/xslt_lib/rb_utils.c
index 1eec15f..503c7ed 100644
--- a/ext/xslt_lib/rb_utils.c
+++ b/ext/xslt_lib/rb_utils.c
@@ -1,31 +1,32 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "rb_utils.h"
char * getRubyObjectName( VALUE rb_Object ) {
VALUE klass = rb_funcall( rb_Object, rb_intern( "class" ), 0 );
- return( STR2CSTR( rb_funcall( klass, rb_intern( "to_s" ), 0 ) ) );
+ VALUE tmp = rb_funcall( klass, rb_intern( "to_s" ), 0 );
+ return( StringValuePtr( tmp ) );
}
int isFile( const char *filename ) {
struct stat stbuf;
if( stat( filename, &stbuf ) ) return 0;
return( ( (stbuf.st_mode & S_IFMT) == S_IFREG ) ? 1 : 0 );
}
diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h
index 9c97cfc..80f2005 100644
--- a/ext/xslt_lib/xslt.h
+++ b/ext/xslt_lib/xslt.h
@@ -1,102 +1,102 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Please see the LICENSE file for copyright and distribution information */
#ifndef __RUBY_XSLT_H__
#define __RUBY_XSLT_H__
#include <ruby.h>
#ifdef RUBY_1_8
#include <rubyio.h>
#else
#include <ruby/io.h>
#endif
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/extra.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libxslt/imports.h>
#ifdef USE_EXSLT
#include <libexslt/exslt.h>
#endif
#ifdef MEMWATCH
#include "memwatch.h"
#endif
#include "rb_utils.h"
#include "parser.h"
#include "parameters.h"
#include "extfunc.h"
-#define RUBY_XSLT_VERSION "0.9.7"
-#define RUBY_XSLT_VERNUM 097
+#define RUBY_XSLT_VERSION "0.9.8"
+#define RUBY_XSLT_VERNUM 098
#define RUBY_XSLT_XSLSRC_TYPE_NULL 0
#define RUBY_XSLT_XSLSRC_TYPE_STR 1
#define RUBY_XSLT_XSLSRC_TYPE_FILE 2
#define RUBY_XSLT_XSLSRC_TYPE_REXML 4
#define RUBY_XSLT_XSLSRC_TYPE_SMART 8
#define RUBY_XSLT_XSLSRC_TYPE_PARSED 16
#define RUBY_XSLT_XMLSRC_TYPE_NULL 0
#define RUBY_XSLT_XMLSRC_TYPE_STR 1
#define RUBY_XSLT_XMLSRC_TYPE_FILE 2
#define RUBY_XSLT_XMLSRC_TYPE_REXML 4
#define RUBY_XSLT_XMLSRC_TYPE_SMART 8
#define RUBY_XSLT_XMLSRC_TYPE_PARSED 16
RUBY_EXTERN VALUE eXSLTError;
RUBY_EXTERN VALUE eXSLTParsingError;
RUBY_EXTERN VALUE eXSLTTransformationError;
typedef struct RbTxslt {
int iXmlType;
VALUE xXmlData;
VALUE oXmlObject;
VALUE xXmlString;
xmlDocPtr tXMLDocument;
int iXslType;
VALUE xXslData;
VALUE oXslObject;
VALUE xXslString;
xsltStylesheetPtr tParsedXslt;
int iXmlResultType;
VALUE xXmlResultCache;
VALUE pxParams;
int iNbParams;
} RbTxslt;
#endif
diff --git a/ext/xslt_lib/xslt_lib.c b/ext/xslt_lib/xslt_lib.c
index 4c441e6..f7953ee 100644
--- a/ext/xslt_lib/xslt_lib.c
+++ b/ext/xslt_lib/xslt_lib.c
@@ -1,599 +1,600 @@
/**
* Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "xslt.h"
VALUE mXML;
VALUE cXSLT;
VALUE eXSLTError;
VALUE eXSLTParsingError;
VALUE eXSLTTransformationError;
void ruby_xslt_free( RbTxslt *pRbTxslt ) {
if( pRbTxslt != NULL ) {
if( pRbTxslt->tParsedXslt != NULL )
xsltFreeStylesheet(pRbTxslt->tParsedXslt);
if( pRbTxslt->tXMLDocument != NULL )
xmlFreeDoc(pRbTxslt->tXMLDocument);
free( pRbTxslt );
}
xsltCleanupGlobals();
xmlCleanupParser();
xmlMemoryDump();
}
void ruby_xslt_mark( RbTxslt *pRbTxslt ) {
if( pRbTxslt == NULL ) return;
if( !NIL_P(pRbTxslt->xXmlData) ) rb_gc_mark( pRbTxslt->xXmlData );
if( !NIL_P(pRbTxslt->oXmlObject) ) rb_gc_mark( pRbTxslt->oXmlObject );
if( !NIL_P(pRbTxslt->xXmlString) ) rb_gc_mark( pRbTxslt->xXmlString );
if( !NIL_P(pRbTxslt->xXslData) ) rb_gc_mark( pRbTxslt->xXslData );
if( !NIL_P(pRbTxslt->oXslObject) ) rb_gc_mark( pRbTxslt->oXslObject );
if( !NIL_P(pRbTxslt->xXslString) ) rb_gc_mark( pRbTxslt->xXslString );
if( !NIL_P(pRbTxslt->xXmlResultCache) ) rb_gc_mark( pRbTxslt->xXmlResultCache );
if( !NIL_P(pRbTxslt->pxParams) ) rb_gc_mark( pRbTxslt->pxParams );
}
/**
* oXSLT = XML::XSLT::new()
*
* Create a new XML::XSLT object
*/
VALUE ruby_xslt_new( VALUE class ) {
RbTxslt *pRbTxslt;
pRbTxslt = (RbTxslt *)malloc(sizeof(RbTxslt));
if( pRbTxslt == NULL )
rb_raise(rb_eNoMemError, "No memory left for XSLT struct");
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlData = Qnil;
pRbTxslt->oXmlObject = Qnil;
pRbTxslt->xXmlString = Qnil;
pRbTxslt->tXMLDocument = NULL;
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_NULL;
pRbTxslt->xXslData = Qnil;
pRbTxslt->oXslObject = Qnil;
pRbTxslt->xXslString = Qnil;
pRbTxslt->tParsedXslt = NULL;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->pxParams = Qnil;
pRbTxslt->iNbParams = 0;
xmlInitMemory();
xmlSubstituteEntitiesDefault( 1 );
xmlLoadExtDtdDefaultValue = 1;
return( Data_Wrap_Struct( class, ruby_xslt_mark, ruby_xslt_free, pRbTxslt ) );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xml=<data|REXML::Document|XML::Smart|file>
*
* Set XML data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xml = <<XML
* <?xml version="1.0" encoding="UTF-8"?>
* <test>This is a test string</test>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xml = REXML::Document.new File.open( "test.xml" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xml = XML::Smart.open( "test.xml" )
*
* # Parameter as Filename
* oXSLT.xml = "test.xml"
*/
VALUE ruby_xslt_xml_obj_set( VALUE self, VALUE xml_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXmlObject = xml_doc_obj;
pRbTxslt->xXmlString = object_to_string( xml_doc_obj );
if( pRbTxslt->xXmlString == Qnil ) {
rb_raise( eXSLTError, "Can't get XML data" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_STR;
pRbTxslt->xXmlData = pRbTxslt->xXmlString;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tXMLDocument != NULL ) {
xmlFreeDoc(pRbTxslt->tXMLDocument);
}
- pRbTxslt->tXMLDocument = parse_xml( STR2CSTR( pRbTxslt->xXmlData ), pRbTxslt->iXmlType );
+ pRbTxslt->tXMLDocument = parse_xml( StringValuePtr( pRbTxslt->xXmlData ), pRbTxslt->iXmlType );
if( pRbTxslt->tXMLDocument == NULL ) {
rb_raise( eXSLTParsingError, "XML parsing error" );
}
pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file>
*/
VALUE ruby_xslt_xml_obj_set_d( VALUE self, VALUE xml_doc_obj ) {
rb_warn( "XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file> !" );
return( ruby_xslt_xml_obj_set( self, xml_doc_obj ) );
}
/**
* string = oXSLT.xml
*
* Return XML, set by XML::XSLT#xml=, as string
*/
VALUE ruby_xslt_xml_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXmlString );
}
/**
* object = oXSLT.xmlobject
*
* Return the XML object set by XML::XSLT#xml=
*/
VALUE ruby_xslt_xml_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXmlObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* oXSLT.xsl=<data|REXML::Document|XML::Smart|file>
*
* Set XSL data.
*
* Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename
*
* Examples :
* # Parameter as String
* oXSLT.xsl = <<XML
* <?xml version="1.0" ?>
* <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
* <xsl:template match="/">
* <xsl:apply-templates />
* </xsl:template>
* </xsl:stylesheet>
* XML
*
* # Parameter as REXML::Document
* require 'rexml/document'
* oXSLT.xsl = REXML::Document.new File.open( "test.xsl" )
*
* # Parameter as XML::Smart::Dom
* require 'xml/smart'
* oXSLT.xsl = XML::Smart.open( "test.xsl" )
*
* # Parameter as Filename
* oXSLT.xsl = "test.xsl"
*/
VALUE ruby_xslt_xsl_obj_set( VALUE self, VALUE xsl_doc_obj ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
pRbTxslt->oXslObject = xsl_doc_obj;
pRbTxslt->xXslString = object_to_string( xsl_doc_obj );
if( pRbTxslt->xXslString == Qnil ) {
rb_raise( eXSLTError, "Can't get XSL data" );
}
if( objectIsFile( xsl_doc_obj ) ) {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_FILE;
pRbTxslt->xXslData = pRbTxslt->oXslObject;
} else {
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_STR;
pRbTxslt->xXslData = pRbTxslt->xXslString;
}
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
if( pRbTxslt->tParsedXslt != NULL ) {
xsltFreeStylesheet(pRbTxslt->tParsedXslt);
}
- pRbTxslt->tParsedXslt = parse_xsl( STR2CSTR( pRbTxslt->xXslData ), pRbTxslt->iXslType );
+ pRbTxslt->tParsedXslt = parse_xsl( StringValuePtr( pRbTxslt->xXslData ), pRbTxslt->iXslType );
if( pRbTxslt->tParsedXslt == NULL ) {
rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
}
pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_PARSED;
return( Qnil );
}
/**
* XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file>
*/
VALUE ruby_xslt_xsl_obj_set_d( VALUE self, VALUE xsl_doc_obj ) {
rb_warning( "XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file> !" );
return( ruby_xslt_xsl_obj_set( self, xsl_doc_obj ) );
}
/**
* string = oXSLT.xsl
*
* Return XSL, set by XML::XSLT#xsl=, as string
*/
VALUE ruby_xslt_xsl_2str_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->xXslString );
}
/**
* object = oXSLT.xslobject
*
* Return the XSL object set by XML::XSLT#xsl=
*/
VALUE ruby_xslt_xsl_2obj_get( VALUE self ) {
RbTxslt *pRbTxslt;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
return( pRbTxslt->oXslObject );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* output_string = oXSLT.serve( )
*
* Return the stylesheet transformation
*/
VALUE ruby_xslt_serve( VALUE self ) {
RbTxslt *pRbTxslt;
char *xOut;
char **pxParams = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( pRbTxslt->iXmlResultType == RUBY_XSLT_XMLSRC_TYPE_NULL ) {
if( pRbTxslt->pxParams != Qnil ){
int iCpt;
pxParams = (char **)ALLOCA_N( void *, pRbTxslt->iNbParams );
MEMZERO( pxParams, void *, pRbTxslt->iNbParams );
for( iCpt = 0; iCpt <= pRbTxslt->iNbParams - 3; iCpt++ ) {
- pxParams[iCpt] = STR2CSTR( rb_ary_entry( pRbTxslt->pxParams, iCpt ) );
+ VALUE tmp = rb_ary_entry( pRbTxslt->pxParams, iCpt );
+ pxParams[iCpt] = StringValuePtr( tmp );
}
}
if( pRbTxslt->iXslType != RUBY_XSLT_XSLSRC_TYPE_NULL &&
pRbTxslt->iXmlType != RUBY_XSLT_XMLSRC_TYPE_NULL ) {
xOut = parse( pRbTxslt->tParsedXslt, pRbTxslt->tXMLDocument, pxParams );
if( xOut == NULL ) {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
} else {
pRbTxslt->xXmlResultCache = rb_str_new2( xOut );
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_STR;
free( xOut );
}
} else {
pRbTxslt->xXmlResultCache = Qnil;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
}
return( pRbTxslt->xXmlResultCache );
}
/**
* oXSLT.save( "result.xml" )
*
* Save the stylesheet transformation to file
*/
VALUE ruby_xslt_save( VALUE self, VALUE xOutFilename ) {
char *xOut;
VALUE rOut;
FILE *fOutFile;
rOut = ruby_xslt_serve( self );
if( rOut != Qnil ) {
- xOut = STR2CSTR( rOut );
+ xOut = StringValuePtr( rOut );
- fOutFile = fopen( STR2CSTR( xOutFilename ), "w" );
+ fOutFile = fopen( StringValuePtr( xOutFilename ), "w" );
if( fOutFile == NULL ) {
free( xOut );
- rb_raise( rb_eRuntimeError, "Can't create file %s\n", STR2CSTR( xOutFilename ) );
+ rb_raise( rb_eRuntimeError, "Can't create file %s\n", StringValuePtr( xOutFilename ) );
rOut = Qnil;
} else {
fwrite( xOut, 1, strlen( xOut ), fOutFile );
fclose( fOutFile );
}
}
return( rOut );
}
/**
* ----------------------------------------------------------------------------
*/
#ifdef USE_ERROR_HANDLER
/**
* Brendan Taylor
* [email protected]
*/
/*
* libxml2/libxslt error handling function
*
* converts the error to a String and passes it off to a block
* registered using XML::XSLT.register_error_handler
*/
void ruby_xslt_error_handler(void *ctx, const char *msg, ...) {
va_list ap;
char *str;
char *larger;
int chars;
int size = 150;
VALUE block = rb_cvar_get(cXSLT, rb_intern("@@error_handler"));
/* the following was cut&pasted from the libxslt python bindings */
str = (char *) xmlMalloc(150);
if (str == NULL)
return;
while (1) {
va_start(ap, msg);
chars = vsnprintf(str, size, msg, ap);
va_end(ap);
if ((chars > -1) && (chars < size))
break;
if (chars > -1)
size += chars + 1;
else
size += 100;
if ((larger = (char *) xmlRealloc(str, size)) == NULL) {
xmlFree(str);
return;
}
str = larger;
}
rb_funcall( block, rb_intern("call"), 1, rb_str_new2(str));
}
#endif
/**
* ----------------------------------------------------------------------------
*/
/**
* parameters support, patch from :
*
* Eustáquio "TaQ" Rangel
* [email protected]
* http://beam.to/taq
*
* Corrections : Greg
*/
/**
* oXSLT.parameters={ "key" => "value", "key" => "value", ... }
*/
VALUE ruby_xslt_parameters_set( VALUE self, VALUE parameters ) {
RbTxslt *pRbTxslt;
Check_Type( parameters, T_HASH );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
if( !NIL_P(parameters) ){
pRbTxslt->pxParams = rb_ary_new( );
// each_pair and process_pair defined ind parameters.c
(void)rb_iterate( each_pair, parameters, process_pair, pRbTxslt->pxParams );
pRbTxslt->iNbParams = FIX2INT( rb_funcall( parameters, rb_intern("size"), 0, 0 ) ) * 2 + 2;
pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL;
}
return( Qnil );
}
/**
* ----------------------------------------------------------------------------
*/
/**
* media type information, path from :
*
* Brendan Taylor
* [email protected]
*
*/
/**
* mediaTypeString = oXSLT.mediaType( )
*
* Return the XSL output's media type
*/
VALUE ruby_xslt_media_type( VALUE self ) {
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
Data_Get_Struct( self, RbTxslt, pRbTxslt );
vXSLTSheet = pRbTxslt->tParsedXslt;
if ( (vXSLTSheet == NULL) || (vXSLTSheet->mediaType == NULL) ) {
return Qnil;
} else {
return rb_str_new2( (char *)(vXSLTSheet->mediaType) );
}
}
/**
* ----------------------------------------------------------------------------
*/
/**
* internal use only.
*/
VALUE ruby_xslt_reg_function( VALUE class, VALUE namespace, VALUE name ) {
- xsltRegisterExtModuleFunction( BAD_CAST STR2CSTR(name), BAD_CAST STR2CSTR(namespace), xmlXPathFuncCallback );
+ xsltRegisterExtModuleFunction( BAD_CAST StringValuePtr(name), BAD_CAST StringValuePtr(namespace), xmlXPathFuncCallback );
return Qnil;
}
/**
* string = oXSLT.xsl_to_s( )
*/
VALUE ruby_xslt_to_s( VALUE self ) {
VALUE vStrOut;
RbTxslt *pRbTxslt;
xsltStylesheetPtr vXSLTSheet = NULL;
char *xKlassName = rb_class2name( CLASS_OF( self ) );
Data_Get_Struct( self, RbTxslt, pRbTxslt );
- //vXSLTSheet = xsltParseStylesheetDoc( xmlParseMemory( STR2CSTR( pRbTxslt->xXslData ), strlen( STR2CSTR( pRbTxslt->xXslData ) ) ) );
+ //vXSLTSheet = xsltParseStylesheetDoc( xmlParseMemory( StringValuePtr( pRbTxslt->xXslData ), strlen( StringValuePtr( pRbTxslt->xXslData ) ) ) );
vXSLTSheet = pRbTxslt->tParsedXslt;
if (vXSLTSheet == NULL) return Qnil;
vStrOut = rb_str_new( 0, strlen(xKlassName)+1024 );
(void) sprintf( RSTRING_PTR(vStrOut),
"#<%s: parent=%p,next=%p,imports=%p,docList=%p,"
"doc=%p,stripSpaces=%p,stripAll=%d,cdataSection=%p,"
"variables=%p,templates=%p,templatesHash=%p,"
"rootMatch=%p,keyMatch=%p,elemMatch=%p,"
"attrMatch=%p,parentMatch=%p,textMatch=%p,"
"piMatch=%p,commentMatch=%p,nsAliases=%p,"
"attributeSets=%p,nsHash=%p,nsDefs=%p,keys=%p,"
"method=%s,methodURI=%s,version=%s,encoding=%s,"
"omitXmlDeclaration=%d,decimalFormat=%p,standalone=%d,"
"doctypePublic=%s,doctypeSystem=%s,indent=%d,"
"mediaType=%s,preComps=%p,warnings=%d,errors=%d,"
"exclPrefix=%s,exclPrefixTab=%p,exclPrefixNr=%d,"
"exclPrefixMax=%d>",
xKlassName,
vXSLTSheet->parent, vXSLTSheet->next, vXSLTSheet->imports, vXSLTSheet->docList,
vXSLTSheet->doc, vXSLTSheet->stripSpaces, vXSLTSheet->stripAll, vXSLTSheet->cdataSection,
vXSLTSheet->variables, vXSLTSheet->templates, vXSLTSheet->templatesHash,
vXSLTSheet->rootMatch, vXSLTSheet->keyMatch, vXSLTSheet->elemMatch,
vXSLTSheet->attrMatch, vXSLTSheet->parentMatch, vXSLTSheet->textMatch,
vXSLTSheet->piMatch, vXSLTSheet->commentMatch, vXSLTSheet->nsAliases,
vXSLTSheet->attributeSets, vXSLTSheet->nsHash, vXSLTSheet->nsDefs, vXSLTSheet->keys,
vXSLTSheet->method, vXSLTSheet->methodURI, vXSLTSheet->version, vXSLTSheet->encoding,
vXSLTSheet->omitXmlDeclaration, vXSLTSheet->decimalFormat, vXSLTSheet->standalone,
vXSLTSheet->doctypePublic, vXSLTSheet->doctypeSystem, vXSLTSheet->indent,
vXSLTSheet->mediaType, vXSLTSheet->preComps, vXSLTSheet->warnings, vXSLTSheet->errors,
vXSLTSheet->exclPrefix, vXSLTSheet->exclPrefixTab, vXSLTSheet->exclPrefixNr,
vXSLTSheet->exclPrefixMax );
vStrOut = strlen(RSTRING_PTR(vStrOut));
if( OBJ_TAINTED(self) ) OBJ_TAINT(vStrOut);
// xsltFreeStylesheet(vXSLTSheet);
return( vStrOut );
}
/**
* ----------------------------------------------------------------------------
*/
void Init_xslt_lib( void ) {
mXML = rb_define_module( "XML" );
cXSLT = rb_define_class_under( mXML, "XSLT", rb_cObject );
eXSLTError = rb_define_class_under( cXSLT, "XSLTError", rb_eRuntimeError );
eXSLTParsingError = rb_define_class_under( cXSLT, "ParsingError", eXSLTError );
eXSLTTransformationError = rb_define_class_under( cXSLT, "TransformationError", eXSLTError );
rb_define_const( cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth) );
rb_define_const( cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT) );
rb_define_const( cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion) );
rb_define_const( cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion) );
rb_define_const( cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion) );
rb_define_const( cXSLT, "XSLT_NAMESPACE", rb_str_new2((char *)XSLT_NAMESPACE) );
rb_define_const( cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR) );
rb_define_const( cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION) );
rb_define_const( cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL) );
rb_define_const( cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((char *)XSLT_LIBXSLT_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((char *)XSLT_NORM_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_SAXON", rb_str_new2((char *)XSLT_SAXON_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XT", rb_str_new2((char *)XSLT_XT_NAMESPACE) );
rb_define_const( cXSLT, "NAMESPACE_XALAN", rb_str_new2((char *)XSLT_XALAN_NAMESPACE) );
rb_define_const( cXSLT, "RUBY_XSLT_VERSION", rb_str_new2(RUBY_XSLT_VERSION) );
rb_define_singleton_method( cXSLT, "new", ruby_xslt_new, 0 );
rb_define_singleton_method( cXSLT, "registerFunction", ruby_xslt_reg_function, 2);
rb_define_method( cXSLT, "serve", ruby_xslt_serve, 0 );
rb_define_method( cXSLT, "save", ruby_xslt_save, 1 );
rb_define_method( cXSLT, "xml=", ruby_xslt_xml_obj_set, 1 );
rb_define_method( cXSLT, "xmlfile=", ruby_xslt_xml_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xml", ruby_xslt_xml_2str_get, 0 );
rb_define_method( cXSLT, "xmlobject", ruby_xslt_xml_2obj_get, 0 );
rb_define_method( cXSLT, "xsl=", ruby_xslt_xsl_obj_set, 1 );
rb_define_method( cXSLT, "xslfile=", ruby_xslt_xsl_obj_set_d, 1 ); // DEPRECATED
rb_define_method( cXSLT, "xsl", ruby_xslt_xsl_2str_get, 0 );
rb_define_method( cXSLT, "xslobject", ruby_xslt_xsl_2obj_get, 0 );
rb_define_method( cXSLT, "parameters=", ruby_xslt_parameters_set, 1 );
rb_define_method( cXSLT, "xsl_to_s", ruby_xslt_to_s, 0 );
rb_define_method( cXSLT, "mediaType", ruby_xslt_media_type, 0 );
#ifdef USE_ERROR_HANDLER
xmlSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
xsltSetGenericErrorFunc( NULL, ruby_xslt_error_handler );
#endif
#ifdef USE_EXSLT
exsltRegisterAll();
#endif
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.